2 Commits
lab6 ... lab8

Author SHA1 Message Date
Efi
ed57ab5202 Лабораторная работа 8 2023-12-26 23:38:54 +04:00
Efi
7c2ac102e0 Лабораторная работа 7 2023-12-26 19:28:29 +04:00
14 changed files with 455 additions and 76 deletions

View File

@@ -8,6 +8,21 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DependencyInjection.AutoRegistration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.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>
@@ -23,4 +38,8 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,60 @@
using AirBomber.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
namespace AirBomber.Generics
{
internal class DrawingWarAirplaneEqutables : IEqualityComparer<DrawingWarAirplane?>
{
public bool Equals(DrawingWarAirplane? x, DrawingWarAirplane? y)
{
if (x == null || x.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarAirplane.Speed != y.EntityWarAirplane.Speed)
{
return false;
}
if (x.EntityWarAirplane.Weight != y.EntityWarAirplane.Weight)
{
return false;
}
if (x.EntityWarAirplane.BodyColor != y.EntityWarAirplane.BodyColor)
{
return false;
}
if (x is DrawingAirBomber && y is DrawingAirBomber)
{
EntityAirBomber EntityX = (EntityAirBomber)x.EntityWarAirplane;
EntityAirBomber EntityY = (EntityAirBomber)y.EntityWarAirplane;
if (EntityX.FuelTank != EntityY.FuelTank)
return false;
if (EntityX.Bombs != EntityY.Bombs)
return false;
if (EntityX.Bombs && EntityX.FuelTank != EntityY.FuelTank && EntityY.Bombs)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarAirplane obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -46,6 +46,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
panelCollection.SuspendLayout();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
@@ -54,6 +56,8 @@
//
// panelCollection
//
panelCollection.Controls.Add(ButtonSortByColor);
panelCollection.Controls.Add(ButtonSortByType);
panelCollection.Controls.Add(panelObject);
panelCollection.Controls.Add(Tools);
panelCollection.Controls.Add(buttonRefreshCollection);
@@ -63,7 +67,7 @@
panelCollection.Dock = DockStyle.Right;
panelCollection.Location = new Point(617, 24);
panelCollection.Name = "panelCollection";
panelCollection.Size = new Size(183, 456);
panelCollection.Size = new Size(183, 574);
panelCollection.TabIndex = 0;
//
// panelObject
@@ -125,7 +129,7 @@
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(3, 395);
buttonRefreshCollection.Location = new Point(3, 519);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(174, 43);
buttonRefreshCollection.TabIndex = 2;
@@ -135,7 +139,7 @@
//
// buttonRemove
//
buttonRemove.Location = new Point(3, 336);
buttonRemove.Location = new Point(3, 468);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(174, 31);
buttonRemove.TabIndex = 2;
@@ -145,7 +149,7 @@
//
// buttonAdd
//
buttonAdd.Location = new Point(3, 255);
buttonAdd.Location = new Point(3, 381);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(174, 31);
buttonAdd.TabIndex = 2;
@@ -155,7 +159,7 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(3, 307);
maskedTextBoxNumber.Location = new Point(3, 439);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(174, 23);
maskedTextBoxNumber.TabIndex = 0;
@@ -165,7 +169,7 @@
pictureBoxCollection.Dock = DockStyle.Left;
pictureBoxCollection.Location = new Point(0, 24);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(617, 456);
pictureBoxCollection.Size = new Size(617, 574);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
@@ -207,11 +211,31 @@
//
saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(3, 266);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(174, 40);
ButtonSortByType.TabIndex = 5;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(3, 312);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(174, 40);
ButtonSortByColor.TabIndex = 6;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormWarAirplaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 480);
ClientSize = new Size(800, 598);
Controls.Add(pictureBoxCollection);
Controls.Add(panelCollection);
Controls.Add(menuStrip);
@@ -249,5 +273,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@@ -10,16 +10,20 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AirBomber.Exceptions;
using Microsoft.Extensions.Logging;
namespace AirBomber
{
public partial class FormWarAirplaneCollection : Form
{
private readonly WarAirplaneGenericStorage _storage;
public FormWarAirplaneCollection()
private readonly ILogger _logger;
public FormWarAirplaneCollection(ILogger<FormWarAirplaneCollection> logger)
{
InitializeComponent();
_storage = new WarAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
@@ -28,7 +32,7 @@ namespace AirBomber
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
@@ -53,11 +57,13 @@ namespace AirBomber
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ButtonDelObject__Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
@@ -66,8 +72,9 @@ namespace AirBomber
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {textBoxStorageName.Text}");
}
_logger.LogWarning("Отмена удаления набора");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@@ -96,16 +103,23 @@ namespace AirBomber
form.Show();
Action<DrawingWarAirplane>? warAirplaneDelegate = new((m) =>
{
bool q = obj + m;
if (q == true)
try
{
bool q = obj + m;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
_logger.LogInformation($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
@@ -119,6 +133,7 @@ namespace AirBomber
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@@ -130,17 +145,28 @@ namespace AirBomber
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowWarAirplane();
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
{
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch(WarAirplaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из {listBoxStorages.SelectedItem.ToString()}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@@ -161,15 +187,18 @@ namespace AirBomber
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
@@ -179,22 +208,44 @@ namespace AirBomber
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
else
catch(Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
private void CompareWarAirplane(IComparer<DrawingWarAirplane?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareWarAirplane(new WarAirplaneCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareWarAirplane(new WarAirplaneCompareByColor());
}
}

View File

@@ -1,3 +1,28 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Log = Serilog.Log;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Json;
using System;
using System.IO;
using System.Windows.Forms;
namespace AirBomber
{
internal static class Program
@@ -6,12 +31,48 @@ namespace AirBomber
/// 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 FormWarAirplaneCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormWarAirplaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
string path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
services.AddSingleton<FormWarAirplaneCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: path + "\\appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
logger.Information("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>");
});
}
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -8,68 +9,62 @@ namespace AirBomber.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
public int startPointer = 0;
public readonly int _maxCount;
public int countMax = 0;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
countMax = count;
}
public bool Insert(T WarAirplane)
public bool Insert(T car, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(WarAirplane, 0);
if (_places.Count == countMax) { throw new StorageOverflowException(countMax); }
Insert(car, 0, equal);
return true;
}
public bool Insert(T WarAirplane, int position)
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public bool Insert(T warAirplane, int position, IEqualityComparer<T>? equal = null)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
_places.Insert(position, WarAirplane);
if (_places.Count == countMax)
throw new StorageOverflowException(countMax);
if (!(position >= 0 && position <= Count)) return false;
if (equal != null)
{
if (_places.Contains(warAirplane, equal))
throw new ArgumentException(nameof(warAirplane));
}
_places.Insert(position, warAirplane);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
if (!(position >= 0 && position < Count))
throw new WarAirplaneNotFoundException(position);
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position >= _maxCount)
{
if (!(position >= 0 && position < Count))
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
if (!(position >= 0 && position < Count && _places.Count < countMax))
return;
}
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetWarAirplane(int? maxWarAirplane = null)
@@ -83,6 +78,11 @@ namespace AirBomber.Generics
}
}
}
public T? Get(int position)
{
if (position < Count && position >= 0) { return _places[position]; }
return null;
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AirBomber.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе" +
$"превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
public StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class WarAirplaneCollectionInfo : IEquatable<WarAirplaneCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public WarAirplaneCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(WarAirplaneCollectionInfo? other)
{
if (other == null || other.Name == null)
throw new ArgumentNullException(nameof(other));
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.DrawingObjects;
namespace AirBomber
{
internal class WarAirplaneCompareByColor : IComparer<DrawingWarAirplane?>
{
public int Compare(DrawingWarAirplane? x, DrawingWarAirplane? y)
{
if (x == null || x.EntityWarAirplane == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityWarAirplane == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityWarAirplane.BodyColor.Name != y.EntityWarAirplane.BodyColor.Name)
{
return x.EntityWarAirplane.BodyColor.Name.CompareTo(y.EntityWarAirplane.BodyColor.Name);
}
var speedCompare = x.EntityWarAirplane.Speed.CompareTo(y.EntityWarAirplane.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityWarAirplane.Weight.CompareTo(y.EntityWarAirplane.Weight);
}
}
}

View File

@@ -0,0 +1,35 @@
using AirBomber.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class WarAirplaneCompareByType : IComparer<DrawingWarAirplane?>
{
public int Compare(DrawingWarAirplane? x, DrawingWarAirplane? y)
{
if (x == null || x.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityWarAirplane.Speed.CompareTo(y.EntityWarAirplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarAirplane.Weight.CompareTo(y.EntityWarAirplane.Weight);
}
}
}

View File

@@ -1,5 +1,6 @@
using AirBomber.MovementStrategy;
using AirBomber.DrawingObjects;
using AirBomber.Generics;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -19,6 +20,7 @@ namespace AirBomber.Generics
private readonly int _placeSizeHeight = 110;
private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetWarAirplanes => _collection.GetWarAirplane();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public WarAirplaneGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
@@ -34,7 +36,7 @@ namespace AirBomber.Generics
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
return collect?._collection.Insert(obj, new DrawingWarAirplaneEqutables()) ?? false;
}
public static bool operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.DrawingObjects;
@@ -10,9 +11,9 @@ namespace AirBomber.Generics
{
internal class WarAirplaneGenericStorage
{
readonly Dictionary<string, WarAirplaneGenericCollection<DrawingWarAirplane,
readonly Dictionary<WarAirplaneCollectionInfo, WarAirplaneGenericCollection<DrawingWarAirplane,
DrawingObjectWarAirplane>> _warAirplaneStorages;
public List<string> Keys => _warAirplaneStorages.Keys.ToList();
public List<WarAirplaneCollectionInfo> Keys => _warAirplaneStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
@@ -20,35 +21,36 @@ namespace AirBomber.Generics
private static readonly char _separatorForObject = ':';
public WarAirplaneGenericStorage(int pictureWidth, int pictureHeight)
{
_warAirplaneStorages = new Dictionary<string, WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>>();
_warAirplaneStorages = new Dictionary<WarAirplaneCollectionInfo, WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_warAirplaneStorages.ContainsKey(name))
if (_warAirplaneStorages.ContainsKey(new WarAirplaneCollectionInfo(name, string.Empty)))
{
return;
}
_warAirplaneStorages.Add(name, new WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>(_pictureWidth, _pictureHeight));
_warAirplaneStorages.Add(new WarAirplaneCollectionInfo(name,string.Empty), new WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_warAirplaneStorages.ContainsKey(name))
if (!_warAirplaneStorages.ContainsKey(new WarAirplaneCollectionInfo(name, string.Empty)))
{
return;
}
_warAirplaneStorages.Remove(name);
_warAirplaneStorages.Remove(new WarAirplaneCollectionInfo(name, string.Empty));
}
public WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>? this[string ind]
{
get
{
if (_warAirplaneStorages.ContainsKey(ind))
WarAirplaneCollectionInfo indObj = new WarAirplaneCollectionInfo(ind, string.Empty);
if (_warAirplaneStorages.ContainsKey(indObj))
{
return _warAirplaneStorages[ind];
return _warAirplaneStorages[indObj];
}
return null;
}
@@ -61,7 +63,7 @@ namespace AirBomber.Generics
File.Delete(filename);
}
StringBuilder data = new();
foreach(KeyValuePair<string,WarAirplaneGenericCollection<
foreach(KeyValuePair<WarAirplaneCollectionInfo,WarAirplaneGenericCollection<
DrawingWarAirplane,DrawingObjectWarAirplane>> record in _warAirplaneStorages)
{
StringBuilder records = new();
@@ -69,11 +71,11 @@ namespace AirBomber.Generics
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if(data.Length == 0)
{
return false;
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes($"WarAirplaneStorage" +
@@ -85,7 +87,7 @@ namespace AirBomber.Generics
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
@@ -101,11 +103,11 @@ namespace AirBomber.Generics
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("WarAirplaneStorage"))
{
return false;
throw new Exception("Неверный формат данных");
}
_warAirplaneStorages.Clear();
foreach (string data in strs)
@@ -126,11 +128,11 @@ namespace AirBomber.Generics
{
if(!(collection + warAirplane))
{
return false;
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_warAirplaneStorages.Add(record[0], collection);
_warAirplaneStorages.Add(new WarAirplaneCollectionInfo(record[0], string.Empty), collection);
}
return true;
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AirBomber.Exceptions
{
[Serializable]
internal class WarAirplaneNotFoundException : ApplicationException
{
public WarAirplaneNotFoundException(int i) : base($"Не найден объект по" +
$"позиции {i}") { }
public WarAirplaneNotFoundException() : base() { }
public WarAirplaneNotFoundException(string message) : base(message) { }
public WarAirplaneNotFoundException(string message, Exception exception) : base(message, exception) { }
public WarAirplaneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Users\\user\\source\\repos\\PIbd-23_Bakshaeva_E.A._AirBomber_Base\\AirBomber\\AirBomber\\Logs\\log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AirBomber"
}
}
}