work lab8

This commit is contained in:
Aleksey-Skvortsov 2024-06-05 12:08:56 +04:00
parent 9563a3d4e5
commit 82f8ca24b0
18 changed files with 557 additions and 79 deletions

View File

@ -8,6 +8,17 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -26,12 +26,12 @@ namespace AccordionBus.CollectionGenericObjects
_pictureWidth = picWidth;
_pictureHeight = picHeigth;
_collection = collection;
_collection.MaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount - 3;
}
public static bool operator +(AbstractCompany company, DrawningBus bus)
{
return company._collection.Insert(bus);
return company._collection?.Insert(bus, new DrawningBusEqutables()) ?? false;
}
public static bool operator -(AbstractCompany company, int position)
@ -51,7 +51,6 @@ namespace AccordionBus.CollectionGenericObjects
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackground(graphics);
for (int i = 0; i < (_collection?.MaxCount ?? 0); i++)
{
DrawningBus? obj = _collection?.Get(i);
@ -63,6 +62,8 @@ namespace AccordionBus.CollectionGenericObjects
return bitmap;
}
public void Sort(IComparer<DrawningBus?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectPosition(int position, int MaxPos, DrawningBus? bus);

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.CollectionGenericObjects
{
public class CollectionInfo : IEquatable<CollectionInfo>
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
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] : "");
}
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

@ -1,4 +1,5 @@
using System;
using AccordionBus.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -22,14 +23,14 @@ namespace AccordionBus.CollectionGenericObjects
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <returns></returns>
bool Insert(T obj);
bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null);
/// <summary>
/// вставить по позиции
/// </summary>
/// <param name="obj">добавляемый объект</param>
/// <param name="position">индекс</param>
/// <returns></returns>
bool Insert(T obj, int position);
bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null);
/// <summary>
/// удаление
/// </summary>
@ -53,5 +54,11 @@ namespace AccordionBus.CollectionGenericObjects
/// </summary>
/// <returns></returns>
IEnumerable<T> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}
}

View File

@ -1,4 +1,6 @@
using System;
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -41,27 +43,50 @@ namespace AccordionBus.CollectionGenericObjects
return _collection[position];
}
public bool Insert(T obj)
public bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null)
{
if (_collection == null || _collection.Count == _maxCount) return false;
if (_collection == null || _collection.Count == _maxCount) throw new CollectionOverflowException(Count);
foreach (var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null)
{
if (_collection == null || position < 0 || position > _maxCount) return false;
foreach (var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
_collection.Insert(position, obj);
return true;
}
public bool Remove(int position)
{
if (_collection == null || position < 0 || position >= _collection.Count) return false;
if (_collection == null || position < 0 || position >= _collection.Count) throw new PozitionOutOfCollectionException(position);
T? obj = _collection[position];
_collection[position] = null;
return true;
}
@ -73,5 +98,10 @@ namespace AccordionBus.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}
}

View File

@ -1,4 +1,6 @@
using System;
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
@ -39,12 +41,27 @@ namespace AccordionBus.CollectionGenericObjects
public T? Get(int position)
{
if (position < 0 || position >= _collection.Length) return null;
if (position < 0 || position >= _collection.Length)
{
throw new PozitionOutOfCollectionException(position);
}
return _collection[position];
}
public bool Insert(T obj)
public bool Insert(T obj, IEqualityComparer<DrawningBus?>? comparer = null)
{
foreach(var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
for (int i = 0; i < _collection.Length; i++)
{
if (_collection[i] == null)
@ -53,12 +70,24 @@ namespace AccordionBus.CollectionGenericObjects
return true;
}
}
return false;
throw new CollectionOverflowException(Count);
}
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<DrawningBus?>? comparer = null)
{
if (position < 0 || position >= _collection.Length) { return false; }
if (position < 0 || position >= _collection.Length) throw new PozitionOutOfCollectionException(position);
foreach (var drawningBus in _collection)
{
if (obj is DrawningBus objdr && drawningBus is DrawningBus bus)
{
if (comparer.Equals(objdr, bus)) throw new ObjectExistsException();
}
else if (obj is DrawningAccordionBus objdra && drawningBus is DrawningAccordionBus busa)
{
if (comparer.Equals(objdra, busa)) throw new ObjectExistsException();
}
}
if (_collection[position] == null)
{
@ -85,14 +114,14 @@ namespace AccordionBus.CollectionGenericObjects
}
}
}
return false;
throw new CollectionOverflowException(Count);
}
public bool Remove(int position)
{
if (position < 0 || position >= _collection.Length) { return false;}
if (position < 0 || position >= _collection.Length) throw new PozitionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T? obj = _collection[position];
_collection[position] = null;
return true;
}
@ -104,5 +133,10 @@ namespace AccordionBus.CollectionGenericObjects
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}
}

View File

@ -1,4 +1,5 @@
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -11,9 +12,9 @@ namespace AccordionBus.CollectionGenericObjects
public class StorageCollection<T>
where T: DrawningBus
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storage;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storage;
public List<string> Keys => _storage.Keys.ToList();
public List<CollectionInfo> Keys => _storage.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage";
@ -23,35 +24,37 @@ namespace AccordionBus.CollectionGenericObjects
public StorageCollection()
{
_storage = new Dictionary<string, ICollectionGenericObjects<T>>();
_storage = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
if (_storage.ContainsKey(name) || name == "") return;
CollectionInfo info = new CollectionInfo(name, collectionType, "");
_storage[name] = CreateCollection(collectionType);
if (_storage.ContainsKey(info) || info.Name == "") return;
_storage[info] = CreateCollection(info.CollectionType);
}
public void DelCollection(string name)
{
_storage.Remove(name);
_storage.Remove(new CollectionInfo(name, CollectionType.None, ""));
}
public ICollectionGenericObjects<T>? this[string name]
{
get
{
if (!_storage.ContainsKey(name)) return null;
return _storage[name];
if (!_storage.ContainsKey(new CollectionInfo(name, CollectionType.None, ""))) return null;
return _storage[new CollectionInfo(name, CollectionType.None, "")];
}
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storage.Count == 0)
{
return false;
throw new InvalidOperationException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -60,7 +63,7 @@ namespace AccordionBus.CollectionGenericObjects
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storage)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storage)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
@ -71,8 +74,6 @@ namespace AccordionBus.CollectionGenericObjects
}
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())
@ -87,57 +88,68 @@ namespace AccordionBus.CollectionGenericObjects
}
writer.Write(sb);
}
return true;
}
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не существует");
}
using (StreamReader reader = File.OpenText(filename))
{
string str = reader.ReadLine();
if (str == null || str.Length == 0)
{
return false;
throw new InvalidOperationException("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new InvalidOperationException("В файле не верные данные");
}
_storage.Clear();
string strs = "";
while ((strs = reader.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new InvalidOperationException("Не удалось определить информацию об коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
return false;
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBus() is T bus)
{
if (!collection.Insert(bus))
try
{
return false;
if (!collection.Insert(bus))
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию " + record[2]);
}
}
catch(ObjectExistsException ex)
{
throw new InvalidOperationException(ex.Message);
}
catch (CollectionOverflowException ex)
{
throw new InvalidOperationException("Коллекция переполнена", ex);
}
}
}
_storage.Add(record[0], collection);
_storage.Add(collectionInfo, collection);
}
return true;
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.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;
if (x.EntityBus.BodyColor != y.EntityBus.BodyColor)
{
var redCompare = x.EntityBus.BodyColor.R.CompareTo(y.EntityBus.BodyColor.R);
if (redCompare != 0) return redCompare;
var blueCompare = x.EntityBus.BodyColor.B.CompareTo(y.EntityBus.BodyColor.B);
if (blueCompare != 0) return blueCompare;
return x.EntityBus.BodyColor.G.CompareTo(y.EntityBus.BodyColor.G);
}
var speedCompare = x.EntityBus.Speed.CompareTo(y.EntityBus.Speed);
if (speedCompare != 0) return speedCompare;
return x.EntityBus.Weight.CompareTo(y.EntityBus.Weight);
}
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
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

@ -0,0 +1,47 @@
using AccordionBus.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Drawnings
{
public class DrawningBusEqutables : 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 DrawningAccordionBus xa && y is DrawningAccordionBus ya)
{
if (xa.EntityBus is EntityAccordionBus ex && ya.EntityBus is EntityAccordionBus ey)
{
if (ex.AdditionalColor != ey.AdditionalColor) return false;
if (ex.FiveDoors != ey.FiveDoors) return false;
if (ex.Hatch != ey.Hatch) return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBus? obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -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 AccordionBus.Exceptions
{
[Serializable]
public class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count : " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

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 AccordionBus.Exceptions
{
public class ObjectExistsException : ApplicationException
{
public ObjectExistsException() : base("Такой объект уже есть в соллекции") { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
public ObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AccordionBus.Exceptions
{
[Serializable]
public 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 context) : base(info, context) { }
}
}

View File

@ -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 AccordionBus.Exceptions
{
[Serializable]
public class PozitionOutOfCollectionException : ApplicationException
{
public PozitionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PozitionOutOfCollectionException() : base() { }
public PozitionOutOfCollectionException(string message) : base(message) { }
public PozitionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PozitionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelTools.SuspendLayout();
@ -68,7 +70,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(948, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(234, 725);
groupBoxTools.Size = new Size(234, 801);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -178,6 +180,8 @@
//
// panelTools
//
panelTools.Controls.Add(buttonSortByColor);
panelTools.Controls.Add(buttonSortByType);
panelTools.Controls.Add(buttonAddBus);
panelTools.Controls.Add(buttonRefresh);
panelTools.Controls.Add(maskedTextBox);
@ -187,7 +191,7 @@
panelTools.Enabled = false;
panelTools.Location = new Point(3, 396);
panelTools.Name = "panelTools";
panelTools.Size = new Size(228, 326);
panelTools.Size = new Size(228, 402);
panelTools.TabIndex = 7;
//
// buttonAddBus
@ -202,7 +206,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(9, 265);
buttonRefresh.Location = new Point(9, 226);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(207, 54);
buttonRefresh.TabIndex = 6;
@ -212,7 +216,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(9, 112);
maskedTextBox.Location = new Point(9, 73);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(207, 27);
@ -221,7 +225,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(9, 205);
buttonGoToCheck.Location = new Point(9, 166);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(207, 54);
buttonGoToCheck.TabIndex = 5;
@ -231,7 +235,7 @@
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(9, 145);
buttonRemoveBus.Location = new Point(9, 106);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(207, 54);
buttonRemoveBus.TabIndex = 4;
@ -244,7 +248,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(948, 725);
pictureBox.Size = new Size(948, 801);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -289,11 +293,31 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(9, 346);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(207, 54);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортирока по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(9, 286);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(207, 54);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormBusCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1182, 753);
ClientSize = new Size(1182, 829);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -339,5 +363,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,5 +1,7 @@
using AccordionBus.CollectionGenericObjects;
using AccordionBus.Drawnings;
using AccordionBus.Exceptions;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -19,10 +21,13 @@ namespace AccordionBus
private AbstractCompany? _company = null;
public FormBusCollection()
private readonly ILogger _logger;
public FormBusCollection(ILogger<FormBusCollection> logger)
{
InitializeComponent();
_storageCollection = new StorageCollection<DrawningBus>();
_logger = logger;
}
private void comboBoxSelectedCompany_SelectedIndexChanged(object sender, EventArgs e)
@ -43,14 +48,24 @@ namespace AccordionBus
bus.SetPictureSize(pictureBox.Width, pictureBox.Height);
if (_company + bus)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + bus)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект добавлен в коллекцию, " + bus.GetDataForSave());
}
}
else
catch (ObjectExistsException ex)
{
MessageBox.Show("Объект не удалось добавить");
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {message}", ex.Message);
}
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {message}", ex.Message);
}
}
@ -62,14 +77,24 @@ namespace AccordionBus
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos)
try
{
MessageBox.Show("Объект удалён");
pictureBox.Image = _company.Show();
if (_company - pos)
{
MessageBox.Show("Объект удалён");
pictureBox.Image = _company.Show();
_logger.LogInformation("Объект по позиции {0} удалён", pos);
}
}
else
catch (PozitionOutOfCollectionException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Не удалось удалить объект. Не верно указана позиция");
_logger.LogError("Ошибка: {message}", ex.Message);
}
catch (ObjectNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект, его не существует");
_logger.LogError("Ошибка: {message}", ex.Message);
}
}
@ -79,10 +104,17 @@ namespace AccordionBus
DrawningBus? bus = null;
int counter = 100;
while (bus == null && counter > 0)
try
{
bus = _company.GetRandomObject();
counter--;
while (bus == null && counter > 0)
{
bus = _company.GetRandomObject();
counter--;
}
}
catch (PozitionOutOfCollectionException ex)
{
_logger.LogError("Ошибка: {message}", ex.Message);
}
if (bus == null) return;
@ -115,8 +147,10 @@ namespace AccordionBus
else if (radioButtonList.Checked) collectionType = CollectionType.List;
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавлена новая коллекция {0}", textBoxCollectionName.Text);
textBoxCollectionName.Text = "";
RefreshListBoxItems();
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
@ -129,10 +163,12 @@ namespace AccordionBus
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RefreshListBoxItems();
MessageBox.Show("Компания удалена");
_logger.LogInformation("Компания удалена");
}
else
{
MessageBox.Show("Не удалось удалить компанию");
_logger.LogError("Ошибка: не удалось удалить компанию");
}
}
@ -158,6 +194,7 @@ namespace AccordionBus
case "Станция":
_company = new BusStation(pictureBox.Width, pictureBox.Height, collection);
pictureBox.Image = _company.Show();
break;
}
@ -169,7 +206,7 @@ namespace AccordionBus
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);
@ -181,15 +218,18 @@ namespace AccordionBus
{
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);
}
}
}
@ -198,18 +238,39 @@ namespace AccordionBus
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка из файла {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBox.Show(ex.Message, "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareBuses(new DrawningBusCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareBuses(new DrawningBusCompareByColor());
}
private void CompareBuses(IComparer<DrawningBus?> comparer)
{
if (_company == null) return;
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace AccordionBus
{
internal static class Program
@ -10,8 +16,24 @@ namespace AccordionBus
{
// 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.Debug);
option.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("C:\\Users\\Professional\\Desktop\\labs\\8\\AccordionBus\\AccordionBus\\serilog.json")
.Build())
.CreateLogger());
});
}
}
}

View File

@ -0,0 +1,18 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs\\log.txt",
"outputTemplate": "[{Level:u}] [{Timestamp:yyyy-MM-dd HH:mm:ss.ffff}] {Message:1j}{NewLine}{Exception}"
}
}
],
"Properties": {
"Application": "Sample"
}
}
}