reflections

This commit is contained in:
Алишер Бустонов 2023-05-21 16:53:29 +04:00
parent 9815574024
commit 714c783904
60 changed files with 1356 additions and 231 deletions

2
.gitignore vendored
View File

@ -13,6 +13,8 @@
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
ImplementationExtensions
BusinessLogicExtensions
# Mono auto generated files
mono_crash.*

401
.gitignore.bak Normal file
View File

@ -0,0 +1,401 @@
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
ImplementationExtensions
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

View File

@ -15,11 +15,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FishFactoryListImplement",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FishFactoryFileImplement", "FishFactoryFileImplement\FishFactoryFileImplement.csproj", "{DE30E611-C52D-4BDB-8CD1-2331EC5D24F8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FishFactoryDatabaseImplement", "FishFactoryDatabaseImplement\FishFactoryDatabaseImplement.csproj", "{F5D03645-1AAA-492E-87CD-9903C526FD7B}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FishFactoryRestApi", "FishFactoryRestApi\FishFactoryRestApi.csproj", "{9781080B-C8D4-47F4-B30D-B46E30AE1E24}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FishFactoryRestApi", "FishFactoryRestApi\FishFactoryRestApi.csproj", "{9781080B-C8D4-47F4-B30D-B46E30AE1E24}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FishFactoryClientApp", "FishFactoryClientApp\FishFactoryClientApp.csproj", "{92455D8F-A94F-498B-853E-479DCF272DED}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FishFactoryClientApp", "FishFactoryClientApp\FishFactoryClientApp.csproj", "{92455D8F-A94F-498B-853E-479DCF272DED}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FishFactoryDatabaseImplement", "FishFactoryDatabaseImplement\FishFactoryDatabaseImplement.csproj", "{F32563DB-FA92-4F7A-A138-277AE26185E6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -51,10 +51,6 @@ Global
{DE30E611-C52D-4BDB-8CD1-2331EC5D24F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DE30E611-C52D-4BDB-8CD1-2331EC5D24F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DE30E611-C52D-4BDB-8CD1-2331EC5D24F8}.Release|Any CPU.Build.0 = Release|Any CPU
{F5D03645-1AAA-492E-87CD-9903C526FD7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F5D03645-1AAA-492E-87CD-9903C526FD7B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F5D03645-1AAA-492E-87CD-9903C526FD7B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F5D03645-1AAA-492E-87CD-9903C526FD7B}.Release|Any CPU.Build.0 = Release|Any CPU
{9781080B-C8D4-47F4-B30D-B46E30AE1E24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9781080B-C8D4-47F4-B30D-B46E30AE1E24}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9781080B-C8D4-47F4-B30D-B46E30AE1E24}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -63,6 +59,10 @@ Global
{92455D8F-A94F-498B-853E-479DCF272DED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92455D8F-A94F-498B-853E-479DCF272DED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92455D8F-A94F-498B-853E-479DCF272DED}.Release|Any CPU.Build.0 = Release|Any CPU
{F32563DB-FA92-4F7A-A138-277AE26185E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F32563DB-FA92-4F7A-A138-277AE26185E6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F32563DB-FA92-4F7A-A138-277AE26185E6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F32563DB-FA92-4F7A-A138-277AE26185E6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -0,0 +1,98 @@
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.StoragesContracts;
using FishFactoryDataModels;
using Microsoft.Extensions.Logging;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace FishFactoryBusinessLogic.BusinessLogics
{
public class BackUpLogic : IBackUpLogic
{
private readonly ILogger _logger;
private readonly IBackUpInfo _backUpInfo;
public BackUpLogic(ILogger<BackUpLogic> logger, IBackUpInfo backUpInfo)
{
_logger = logger;
_backUpInfo = backUpInfo;
}
public void CreateBackUp(BackUpSaveBindingModel model)
{
if (_backUpInfo == null)
{
return;
}
try
{
_logger.LogDebug("Clear folder");
// зачистка папки и удаление старого архива
var dirInfo = new DirectoryInfo(model.FolderName);
if (dirInfo.Exists)
{
foreach (var file in dirInfo.GetFiles())
{
file.Delete();
}
}
_logger.LogDebug("Delete archive");
string fileName = $"{model.FolderName}.zip";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
// берем метод для сохранения
_logger.LogDebug("Get assembly");
var typeIId = typeof(IId);
var assembly = typeIId.Assembly;
if (assembly == null)
{
throw new ArgumentNullException("Сборка не найдена", nameof(assembly));
}
var types = assembly.GetTypes();
var method = GetType().GetMethod("SaveToFile", BindingFlags.NonPublic | BindingFlags.Instance);
_logger.LogDebug("Find {count} types", types.Length);
foreach (var type in types)
{
if (type.IsInterface && type.GetInterface(typeIId.Name) != null)
{
var modelType = _backUpInfo.GetTypeByModelInterface(type.Name);
if (modelType == null)
{
throw new InvalidOperationException($"Не найден класс-модель для {type.Name}");
}
_logger.LogDebug("Call SaveToFile method for {name} type", type.Name);
// вызываем метод на выполнение
method?.MakeGenericMethod(modelType).Invoke(this, new object[] { model.FolderName });
}
}
_logger.LogDebug("Create zip and remove folder");
// архивируем
ZipFile.CreateFromDirectory(model.FolderName, fileName);
// удаляем папку
dirInfo.Delete(true);
}
catch (Exception)
{
throw;
}
}
private void SaveToFile<T>(string folderName) where T : class, new()
{
var records = _backUpInfo.GetList<T>();
if (records == null)
{
_logger.LogWarning("{type} type get null list", typeof(T).Name);
return;
}
var jsonFormatter = new DataContractJsonSerializer(typeof(List<T>));
using var fs = new FileStream(string.Format("{0}/{1}.json", folderName, typeof(T).Name), FileMode.OpenOrCreate);
jsonFormatter.WriteObject(fs, records);
}
}
}

View File

@ -0,0 +1,25 @@
namespace FishFactoryContracts.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Title { get; private set; }
public bool Visible { get; private set; }
public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; }
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false)
{
Title = title;
Visible = visible;
Width = width;
GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize;
}
}
}

View File

@ -0,0 +1,21 @@
namespace FishFactoryContracts.Attributes
{
public enum GridViewAutoSize
{
NotSet = 0,
None = 1,
ColumnHeader = 2,
AllCellsExceptHeader = 4,
AllCells = 6,
DisplayedCellsExceptHeader = 8,
DisplayedCells = 10,
Fill = 16
}
}

View File

@ -0,0 +1,7 @@
namespace FishFactoryContracts.BindingModels
{
public class BackUpSaveBindingModel
{
public string FolderName { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,9 @@
using FishFactoryContracts.BindingModels;
namespace FishFactoryContracts.BusinessLogicsContracts
{
public interface IBackUpLogic
{
void CreateBackUp(BackUpSaveBindingModel model);
}
}

View File

@ -0,0 +1,61 @@
using Microsoft.Extensions.Logging;
namespace FishFactoryContracts.DI
{
public class DependencyManager
{
private readonly IDependencyContainer _dependencyManager;
private static DependencyManager? _manager;
private static readonly object _locjObject = new();
private DependencyManager()
{
_dependencyManager = new UnityDependencyContainer();
}
public static DependencyManager Instance { get { if (_manager == null) { lock (_locjObject) { _manager = new DependencyManager(); } } return _manager; } }
/// <summary>
/// Иницализация библиотек, в которых идут установки зависомстей
/// </summary>
public static void InitDependency()
{
var ext = ServiceProviderLoader.GetImplementationExtensions();
if (ext == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
// регистрируем зависимости
ext.RegisterServices();
}
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
public void AddLogging(Action<ILoggingBuilder> configure) => _dependencyManager.AddLogging(configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T, U>(bool isSingle = false) where U : class, T where T : class => _dependencyManager.RegisterType<T, U>(isSingle);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
public void RegisterType<T>(bool isSingle = false) where T : class => _dependencyManager.RegisterType<T>(isSingle);
/// <summary>
/// Получение класса со всеми зависмостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Resolve<T>() => _dependencyManager.Resolve<T>();
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.Extensions.Logging;
namespace FishFactoryContracts.DI
{
public interface IDependencyContainer
{
/// <summary>
/// Регистрация логгера
/// </summary>
/// <param name="configure"></param>
void AddLogging(Action<ILoggingBuilder> configure);
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T, U>(bool isSingle) where U : class, T where T : class;
/// <summary>
/// Добавление зависимости
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isSingle"></param>
void RegisterType<T>(bool isSingle) where T : class;
/// <summary>
/// Получение класса со всеми зависимостями
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Resolve<T>();
}
}

View File

@ -0,0 +1,11 @@
namespace FishFactoryContracts.DI
{
public interface IImplementationExtension
{
public int Priority { get; }
/// <summary>
/// Регистрация сервисов
/// </summary>
public void RegisterServices();
}
}

View File

@ -0,0 +1,57 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FishFactoryContracts.DI
{
public class ServiceDependencyContainer : IDependencyContainer
{
private ServiceProvider? _serviceProvider;
private readonly ServiceCollection _serviceCollection;
public ServiceDependencyContainer()
{
_serviceCollection = new ServiceCollection();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_serviceCollection.AddLogging(configure);
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T, U>();
}
else
{
_serviceCollection.AddTransient<T, U>();
}
_serviceProvider = null;
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_serviceCollection.AddSingleton<T>();
}
else
{
_serviceCollection.AddTransient<T>();
}
_serviceProvider = null;
}
public T Resolve<T>()
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider.GetService<T>()!;
}
}
}

View File

@ -0,0 +1,50 @@
using System.Reflection;
namespace FishFactoryContracts.DI
{
public class ServiceProviderLoader
{
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension
/// </summary>
/// <returns></returns>
public static IImplementationExtension? GetImplementationExtensions()
{
IImplementationExtension? source = null;
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct())
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
if (source == null)
{
source = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{
source = newSource;
}
}
}
}
}
return source;
}
private static string TryGetImplementationExtensionsFolder()
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null && !directory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
{
directory = directory.Parent;
}
return $"{directory?.FullName}\\ImplementationExtensions";
}
}
}

View File

@ -0,0 +1,50 @@
using Microsoft.Extensions.Logging;
using Unity;
using Unity.Microsoft.Logging;
namespace FishFactoryContracts.DI
{
public class UnityDependencyContainer : IDependencyContainer
{
private readonly UnityContainer _container;
public UnityDependencyContainer()
{
_container = new UnityContainer();
}
public void AddLogging(Action<ILoggingBuilder> configure)
{
_container.AddExtension(new LoggingExtension(LoggerFactory.Create(configure)));
}
public void RegisterType<T, U>(bool isSingle) where U : class, T where T : class
{
if (isSingle)
{
_container.RegisterSingleton<T, U>();
}
else
{
_container.RegisterType<T, U>();
}
}
public void RegisterType<T>(bool isSingle) where T : class
{
if (isSingle)
{
_container.RegisterSingleton<T>();
}
else
{
_container.RegisterType<T>();
}
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
}

View File

@ -11,6 +11,11 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.1" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,9 @@
namespace FishFactoryContracts.StoragesContracts
{
public interface IBackUpInfo
{
List<T>? GetList<T>() where T : class, new();
Type? GetTypeByModelInterface(string modelInterfaceName);
}
}

View File

@ -1,15 +1,17 @@
using FishFactoryDataModels.Models;
using System.ComponentModel;
using FishFactoryContracts.Attributes;
using FishFactoryDataModels.Models;
namespace FishFactoryContracts.ViewModels
{
public class CannedViewModel : ICannedModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Название изделия")]
[Column(title: "Консерва", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string CannedName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 150)]
public double Price { get; set; }
[Column(visible: false)]
public Dictionary<int, (IIngredientModel, int)> CannedIngredients
{
get;

View File

@ -1,19 +1,20 @@
using FishFactoryDataModels.Models;
using System.ComponentModel;
using FishFactoryContracts.Attributes;
using FishFactoryDataModels.Models;
namespace FishFactoryContracts.ViewModels
{
public class ClientViewModel : IClientModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("Клиент")]
[Column(title: "Клиент", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")]
[Column(title: "Логин (эл. почта)", width: 150)]
public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")]
[Column(title: "Пароль", width: 150)]
public string Password { get; set; } = string.Empty;
}
}

View File

@ -1,5 +1,5 @@
using FishFactoryDataModels.Models;
using System.ComponentModel;
using FishFactoryContracts.Attributes;
using FishFactoryDataModels.Models;
namespace FishFactoryContracts.ViewModels
{
@ -8,18 +8,19 @@ namespace FishFactoryContracts.ViewModels
/// </summary>
public class ImplementerViewModel : IImplementerModel
{
[Column(visible: false)]
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
[Column(title: "ФИО исполнителя", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
[Column(title: "Пароль", width: 100)]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
[Column(title: "Стаж работы", width: 50)]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
[Column(title: "Квалификация", width: 50)]
public int Qualification { get; set; }
}
}

View File

@ -1,14 +1,15 @@
using System.ComponentModel;
using FishFactoryContracts.Attributes;
using FishFactoryDataModels.Models;
namespace FishFactoryContracts.ViewModels
{
public class IngredientViewModel : IIngredientModel
{
public int Id { get; set; }
[DisplayName("Название ингредиента")]
[Column(visible: false)]
public int Id { get; set; }
[Column(title: "Ингредиент", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string IngredientName { get; set; } = string.Empty;
[DisplayName("Цена")]
[Column(title: "Цена", width: 150)]
public double Cost { get; set; }
}
}

View File

@ -1,24 +1,29 @@
using FishFactoryDataModels.Models;
using System.ComponentModel;
using FishFactoryContracts.Attributes;
using FishFactoryDataModels.Models;
namespace FishFactoryContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public string MessageId { get; set; } = string.Empty;
[Column(visible: false)]
public int? ClientId { get; set; }
[DisplayName("Отправитель")]
[Column(title: "Отправитель", width: 150)]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата письма")]
[Column(title: "Дата письма", width: 150)]
public DateTime DateDelivery { get; set; }
[DisplayName("Заголовок")]
[Column(title: "Заголовок", width: 150)]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
[Column(title: "Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty;
[Column(visible: false)]
public int Id => throw new NotImplementedException();
}
}

View File

@ -1,4 +1,4 @@
using System.ComponentModel;
using FishFactoryContracts.Attributes;
using FishFactoryDataModels.Enums;
using FishFactoryDataModels.Models;
@ -6,26 +6,29 @@ namespace FishFactoryContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
[Column(title: "Номер", width: 50)]
public int Id { get; set; }
[Column(visible: false)]
public int CannedId { get; set; }
[Column(visible: false)]
public int ClientId { get; set; }
[Column(visible: false)]
public int? ImplementerId { get; set; }
[DisplayName("Консерва")]
[Column(title: "Консерва", width: 100)]
public string CannedName { get; set; } = string.Empty;
[DisplayName("Клиент")]
[Column(title: "Клиент", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Исполнитель")]
[Column(title: "Исполнитель", width: 130)]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
[Column(title: "Количество", width: 100)]
public int Count { get; set; }
[DisplayName("Сумма")]
[Column(title: "Сумма", width: 50)]
public double Sum { get; set; }
[DisplayName("Статус")]
[Column(title: "Статус", width: 50)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
[Column(title: "Дата создания", width: 100)]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
[Column(title: "Дата выполнения", width: 100)]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using FishFactoryContracts.DI;
using FishFactoryContracts.StoragesContracts;
using FishFactoryDatabaseImplement.Implements;
namespace FishFactoryDatabaseImplement
{
public class DatabaseImplementationExtension : IImplementationExtension
{
public int Priority => 2;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IIngredientStorage, IngredientStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICannedStorage, CannedStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -20,4 +20,7 @@
<ProjectReference Include="..\FishFactoryDataModels\FishFactoryDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@ -0,0 +1,27 @@
using FishFactoryContracts.StoragesContracts;
namespace FishFactoryDatabaseImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
using var context = new FishFactoryDatabase();
return context.Set<T>().ToList();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace FishFactoryDatabaseImplement.Migrations
{
[DbContext(typeof(FishFactoryDatabase))]
[Migration("20230521120653_InitialCreate")]
[Migration("20230521124018_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />

View File

@ -3,22 +3,28 @@ using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace FishFactoryDatabaseImplement.Models
{
public class Canned : ICannedModel
[DataContract]
public class Canned : ICannedModel
{
public int Id { get; set; }
[Required]
[DataMember]
public int Id { get; set; }
[DataMember]
[Required]
public string CannedName { get; set; } = string.Empty;
[Required]
[DataMember]
[Required]
public double Price { get; set; }
private Dictionary<int, (IIngredientModel, int)>? _cannedIngredients = null;
[NotMapped]
[DataMember]
[NotMapped]
public Dictionary<int, (IIngredientModel, int)> CannedIngredients
{
get

View File

@ -3,17 +3,23 @@ using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace FishFactoryDatabaseImplement.Models
{
[DataContract]
public class Client : IClientModel
{
public int Id { get; private set; }
[Required]
[DataMember]
public int Id { get; private set; }
[DataMember]
[Required]
public string ClientFIO { get; set; } = string.Empty;
[Required]
[DataMember]
[Required]
public string Email { get; set; } = string.Empty;
[Required]
[DataMember]
[Required]
public string Password { get; set; } = string.Empty;
[ForeignKey("ClientId")]

View File

@ -3,19 +3,26 @@ using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace FishFactoryDatabaseImplement.Models
{
public class Implementer : IImplementerModel
[DataContract]
public class Implementer : IImplementerModel
{
[DataMember]
public int Id { get; private set; }
[Required]
[DataMember]
[Required]
public string ImplementerFIO { get; private set; } = string.Empty;
[Required]
[DataMember]
[Required]
public string Password { get; private set; } = string.Empty;
[Required]
[DataMember]
[Required]
public int WorkExperience { get; private set; }
[Required]
[DataMember]
[Required]
public int Qualification { get; private set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; set; } = new();

View File

@ -3,16 +3,19 @@ using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace FishFactoryDatabaseImplement.Models
{
[DataContract]
public class Ingredient : IIngredientModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
[Required]
public string IngredientName { get; private set; } = string.Empty;
[DataMember]
[Required]
public double Cost { get; set; }

View File

@ -2,21 +2,29 @@
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace FishFactoryDatabaseImplement.Models
{
[DataContract]
public class Message : IMessageInfoModel
{
[Key]
[DataMember]
[Key]
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; }
[Required]
[DataMember]
public int? ClientId { get; private set; }
[DataMember]
[Required]
public string SenderName { get; private set; } = string.Empty;
[Required]
[DataMember]
[Required]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
[Required]
[DataMember]
[Required]
public string Subject { get; private set; } = string.Empty;
[Required]
[DataMember]
[Required]
public string Body { get; private set; } = string.Empty;
public static Message? Create(MessageInfoBindingModel model)
@ -45,5 +53,7 @@ namespace FishFactoryDatabaseImplement.Models
SenderName = SenderName,
DateDelivery = DateDelivery,
};
public int Id => throw new NotImplementedException();
}
}

View File

@ -3,26 +3,37 @@ using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using FishFactoryDataModels.Enums;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace FishFactoryDatabaseImplement.Models
{
[DataContract]
public class Order : IOrderModel
{
[Required]
[DataMember]
[Required]
public int CannedId { get; set; }
[Required]
[DataMember]
[Required]
public int ClientId { get; set; }
[DataMember]
public int? ImplementerId { get; private set; }
[Required]
[DataMember]
[Required]
public int Count { get; set; }
[Required]
[DataMember]
[Required]
public double Sum { get; set; }
[Required]
[DataMember]
[Required]
public OrderStatus Status { get; set; }
[Required]
[DataMember]
[Required]
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int Id { get; set; }
[DataMember]
public DateTime? DateImplement { get; set; }
[DataMember]
public int Id { get; set; }
public Canned Canned { get; set; }
public Client Client { get; set; }
public Implementer? Implementer { get; set; }

View File

@ -0,0 +1,22 @@
using FishFactoryContracts.DI;
using FishFactoryContracts.StoragesContracts;
using FishFactoryFileImplement.Implements;
namespace FishFactoryFileImplement
{
public class FileImplementationExtension : IImplementationExtension
{
public int Priority => 1;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IIngredientStorage, IngredientStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICannedStorage, CannedStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -18,4 +18,7 @@
<ProjectReference Include="..\FishFactoryDataModels\FishFactoryDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@ -0,0 +1,29 @@
using FishFactoryContracts.StoragesContracts;
namespace FishFactoryFileImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
var source = DataFileSingleton.GetInstance();
return (List<T>?)source.GetType().GetProperties()
.FirstOrDefault(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericArguments()[0] == typeof(T))
?.GetValue(source);
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
var assembly = typeof(BackUpInfo).Assembly;
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.GetInterface(modelInterfaceName) != null)
{
return type;
}
}
return null;
}
}
}

View File

@ -1,18 +1,24 @@
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
public class Canned : ICannedModel
[DataContract]
public class Canned : ICannedModel
{
public int Id { get; private set; }
public string CannedName { get; private set; } = string.Empty;
public double Price { get; private set; }
[DataMember]
public int Id { get; private set; }
[DataMember]
public string CannedName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Ingredients { get; private set; } = new();
private Dictionary<int, (IIngredientModel, int)>? _productIngredients = null;
public Dictionary<int, (IIngredientModel, int)> CannedIngredients
[DataMember]
public Dictionary<int, (IIngredientModel, int)> CannedIngredients
{
get
{

View File

@ -1,16 +1,22 @@
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
public class Client : IClientModel
[DataContract]
public class Client : IClientModel
{
public int Id { get; private set; }
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ClientFIO { get; private set; } = string.Empty;
[DataMember]
public string Email { get; set; } = string.Empty;
[DataMember]
public string Password { get; set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
if (model == null)

View File

@ -1,20 +1,23 @@
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
public class Implementer : IImplementerModel
[DataContract]
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
[DataMember]
public int Id { get; private set; }
[DataMember]
public string ImplementerFIO { get; private set; } = string.Empty;
[DataMember]
public string Password { get; private set; } = string.Empty;
[DataMember]
public int WorkExperience { get; private set; }
[DataMember]
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel? model)

View File

@ -1,15 +1,20 @@
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
public class Ingredient : IIngredientModel
[DataContract]
public class Ingredient : IIngredientModel
{
public int Id { get; private set; }
public string IngredientName { get; private set; } = string.Empty;
public double Cost { get; set; }
[DataMember]
public int Id { get; private set; }
[DataMember]
public string IngredientName { get; private set; } = string.Empty;
[DataMember]
public double Cost { get; set; }
public static Ingredient? Create(IngredientBindingModel model)
{
if (model == null)

View File

@ -2,22 +2,25 @@
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
public class Message : IMessageInfoModel
[DataContract]
public class Message : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
[DataMember]
public string MessageId { get; private set; } = string.Empty;
[DataMember]
public int? ClientId { get; private set; }
[DataMember]
public string SenderName { get; private set; } = string.Empty;
[DataMember]
public DateTime DateDelivery { get; private set; } = DateTime.Now;
[DataMember]
public string Subject { get; private set; } = string.Empty;
[DataMember]
public string Body { get; private set; } = string.Empty;
public static Message? Create(MessageInfoBindingModel model)
@ -72,5 +75,7 @@ namespace FishFactoryFileImplement.Models
new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery)
);
public int Id => throw new NotImplementedException();
}
}

View File

@ -2,21 +2,32 @@
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using FishFactoryDataModels.Enums;
using System.Runtime.Serialization;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
public class Order : IOrderModel
[DataContract]
public class Order : IOrderModel
{
public int Id { get; private set; }
public int CannedId { get; private set; }
public int ClientId { get; private set; }
[DataMember]
public int Id { get; private set; }
[DataMember]
public int CannedId { get; private set; }
[DataMember]
public int ClientId { get; private set; }
[DataMember]
public int? ImplementerId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
[DataMember]
public int Count { get; private set; }
[DataMember]
public double Sum { get; private set; }
[DataMember]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[DataMember]
public DateTime DateCreate { get; private set; } = DateTime.Now;
[DataMember]
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
{

View File

@ -21,4 +21,7 @@
<ProjectReference Include="..\FishFactoryDataModels\FishFactoryDataModels.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project>

View File

@ -0,0 +1,17 @@
using FishFactoryContracts.StoragesContracts;
namespace FishFactoryListImplement.Implements
{
public class BackUpInfo : IBackUpInfo
{
public List<T>? GetList<T>() where T : class, new()
{
throw new NotImplementedException();
}
public Type? GetTypeByModelInterface(string modelInterfaceName)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,22 @@
using FishFactoryContracts.DI;
using FishFactoryContracts.StoragesContracts;
using FishFactoryListImplement.Implements;
namespace FishFactoryListImplement
{
public class ListImplementationExtension : IImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IClientStorage, ClientStorage>();
DependencyManager.Instance.RegisterType<IIngredientStorage, IngredientStorage>();
DependencyManager.Instance.RegisterType<IImplementerStorage, ImplementerStorage>();
DependencyManager.Instance.RegisterType<IMessageInfoStorage, MessageInfoStorage>();
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<ICannedStorage, CannedStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
}
}
}

View File

@ -44,5 +44,7 @@ namespace FishFactoryListImplement.Models
ClientId = ClientId,
MessageId = MessageId
};
public int Id => throw new NotImplementedException();
}
}

View File

@ -13,7 +13,9 @@
<ItemGroup>
<ProjectReference Include="..\FishFactoryBusinessLogic\FishFactoryBusinessLogic.csproj" />
<ProjectReference Include="..\FishFactoryContracts\FishFactoryContracts.csproj" />
<ProjectReference Include="..\FishFactoryDatabaseImplement\FishFactoryDatabaseImplement.csproj" />
<ProjectReference Include="..\FishFactoryFileImplement\FishFactoryFileImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -12,5 +12,5 @@
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "fishfactorymail@gmail.com",
"MailPassword": "rqhd bdhh ampu tsnn"
"MailPassword": "fvdy wqeh xnnr kefc"
}

View File

@ -6,6 +6,6 @@
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="fishfactorymail@gmail.com" />
<add key="MailPassword" value="rqhd bdhh ampu tsnn" />
<add key="MailPassword" value="fvdy wqeh xnnr kefc" />
</appSettings>
</configuration>

View File

@ -0,0 +1,46 @@
using FishFactoryContracts.Attributes;
namespace FishFactoryView
{
internal static class DataGridViewExtension
{
public static void FillAndConfigGrid<T>(this DataGridView grid, List<T>? data)
{
if (data == null)
{
return;
}
grid.DataSource = data;
var type = typeof(T);
var properties = type.GetProperties();
foreach (DataGridViewColumn column in grid.Columns)
{
var property = properties.FirstOrDefault(x => x.Name == column.Name);
if (property == null)
{
throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}");
}
var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
if (attribute == null)
{
throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}");
}
// ищем нужный нам атрибут
if (attribute is ColumnAttribute columnAttr)
{
column.HeaderText = columnAttr.Title;
column.Visible = columnAttr.Visible;
if (columnAttr.IsUseAutoSize)
{
column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString());
}
else
{
column.Width = columnAttr.Width;
}
}
}
}
}
}

View File

@ -31,6 +31,9 @@
</ItemGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ReportOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>

View File

@ -3,6 +3,7 @@ using FishFactoryContracts.BindingModels;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.SearchModels;
using FishFactoryDataModels.Models;
using FishFactoryContracts.DI;
namespace FishFactoryView
{
@ -70,7 +71,7 @@ namespace FishFactoryView
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCannedIngredients));
var service = DependencyManager.Instance.Resolve<FormCannedIngredients>();
if (service is FormCannedIngredients form)
{
if (form.ShowDialog() == DialogResult.OK)
@ -98,7 +99,7 @@ namespace FishFactoryView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCannedIngredients));
var service = DependencyManager.Instance.Resolve<FormCannedIngredients>();
if (service is FormCannedIngredients form)
{
int id =

View File

@ -26,13 +26,7 @@ namespace FishFactoryView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.DI;
namespace FishFactoryView
{
@ -22,13 +23,7 @@ namespace FishFactoryView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
@ -40,7 +35,7 @@ namespace FishFactoryView
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
var service = DependencyManager.Instance.Resolve <FormImplementer>();
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
@ -53,7 +48,7 @@ namespace FishFactoryView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
var service = DependencyManager.Instance.Resolve<FormImplementer>();
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.DI;
namespace FishFactoryView
{
@ -22,13 +23,7 @@ namespace FishFactoryView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["IngredientName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка ингредиентов");
}
catch (Exception ex)
@ -40,7 +35,7 @@ namespace FishFactoryView
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormIngredient));
var service = DependencyManager.Instance.Resolve<FormIngredient>();
if (service is FormIngredient form)
{
if (form.ShowDialog() == DialogResult.OK)
@ -53,7 +48,7 @@ namespace FishFactoryView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormIngredient));
var service = DependencyManager.Instance.Resolve <FormIngredient>();
if (service is FormIngredient form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.DI;
namespace FishFactoryView
{
@ -23,14 +24,7 @@ namespace FishFactoryView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["CannedName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["CannedIngredients"].Visible = false;
}
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка консервы");
}
catch (Exception ex)
@ -42,7 +36,7 @@ namespace FishFactoryView
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCanned));
var service = DependencyManager.Instance.Resolve<FormCanned>();
if (service is FormCanned form)
{
if (form.ShowDialog() == DialogResult.OK)
@ -56,7 +50,7 @@ namespace FishFactoryView
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCanned));
var service = DependencyManager.Instance.Resolve<FormCanned>();
if (service is FormCanned form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);

View File

@ -19,14 +19,7 @@ namespace FishFactoryView
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка писем");
}
catch (Exception ex)

View File

@ -39,6 +39,7 @@
this.ingredientsByCannedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ordersListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.startOfWorkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createBackUpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonSetToFinish = new System.Windows.Forms.Button();
this.buttonCreateOrder = new System.Windows.Forms.Button();
@ -54,7 +55,8 @@
this.reference_booksToolStripMenuItem,
this.reportsToolStripMenuItem,
this.startOfWorkToolStripMenuItem,
this.lettersToolStripMenuItem});
this.lettersToolStripMenuItem,
this.createBackUpToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1086, 24);
@ -145,6 +147,13 @@
this.lettersToolStripMenuItem.Text = "Письма";
this.lettersToolStripMenuItem.Click += new System.EventHandler(this.MailsToolStripMenuItem_Click);
//
// createBackUpToolStripMenuItem
//
this.createBackUpToolStripMenuItem.Name = "createBackUpToolStripMenuItem";
this.createBackUpToolStripMenuItem.Size = new System.Drawing.Size(97, 20);
this.createBackUpToolStripMenuItem.Text = "Создать бекап";
this.createBackUpToolStripMenuItem.Click += new System.EventHandler(this.CreateBackUpToolStripMenuItem_Click);
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(905, 253);
@ -230,5 +239,6 @@
private ToolStripMenuItem performersToolStripMenuItem;
private ToolStripMenuItem startOfWorkToolStripMenuItem;
private ToolStripMenuItem lettersToolStripMenuItem;
private ToolStripMenuItem createBackUpToolStripMenuItem;
}
}

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.DI;
namespace FishFactoryView
{
@ -10,13 +11,15 @@ namespace FishFactoryView
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
private readonly IBackUpLogic _backUpLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IBackUpLogic backUpLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
_backUpLogic = backUpLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -27,18 +30,7 @@ namespace FishFactoryView
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["CannedId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["CannedName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
dataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
@ -49,7 +41,7 @@ namespace FishFactoryView
}
private void IngredientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormIngredients));
var service = DependencyManager.Instance.Resolve<FormIngredients>();
if (service is FormIngredients form)
{
form.ShowDialog();
@ -57,7 +49,7 @@ namespace FishFactoryView
}
private void CannedToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormListCanned));
var service = DependencyManager.Instance.Resolve<FormListCanned>();
if (service is FormListCanned form)
{
form.ShowDialog();
@ -65,7 +57,7 @@ namespace FishFactoryView
}
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
var service = DependencyManager.Instance.Resolve<FormImplementers>();
if (service is FormImplementers form)
{
form.ShowDialog();
@ -75,14 +67,14 @@ namespace FishFactoryView
private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((
Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!,
DependencyManager.Instance.Resolve<IImplementerLogic>() as IImplementerLogic)!,
_orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
var service = DependencyManager.Instance.Resolve<FormCreateOrder>();
if (service is FormCreateOrder form)
{
form.ShowDialog();
@ -182,7 +174,7 @@ namespace FishFactoryView
private void CannedIngredientToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportCannedIngredients));
var service = DependencyManager.Instance.Resolve<FormReportCannedIngredients>();
if (service is FormReportCannedIngredients form)
{
form.ShowDialog();
@ -191,7 +183,7 @@ namespace FishFactoryView
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
var service = DependencyManager.Instance.Resolve<FormReportOrders>();
if (service is FormReportOrders form)
{
form.ShowDialog();
@ -201,7 +193,7 @@ namespace FishFactoryView
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
var service = DependencyManager.Instance.Resolve<FormClients>();
if (service is FormClients form)
{
form.ShowDialog();
@ -210,11 +202,36 @@ namespace FishFactoryView
private void MailsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMails));
var service = DependencyManager.Instance.Resolve<FormMails>();
if (service is FormMails form)
{
form.ShowDialog();
}
}
private void CreateBackUpToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_backUpLogic != null)
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
_backUpLogic.CreateBackUp(new BackUpSaveBindingModel
{
FolderName = fbd.SelectedPath
});
MessageBox.Show("Бекап создан", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}

View File

@ -1,22 +1,18 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using FishFactoryBusinessLogic.BusinessLogics;
using FishFactoryBusinessLogic.OfficePackage.Implements;
using FishFactoryBusinessLogic.OfficePackage;
using FishFactoryContracts.BusinessLogicsContracts;
using FishFactoryContracts.StoragesContracts;
using FishFactoryDatabaseImplement.Implements;
using FishFactoryBusinessLogic.MailWorker;
using FishFactoryContracts.BindingModels;
using FishFactoryContracts.DI;
namespace FishFactoryView
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
@ -26,13 +22,11 @@ namespace FishFactoryView
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
InitDependency();
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
var mailSender = DependencyManager.Instance.Resolve<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
@ -48,54 +42,52 @@ namespace FishFactoryView
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "ошибка работы с почтой");
var logger = DependencyManager.Instance.Resolve<ILogger>();
logger?.LogError(ex, "Ошибка работы с почтой");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
Application.Run(DependencyManager.Instance.Resolve<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
private static void InitDependency()
{
services.AddLogging(option =>
DependencyManager.InitDependency();
DependencyManager.Instance.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IIngredientStorage, IngredientStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ICannedStorage, CannedStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IIngredientLogic, IngredientLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ICannedLogic, CannedLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
;
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IIngredientLogic, IngredientLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<ICannedLogic, CannedLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(true);
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>();
services.AddTransient<FormClients>();
services.AddTransient<FormIngredient>();
services.AddTransient<FormIngredients>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormCanned>();
services.AddTransient<FormCannedIngredients>();
services.AddTransient<FormListCanned>();
services.AddTransient<FormReportCannedIngredients>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormMails>();
DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormClients>();
DependencyManager.Instance.RegisterType<FormIngredient>();
DependencyManager.Instance.RegisterType<FormIngredients>();
DependencyManager.Instance.RegisterType<FormCreateOrder>();
DependencyManager.Instance.RegisterType<FormCanned>();
DependencyManager.Instance.RegisterType<FormCannedIngredients>();
DependencyManager.Instance.RegisterType<FormListCanned>();
DependencyManager.Instance.RegisterType<FormReportCannedIngredients>();
DependencyManager.Instance.RegisterType<FormReportOrders>();
DependencyManager.Instance.RegisterType<FormImplementers>();
DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormMails>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
private static void MailCheck(object obj) => DependencyManager.Instance.Resolve<AbstractMailWorker>()?.MailCheck();
}
}