3 Commits
lab6 ... lab7

Author SHA1 Message Date
Efi
1ca1dd6513 Changes: Throw exception 2024-02-13 23:37:14 +04:00
Efi
13465da48f Changes: ButtonAddWarAirplane_Click StorageOverflowException 2023-12-26 23:40:33 +04:00
Efi
7c2ac102e0 Лабораторная работа 7 2023-12-26 19:28:29 +04:00
9 changed files with 222 additions and 82 deletions

View File

@@ -8,6 +8,37 @@
<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.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<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" />
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageReference Include="System.Text.Encodings.Web" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -10,6 +10,10 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace AirBomber
{
@@ -42,9 +46,9 @@ namespace AirBomber
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
private void ButtonAddObject_Click(object sender, EventArgs e) //работает
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
if (string.IsNullOrEmpty(textBoxStorageName.Text.ToString() ?? string.Empty))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
@@ -53,6 +57,7 @@ namespace AirBomber
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
private void ButtonDelObject__Click(object sender, EventArgs e)
{
@@ -60,14 +65,18 @@ namespace AirBomber
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
if (MessageBox.Show($"Удалить набор {listBoxStorages.SelectedItem.ToString() ?? string.Empty}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
if (listBoxStorages.SelectedIndex == null)
{
return;
}
Log.Information($"Удален набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
?? string.Empty);
ReloadObjects();
}
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@@ -87,37 +96,46 @@ namespace AirBomber
if (obj == null)
{
return;
}
FormWarAirplaneConfig form = new FormWarAirplaneConfig();
form.Show();
Action<DrawingWarAirplane>? warAirplaneDelegate = new((m) =>
{
bool q = obj + m;
if (q == true)
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowWarAirplane();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
//int pos = Convert.ToInt32(maskedTextBoxNumber.Text); // TO DO
var q = obj + m;
if(q != -1)
{
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
{
MessageBox.Show("Не удалось добавить объект");
Log.Information("Не удалось добавить объект");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
Action<Color>? ColorDelegate = new((m) =>
{
MessageBox.Show(m.ToString());
});
form.AddEvent(warAirplaneDelegate);
}
private void ButtonRemoveWarAirplane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
try
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
@@ -125,6 +143,8 @@ namespace AirBomber
string.Empty];
if (obj == null)
{
Log.Information("Не удалось удалить объект. Объект равен null");
MessageBox.Show("Не удалось удалить объект");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
@@ -132,15 +152,27 @@ namespace AirBomber
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
if (maskedTextBoxNumber.Text == null)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект номер {pos} из набора {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
catch (WarAirplaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@@ -161,15 +193,18 @@ namespace AirBomber
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Данные загружены в файл {saveFileDialog.FileName}");
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
@@ -179,19 +214,22 @@ 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);
}
Log.Information($"Данные загружены из файла {openFileDialog.FileName}");
}
else
catch(Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}

View File

@@ -1,3 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace AirBomber
{
internal static class Program
@@ -6,12 +15,27 @@ 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();
ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormWarAirplaneCollection());
}
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -18,31 +19,24 @@ namespace AirBomber.Generics
_maxCount = count;
_places = new List<T?>(count);
}
public bool Insert(T WarAirplane)
public int Insert(T WarAirplane)
{
if (_places.Count == _maxCount)
{
return false;
}
if (_places.Count == _maxCount) { throw new StorageOverflowException(_maxCount); }
Insert(WarAirplane, 0);
return true;
return 1;
}
public bool Insert(T WarAirplane, int position)
public int Insert(T WarAirplane, int position)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count)) return -1;
_places.Insert(position, WarAirplane);
return true;
return position;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
throw new WarAirplaneNotFoundException(position);
_places.RemoveAt(position);
return true;
@@ -53,23 +47,16 @@ namespace AirBomber.Generics
{
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))
{
return;
}
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetWarAirplane(int? maxWarAirplane = null)
@@ -83,6 +70,12 @@ 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

@@ -13,6 +13,7 @@ namespace AirBomber.Generics
where T : DrawingWarAirplane
where U : IMoveableObject
{
public IEnumerable<T?> GetWarAirplane => _collection.GetWarAirplane();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 110;
@@ -27,28 +28,26 @@ namespace AirBomber.Generics
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static bool operator +(WarAirplaneGenericCollection<T, U> collect, T?
public static int operator +(WarAirplaneGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return false;
return -1;
}
return collect?._collection.Insert(obj) ?? false;
collect._collection.Insert(obj);
return 1;
}
public static bool operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)
public static T? operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return true;
collect._collection.Remove(pos);
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
public Bitmap ShowWarAirplane()
{
@@ -76,17 +75,16 @@ namespace AirBomber.Generics
}
private void DrawObjects(Graphics g)
{
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
int i = 0;
foreach (var warAirplane in _collection.GetWarAirplane()) {
if (warAirplane != null)
{
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
warAirplane.SetPosition((numPlacesInRow - 1 - (i % numPlacesInRow)) * _placeSizeWidth,
i / numPlacesInRow * _placeSizeHeight);
warAirplane.DrawTransport(g);
warAirplane.SetPosition((i % numPlacesInRow) * _placeSizeWidth + _placeSizeWidth / 20, _placeSizeHeight * (i / numPlacesInRow) + _placeSizeHeight / 10);
warAirplane.DrawTransport(g);
}
i++;
}
i+=1;
}
}
}

View File

@@ -73,7 +73,7 @@ namespace AirBomber.Generics
}
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 +85,7 @@ namespace AirBomber.Generics
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
@@ -101,11 +101,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)
@@ -124,9 +124,10 @@ namespace AirBomber.Generics
DrawingWarAirplane? warAirplane = elem?.CreateDrawingWarAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if(warAirplane != null)
{
if(!(collection + warAirplane))
if(collection + warAirplane == -1)
{
return false;
throw new Exception("Ошибка добавления в коллекцию");
}
}
}

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,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.txt" }
}
],
"Properties": {
"Application": "Sample"
}
}
}