25 Commits
Author SHA1 Message Date
ivanszabo a6af9f2db7 Induláskor átmenjen a middlewareon a bejelentkezéshez szükséges elemek 2026-09-16 14:02:18 +02:00
ivanszabo 364c1b455d Felesleges footerek levétele 2026-09-14 11:48:33 +02:00
ivanszabo d00e087b35 Dashboard is élő, bekötve! 2026-09-14 11:14:22 +02:00
ivanszabo 289992ce5e Arculat javítása 2026-09-12 22:19:24 +02:00
ivanszabo 02ba8d4fe5 INIT GITEA 2026-09-12 18:19:29 +02:00
ivanszabo b2faeb2986 Arculat hozzáadása 2026-09-12 12:38:39 +02:00
ivanszabo 717becd1fc ServerSide Paging 2026-08-02 16:36:21 +02:00
ivanszabo 92acb42601 Na most jó a lapozás 2026-03-09 11:32:12 +01:00
ivanszabo 53dc9b326a Ez most szerver oldalon szűr és lapoz 2026-03-02 14:12:43 +01:00
ivanszabo ea9673c29b Login secure problem 2026-01-28 13:46:16 +01:00
ivanszabo 4c7e24c478 1.1.32 kiadás 2026-01-28 12:48:21 +01:00
ivanszabo c11ff65a3e Ellenőrzések szétválasztása + sorrend 2026-01-28 12:47:43 +01:00
ivanszabo 8c0796eb69 satatables hu language pack lokálisan 2026-01-28 11:54:11 +01:00
ivanszabo 10ad411b5e appsettings beállítása fejlesztéshez 2026-01-28 11:53:52 +01:00
ivanszabo 8d766ab988 publish cmd 2026-01-28 11:18:26 +01:00
ivanszabo 8177a60351 - 2026-01-21 13:01:06 +01:00
ivanszabo 0fd073755e Password első felhasználó rögzítésénél hiba 2026-01-21 12:59:56 +01:00
ivanszabo 6ea799dcdf WS2016DC\\SQLEXPRESS javítása 2026-01-21 10:22:33 +01:00
ivanszabo caf9746443 API pulish.cmd kiegészítése 2026-01-21 09:35:09 +01:00
ivanszabo 41542e492d E-mail küldése 10 próbálkozásra, 2 mp-es várakozással 2026-01-21 09:19:22 +01:00
ivanszabo 4f4ca5cec4 Login és ChangePassword formok változtatása spinner kiegészítés 2026-01-20 10:10:52 +01:00
ivanszabo f480269bc5 Maximumart gépre átállás VS 2026 2026-01-20 10:09:59 +01:00
ivanszabo 24c49567aa BUGFIX valu mentésére 2025-07-07 14:57:40 +02:00
ivanszabo affad21ab0 BUGFIX mentés, scrollozás 2025-07-03 08:55:09 +02:00
ivanszabo a646258837 Elvileg jó, meg a mentés is. 2025-07-02 19:38:33 +02:00
439 changed files with 127051 additions and 124761 deletions
+107 -107
View File
@@ -1,107 +1,107 @@
# Suppress: EC112 # Suppress: EC112
# top-most EditorConfig file # top-most EditorConfig file
root = true root = true
# Don't use tabs for indentation. # Don't use tabs for indentation.
[*] [*]
indent_style = space indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.) # (Please don't specify an indent_size here; that has too many unintended consequences.)
# Code files # Code files
[*.{cs,csx,vb,vbx}] [*.{cs,csx,vb,vbx}]
indent_size = 4 indent_size = 4
# Xml project files # Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2 indent_size = 2
# Xml config files # Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2 indent_size = 2
# JSON files # JSON files
[*.json] [*.json]
indent_size = 2 indent_size = 2
# Dotnet code style settings: # Dotnet code style settings:
[*.{cs,vb}] [*.{cs,vb}]
# Sort using and Import directives with System.* appearing first # Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = false dotnet_sort_system_directives_first = false
# Avoid "this." and "Me." if not necessary # Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:suggestion dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion dotnet_style_qualification_for_event = false:suggestion
# Use language keywords instead of framework type names for type references # Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion dotnet_style_predefined_type_for_member_access = true:suggestion
# Suggest more modern language features when available # Suggest more modern language features when available
dotnet_style_object_initializer = true:suggestion dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion dotnet_style_explicit_tuple_names = true:suggestion
# Naming Conventions: # Naming Conventions:
# Pascal Casing # Pascal Casing
dotnet_naming_symbols.method_and_property_symbols.applicable_kinds = method,property,enum dotnet_naming_symbols.method_and_property_symbols.applicable_kinds = method,property,enum
dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities = * dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities = *
dotnet_naming_style.pascal_case_style.capitalization = pascal_case dotnet_naming_style.pascal_case_style.capitalization = pascal_case
dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity = warning dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity = warning
dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols = method_and_property_symbols dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols = method_and_property_symbols
dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style = pascal_case_style dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style = pascal_case_style
# Non-public members must be lower-case # Non-public members must be lower-case
#dotnet_naming_symbols.non_public_symbols.applicable_kinds = property,event,delegate #dotnet_naming_symbols.non_public_symbols.applicable_kinds = property,event,delegate
#dotnet_naming_symbols.non_public_symbols.applicable_accessibilities = private #dotnet_naming_symbols.non_public_symbols.applicable_accessibilities = private
#dotnet_naming_style.all_lower_case_style.capitalization = camel_case #dotnet_naming_style.all_lower_case_style.capitalization = camel_case
#dotnet_naming_rule.non_public_members_must_be_lower_case.severity = warning #dotnet_naming_rule.non_public_members_must_be_lower_case.severity = warning
#dotnet_naming_rule.non_public_members_must_be_lower_case.symbols = non_public_symbols #dotnet_naming_rule.non_public_members_must_be_lower_case.symbols = non_public_symbols
#dotnet_naming_rule.non_public_members_must_be_lower_case.style = all_lower_case_style #dotnet_naming_rule.non_public_members_must_be_lower_case.style = all_lower_case_style
# Private fields must start with an underscore # Private fields must start with an underscore
dotnet_naming_symbols.private_fields.applicable_kinds = field dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_style.prefix_underscore.capitalization = camel_case dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _ dotnet_naming_style.prefix_underscore.required_prefix = _
dotnet_naming_rule.private_members_with_underscore.severity = warning dotnet_naming_rule.private_members_with_underscore.severity = warning
dotnet_naming_rule.private_members_with_underscore.symbols = private_fields dotnet_naming_rule.private_members_with_underscore.symbols = private_fields
dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore
# CSharp code style settings: # CSharp code style settings:
[*.cs] [*.cs]
# Do not prefer "var" everywhere # Do not prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion csharp_style_var_elsewhere = true:suggestion
# Prefer method-like constructs to have a block body # Prefer method-like constructs to have a block body
csharp_style_expression_bodied_methods = true:suggestion csharp_style_expression_bodied_methods = true:suggestion
csharp_style_expression_bodied_constructors = true:none csharp_style_expression_bodied_constructors = true:none
csharp_style_expression_bodied_operators = true:none csharp_style_expression_bodied_operators = true:none
# Prefer property-like constructs to have an expression-body # Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_properties = true:suggestion csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_indexers = true:none csharp_style_expression_bodied_indexers = true:none
csharp_style_expression_bodied_accessors = true:none csharp_style_expression_bodied_accessors = true:none
# Suggest more modern language features when available # Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion csharp_style_conditional_delegate_call = true:suggestion
# Newline settings # Newline settings
csharp_new_line_before_open_brace = all csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true csharp_new_line_before_else = true
csharp_new_line_before_catch = true csharp_new_line_before_catch = true
csharp_new_line_before_finally = true csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_anonymous_types = true
+346 -346
View File
@@ -1,346 +1,346 @@
## Ignore Visual Studio temporary files, build results, and ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons. ## files generated by popular Visual Studio add-ons.
## ##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files # User-specific files
*.rsuser *.rsuser
*.suo *.suo
*.user *.user
*.userosscache *.userosscache
*.sln.docstates *.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio) # User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs *.userprefs
# Build results # Build results
[Dd]ebug/ [Dd]ebug/
[Dd]ebugPublic/ [Dd]ebugPublic/
[Rr]elease/ [Rr]elease/
[Rr]eleases/ [Rr]eleases/
x64/ x64/
x86/ x86/
[Aa][Rr][Mm]/ [Aa][Rr][Mm]/
[Aa][Rr][Mm]64/ [Aa][Rr][Mm]64/
bld/ bld/
[Bb]in/ [Bb]in/
[Oo]bj/ [Oo]bj/
[Ll]og/ [Ll]og/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/ #wwwroot/
# Visual Studio 2017 auto generated files # Visual Studio 2017 auto generated files
Generated\ Files/ Generated\ Files/
# MSTest test Results # MSTest test Results
[Tt]est[Rr]esult*/ [Tt]est[Rr]esult*/
[Bb]uild[Ll]og.* [Bb]uild[Ll]og.*
# NUNIT # NUNIT
*.VisualState.xml *.VisualState.xml
TestResult.xml TestResult.xml
# Build Results of an ATL Project # Build Results of an ATL Project
[Dd]ebugPS/ [Dd]ebugPS/
[Rr]eleasePS/ [Rr]eleasePS/
dlldata.c dlldata.c
# Benchmark Results # Benchmark Results
BenchmarkDotNet.Artifacts/ BenchmarkDotNet.Artifacts/
# .NET Core # .NET Core
project.lock.json project.lock.json
project.fragment.lock.json project.fragment.lock.json
artifacts/ artifacts/
# StyleCop # StyleCop
StyleCopReport.xml StyleCopReport.xml
# Files built by Visual Studio # Files built by Visual Studio
*_i.c *_i.c
*_p.c *_p.c
*_h.h *_h.h
*.ilk *.ilk
*.meta *.meta
*.obj *.obj
*.iobj *.iobj
*.pch *.pch
*.pdb *.pdb
*.ipdb *.ipdb
*.pgc *.pgc
*.pgd *.pgd
*.rsp *.rsp
*.sbr *.sbr
*.tlb *.tlb
*.tli *.tli
*.tlh *.tlh
*.tmp *.tmp
*.tmp_proj *.tmp_proj
*_wpftmp.csproj *_wpftmp.csproj
*.log *.log
*.vspscc *.vspscc
*.vssscc *.vssscc
.builds .builds
*.pidb *.pidb
*.svclog *.svclog
*.scc *.scc
# Chutzpah Test files # Chutzpah Test files
_Chutzpah* _Chutzpah*
# Visual C++ cache files # Visual C++ cache files
ipch/ ipch/
*.aps *.aps
*.ncb *.ncb
*.opendb *.opendb
*.opensdf *.opensdf
*.sdf *.sdf
*.cachefile *.cachefile
*.VC.db *.VC.db
*.VC.VC.opendb *.VC.VC.opendb
# Visual Studio profiler # Visual Studio profiler
*.psess *.psess
*.vsp *.vsp
*.vspx *.vspx
*.sap *.sap
# Visual Studio Trace Files # Visual Studio Trace Files
*.e2e *.e2e
# TFS 2012 Local Workspace # TFS 2012 Local Workspace
$tf/ $tf/
# Guidance Automation Toolkit # Guidance Automation Toolkit
*.gpState *.gpState
# ReSharper is a .NET coding add-in # ReSharper is a .NET coding add-in
_ReSharper*/ _ReSharper*/
*.[Rr]e[Ss]harper *.[Rr]e[Ss]harper
*.DotSettings.user *.DotSettings.user
# JustCode is a .NET coding add-in # JustCode is a .NET coding add-in
.JustCode .JustCode
# TeamCity is a build add-in # TeamCity is a build add-in
_TeamCity* _TeamCity*
# DotCover is a Code Coverage Tool # DotCover is a Code Coverage Tool
*.dotCover *.dotCover
# AxoCover is a Code Coverage Tool # AxoCover is a Code Coverage Tool
.axoCover/* .axoCover/*
!.axoCover/settings.json !.axoCover/settings.json
# Visual Studio code coverage results # Visual Studio code coverage results
*.coverage *.coverage
*.coveragexml *.coveragexml
# NCrunch # NCrunch
_NCrunch_* _NCrunch_*
.*crunch*.local.xml .*crunch*.local.xml
nCrunchTemp_* nCrunchTemp_*
# MightyMoose # MightyMoose
*.mm.* *.mm.*
AutoTest.Net/ AutoTest.Net/
# Web workbench (sass) # Web workbench (sass)
.sass-cache/ .sass-cache/
# Installshield output folder # Installshield output folder
[Ee]xpress/ [Ee]xpress/
# DocProject is a documentation generator add-in # DocProject is a documentation generator add-in
DocProject/buildhelp/ DocProject/buildhelp/
DocProject/Help/*.HxT DocProject/Help/*.HxT
DocProject/Help/*.HxC DocProject/Help/*.HxC
DocProject/Help/*.hhc DocProject/Help/*.hhc
DocProject/Help/*.hhk DocProject/Help/*.hhk
DocProject/Help/*.hhp DocProject/Help/*.hhp
DocProject/Help/Html2 DocProject/Help/Html2
DocProject/Help/html DocProject/Help/html
# Click-Once directory # Click-Once directory
publish/ publish/
# Publish Web Output # Publish Web Output
*.[Pp]ublish.xml *.[Pp]ublish.xml
*.azurePubxml *.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings, # Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted # but database connection strings (with potential passwords) will be unencrypted
*.pubxml *.pubxml
*.publishproj *.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to # 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 # checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted # in these scripts will be unencrypted
PublishScripts/ PublishScripts/
# NuGet Packages # NuGet Packages
*.nupkg *.nupkg
# The packages folder can be ignored because of Package Restore # The packages folder can be ignored because of Package Restore
**/[Pp]ackages/* **/[Pp]ackages/*
# except build/, which is used as an MSBuild target. # except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/ !**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed # Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config #!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files # NuGet v3's project.json files produces more ignorable files
*.nuget.props *.nuget.props
*.nuget.targets *.nuget.targets
# Microsoft Azure Build Output # Microsoft Azure Build Output
csx/ csx/
*.build.csdef *.build.csdef
# Microsoft Azure Emulator # Microsoft Azure Emulator
ecf/ ecf/
rcf/ rcf/
# Windows Store app package directories and files # Windows Store app package directories and files
AppPackages/ AppPackages/
BundleArtifacts/ BundleArtifacts/
Package.StoreAssociation.xml Package.StoreAssociation.xml
_pkginfo.txt _pkginfo.txt
*.appx *.appx
# Visual Studio cache files # Visual Studio cache files
# files ending in .cache can be ignored # files ending in .cache can be ignored
*.[Cc]ache *.[Cc]ache
# but keep track of directories ending in .cache # but keep track of directories ending in .cache
!?*.[Cc]ache/ !?*.[Cc]ache/
# Others # Others
ClientBin/ ClientBin/
~$* ~$*
*~ *~
*.dbmdl *.dbmdl
*.dbproj.schemaview *.dbproj.schemaview
*.jfm *.jfm
*.pfx *.pfx
*.publishsettings *.publishsettings
orleans.codegen.cs orleans.codegen.cs
# Including strong name files can present a security risk # Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424) # (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk #*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components # Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/ #bower_components/
# ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true # ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true
**/wwwroot/lib/ **/wwwroot/lib/
# RIA/Silverlight projects # RIA/Silverlight projects
Generated_Code/ Generated_Code/
# Backup & report files from converting an old project file # Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed, # to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-) # because we have git ;-)
_UpgradeReport_Files/ _UpgradeReport_Files/
Backup*/ Backup*/
UpgradeLog*.XML UpgradeLog*.XML
UpgradeLog*.htm UpgradeLog*.htm
ServiceFabricBackup/ ServiceFabricBackup/
*.rptproj.bak *.rptproj.bak
# SQL Server files # SQL Server files
*.mdf *.mdf
*.ldf *.ldf
*.ndf *.ndf
# Business Intelligence projects # Business Intelligence projects
*.rdl.data *.rdl.data
*.bim.layout *.bim.layout
*.bim_*.settings *.bim_*.settings
*.rptproj.rsuser *.rptproj.rsuser
# Microsoft Fakes # Microsoft Fakes
FakesAssemblies/ FakesAssemblies/
# GhostDoc plugin setting file # GhostDoc plugin setting file
*.GhostDoc.xml *.GhostDoc.xml
# Node.js Tools for Visual Studio # Node.js Tools for Visual Studio
.ntvs_analysis.dat .ntvs_analysis.dat
node_modules/ node_modules/
# Visual Studio 6 build log # Visual Studio 6 build log
*.plg *.plg
# Visual Studio 6 workspace options file # Visual Studio 6 workspace options file
*.opt *.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw *.vbw
# Visual Studio LightSwitch build output # Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts **/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml **/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts **/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml **/*.Server/ModelManifest.xml
_Pvt_Extensions _Pvt_Extensions
# Paket dependency manager # Paket dependency manager
.paket/paket.exe .paket/paket.exe
paket-files/ paket-files/
# FAKE - F# Make # FAKE - F# Make
.fake/ .fake/
# JetBrains Rider # JetBrains Rider
.idea/ .idea/
*.sln.iml *.sln.iml
# CodeRush personal settings # CodeRush personal settings
.cr/personal .cr/personal
# Python Tools for Visual Studio (PTVS) # Python Tools for Visual Studio (PTVS)
__pycache__/ __pycache__/
*.pyc *.pyc
# Cake - Uncomment if you are using it # Cake - Uncomment if you are using it
# tools/** # tools/**
# !tools/packages.config # !tools/packages.config
# Tabs Studio # Tabs Studio
*.tss *.tss
# Telerik's JustMock configuration file # Telerik's JustMock configuration file
*.jmconfig *.jmconfig
# BizTalk build output # BizTalk build output
*.btp.cs *.btp.cs
*.btm.cs *.btm.cs
*.odx.cs *.odx.cs
*.xsd.cs *.xsd.cs
# OpenCover UI analysis results # OpenCover UI analysis results
OpenCover/ OpenCover/
# Azure Stream Analytics local run output # Azure Stream Analytics local run output
ASALocalRun/ ASALocalRun/
# MSBuild Binary and Structured Log # MSBuild Binary and Structured Log
*.binlog *.binlog
# NVidia Nsight GPU debugger configuration file # NVidia Nsight GPU debugger configuration file
*.nvuser *.nvuser
# MFractors (Xamarin productivity tool) working folder # MFractors (Xamarin productivity tool) working folder
.mfractor/ .mfractor/
# Local History for Visual Studio # Local History for Visual Studio
.localhistory/ .localhistory/
# BeatPulse healthcheck temp database # BeatPulse healthcheck temp database
healthchecksdb healthchecksdb
/src/WorkFlowCheck.API/Images /src/WorkFlowCheck.API/Images
*.pdf *.pdf
/src/WorkFlowCheck.API/Pdf/c86f3a6a-c646-4627-823c-7e24134b7725.docx /src/WorkFlowCheck.API/Pdf/c86f3a6a-c646-4627-823c-7e24134b7725.docx
/src/WorkFlowCheck.API/Downloads/APK/com.nuvolar.wfcapp-Signed.apk /src/WorkFlowCheck.API/Downloads/APK/com.nuvolar.wfcapp-Signed.apk
/src/WorkFlowCheck.API/Pdf/3b9fd83a-dce8-4427-813b-9475726700be.docx /src/WorkFlowCheck.API/Pdf/3b9fd83a-dce8-4427-813b-9475726700be.docx
+19 -19
View File
@@ -1,20 +1,20 @@
#Introduction #Introduction
TODO: Give a short introduction of your project. Let this section explain the objectives or the motivation behind this project. TODO: Give a short introduction of your project. Let this section explain the objectives or the motivation behind this project.
#Getting Started #Getting Started
TODO: Guide users through getting your code up and running on their own system. In this section you can talk about: TODO: Guide users through getting your code up and running on their own system. In this section you can talk about:
1. Installation process 1. Installation process
2. Software dependencies 2. Software dependencies
3. Latest releases 3. Latest releases
4. API references 4. API references
#Build and Test #Build and Test
TODO: Describe and show how to build your code and run the tests. TODO: Describe and show how to build your code and run the tests.
#Contribute #Contribute
TODO: Explain how other users and developers can contribute to make your code better. TODO: Explain how other users and developers can contribute to make your code better.
If you want to learn more about creating good readme files then refer the following [guidelines](https://www.visualstudio.com/en-us/docs/git/create-a-readme). You can also seek inspiration from the below readme files: If you want to learn more about creating good readme files then refer the following [guidelines](https://www.visualstudio.com/en-us/docs/git/create-a-readme). You can also seek inspiration from the below readme files:
- [ASP.NET Core](https://github.com/aspnet/Home) - [ASP.NET Core](https://github.com/aspnet/Home)
- [Visual Studio Code](https://github.com/Microsoft/vscode) - [Visual Studio Code](https://github.com/Microsoft/vscode)
- [Chakra Core](https://github.com/Microsoft/ChakraCore) - [Chakra Core](https://github.com/Microsoft/ChakraCore)
+5 -5
View File
@@ -1,5 +1,5 @@
echo off echo off
echo "dotnet ef migrations add InitialCreate --project WorkFlowCheck.DL --startup-project WorkFlowCheck.API" echo "dotnet ef migrations add InitialCreate --project WorkFlowCheck.DL --startup-project WorkFlowCheck.API"
echo "dotnet ef database update --project WorkFlowCheck.DL --startup-project WorkFlowCheck.API" echo "dotnet ef database update --project WorkFlowCheck.DL --startup-project WorkFlowCheck.API"
echo "dotnet ef migrations remove --project WorkFlowCheck.DL --startup-project WorkFlowCheck.API" echo "dotnet ef migrations remove --project WorkFlowCheck.DL --startup-project WorkFlowCheck.API"
pause pause
+90 -90
View File
@@ -1,90 +1,90 @@
using Android.App; using Android.App;
using Android.Content; using Android.Content;
using Android.OS; using Android.OS;
using System; using System;
namespace Plugin.NFC namespace Plugin.NFC
{ {
/// <summary> /// <summary>
/// Cross NFC (Android specific) /// Cross NFC (Android specific)
/// </summary> /// </summary>
public static partial class CrossNFC public static partial class CrossNFC
{ {
internal static ActivityLifecycleContextListener lifecycleListener; internal static ActivityLifecycleContextListener lifecycleListener;
/// <summary> /// <summary>
/// Initialization /// Initialization
/// </summary> /// </summary>
/// <param name="application">Android <see cref="Application"/></param> /// <param name="application">Android <see cref="Application"/></param>
public static void Init(Application application) public static void Init(Application application)
{ {
if (lifecycleListener != null) return; if (lifecycleListener != null) return;
lifecycleListener = new ActivityLifecycleContextListener(); lifecycleListener = new ActivityLifecycleContextListener();
application.RegisterActivityLifecycleCallbacks(lifecycleListener); application.RegisterActivityLifecycleCallbacks(lifecycleListener);
} }
/// <summary> /// <summary>
/// Initialization /// Initialization
/// </summary> /// </summary>
/// <param name="activity">Android <see cref="Activity"/></param> /// <param name="activity">Android <see cref="Activity"/></param>
public static void Init(Activity activity) public static void Init(Activity activity)
{ {
Init(activity.Application); Init(activity.Application);
lifecycleListener.Activity = activity; lifecycleListener.Activity = activity;
} }
/// <summary> /// <summary>
/// Overrides Activity.OnNewIntent() /// Overrides Activity.OnNewIntent()
/// </summary> /// </summary>
/// <param name="intent">Android <see cref="Intent"/></param> /// <param name="intent">Android <see cref="Intent"/></param>
public static void OnNewIntent(Intent intent) => ((NFCImplementation)Current).HandleNewIntent(intent); public static void OnNewIntent(Intent intent) => ((NFCImplementation)Current).HandleNewIntent(intent);
/// <summary> /// <summary>
/// Overrides Activity.OnResume() /// Overrides Activity.OnResume()
/// </summary> /// </summary>
public static void OnResume() => ((NFCImplementation)Current).HandleOnResume(); public static void OnResume() => ((NFCImplementation)Current).HandleOnResume();
/// <summary> /// <summary>
/// Returns the current Android <see cref="Context"/> /// Returns the current Android <see cref="Context"/>
/// </summary> /// </summary>
internal static Context AppContext => Application.Context; internal static Context AppContext => Application.Context;
/// <summary> /// <summary>
/// Returns the current Android <see cref="Activity"/> /// Returns the current Android <see cref="Activity"/>
/// </summary> /// </summary>
/// <param name="throwError"></param> /// <param name="throwError"></param>
/// <returns></returns> /// <returns></returns>
internal static Activity GetCurrentActivity(bool throwError) internal static Activity GetCurrentActivity(bool throwError)
{ {
var activity = lifecycleListener?.Activity; var activity = lifecycleListener?.Activity;
if (throwError && activity == null) if (throwError && activity == null)
throw new NullReferenceException("The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class."); throw new NullReferenceException("The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class.");
return activity; return activity;
} }
} }
/// <summary> /// <summary>
/// James Montemagno's ActivityLifecycleContextListener from CurrentActivityPlugin /// James Montemagno's ActivityLifecycleContextListener from CurrentActivityPlugin
/// <see href="https://github.com/jamesmontemagno/CurrentActivityPlugin"/> /// <see href="https://github.com/jamesmontemagno/CurrentActivityPlugin"/>
/// </summary> /// </summary>
class ActivityLifecycleContextListener : Java.Lang.Object, Application.IActivityLifecycleCallbacks class ActivityLifecycleContextListener : Java.Lang.Object, Application.IActivityLifecycleCallbacks
{ {
WeakReference<Activity> _currentActivity = new WeakReference<Activity>(null); WeakReference<Activity> _currentActivity = new WeakReference<Activity>(null);
internal Context Context => Activity ?? Application.Context; internal Context Context => Activity ?? Application.Context;
internal Activity Activity internal Activity Activity
{ {
get => _currentActivity.TryGetTarget(out var a) ? a : null; get => _currentActivity.TryGetTarget(out var a) ? a : null;
set => _currentActivity.SetTarget(value); set => _currentActivity.SetTarget(value);
} }
void Application.IActivityLifecycleCallbacks.OnActivityCreated(Activity activity, Bundle savedInstanceState) => Activity = activity; void Application.IActivityLifecycleCallbacks.OnActivityCreated(Activity activity, Bundle savedInstanceState) => Activity = activity;
void Application.IActivityLifecycleCallbacks.OnActivityDestroyed(Activity activity) { } void Application.IActivityLifecycleCallbacks.OnActivityDestroyed(Activity activity) { }
void Application.IActivityLifecycleCallbacks.OnActivityPaused(Activity activity) => Activity = activity; void Application.IActivityLifecycleCallbacks.OnActivityPaused(Activity activity) => Activity = activity;
void Application.IActivityLifecycleCallbacks.OnActivityResumed(Activity activity) => Activity = activity; void Application.IActivityLifecycleCallbacks.OnActivityResumed(Activity activity) => Activity = activity;
void Application.IActivityLifecycleCallbacks.OnActivitySaveInstanceState(Activity activity, Bundle outState) { } void Application.IActivityLifecycleCallbacks.OnActivitySaveInstanceState(Activity activity, Bundle outState) { }
void Application.IActivityLifecycleCallbacks.OnActivityStarted(Activity activity) { } void Application.IActivityLifecycleCallbacks.OnActivityStarted(Activity activity) { }
void Application.IActivityLifecycleCallbacks.OnActivityStopped(Activity activity) { } void Application.IActivityLifecycleCallbacks.OnActivityStopped(Activity activity) { }
} }
} }
File diff suppressed because it is too large Load Diff
+108 -108
View File
@@ -1,108 +1,108 @@
<Project Sdk="MSBuild.Sdk.Extras/3.0.44"> <Project Sdk="MSBuild.Sdk.Extras/3.0.44">
<PropertyGroup> <PropertyGroup>
<!--Work around so the conditions work below--> <!--Work around so the conditions work below-->
<!--<TargetFrameworks>netstandard1.0;netstandard2.0;Xamarin.iOS10;MonoAndroid10.0;net8.0;net8.0-android;net8.0-ios</TargetFrameworks>--> <!--<TargetFrameworks>netstandard1.0;netstandard2.0;Xamarin.iOS10;MonoAndroid10.0;net8.0;net8.0-android;net8.0-ios</TargetFrameworks>-->
<TargetFrameworks>net8.0;net8.0-android;net8.0-ios</TargetFrameworks> <TargetFrameworks>net8.0;net8.0-android;net8.0-ios</TargetFrameworks>
<AssemblyName>Plugin.NFC</AssemblyName> <AssemblyName>Plugin.NFC</AssemblyName>
<RootNamespace>Plugin.NFC</RootNamespace> <RootNamespace>Plugin.NFC</RootNamespace>
<PackageId>Plugin.NFC</PackageId> <PackageId>Plugin.NFC</PackageId>
<Product>$(AssemblyName) ($(TargetFramework))</Product> <Product>$(AssemblyName) ($(TargetFramework))</Product>
<AssemblyVersion>1.0.0.0</AssemblyVersion> <AssemblyVersion>1.0.0.0</AssemblyVersion>
<AssemblyFileVersion>1.0.0.0</AssemblyFileVersion> <AssemblyFileVersion>1.0.0.0</AssemblyFileVersion>
<Version>1.0.0.0</Version> <Version>1.0.0.0</Version>
<PackageVersion>1.0.0.0</PackageVersion> <PackageVersion>1.0.0.0</PackageVersion>
<PackOnBuild>true</PackOnBuild> <PackOnBuild>true</PackOnBuild>
<NeutralLanguage>en</NeutralLanguage> <NeutralLanguage>en</NeutralLanguage>
<DefineConstants>$(DefineConstants);</DefineConstants> <DefineConstants>$(DefineConstants);</DefineConstants>
<NoWarn>CS0067</NoWarn> <NoWarn>CS0067</NoWarn>
<UseFullSemVerForNuGet>false</UseFullSemVerForNuGet> <UseFullSemVerForNuGet>false</UseFullSemVerForNuGet>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems> <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<DebugType>portable</DebugType> <DebugType>portable</DebugType>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageProjectUrl>https://github.com/franckbour/Plugin.NFC</PackageProjectUrl> <PackageProjectUrl>https://github.com/franckbour/Plugin.NFC</PackageProjectUrl>
<RepositoryUrl>https://github.com/franckbour/Plugin.NFC</RepositoryUrl> <RepositoryUrl>https://github.com/franckbour/Plugin.NFC</RepositoryUrl>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<PackageReleaseNotes>https://github.com/franckbour/Plugin.NFC/blob/master/CHANGELOG.md</PackageReleaseNotes> <PackageReleaseNotes>https://github.com/franckbour/Plugin.NFC/blob/master/CHANGELOG.md</PackageReleaseNotes>
<PackageIconUrl>https://github.com/franckbour/Plugin.NFC/raw/master/art/nfc128.png</PackageIconUrl> <PackageIconUrl>https://github.com/franckbour/Plugin.NFC/raw/master/art/nfc128.png</PackageIconUrl>
<PackageIcon>icon.png</PackageIcon> <PackageIcon>icon.png</PackageIcon>
<PackageTags>maui, xamarin, ios, android, xamarin.forms, plugin, NFC</PackageTags> <PackageTags>maui, xamarin, ios, android, xamarin.forms, plugin, NFC</PackageTags>
<Title>NFC Plugin for Xamarin</Title> <Title>NFC Plugin for Xamarin</Title>
<Summary>A Cross-Platform plugin to easily read and write NFC tags.</Summary> <Summary>A Cross-Platform plugin to easily read and write NFC tags.</Summary>
<Description>Cross-Platform NFC (Near Field Communication) plugin to easily read and write NFC tags in your application.</Description> <Description>Cross-Platform NFC (Near Field Communication) plugin to easily read and write NFC tags in your application.</Description>
<Owners>Franck Bour</Owners> <Owners>Franck Bour</Owners>
<Authors>Franck Bour</Authors> <Authors>Franck Bour</Authors>
<Copyright>Copyright 2022</Copyright> <Copyright>Copyright 2022</Copyright>
<!-- When built in 2019 will remove extra references on pack for iOS in System.Drawing.Common --> <!-- When built in 2019 will remove extra references on pack for iOS in System.Drawing.Common -->
<DisableExtraReferences>false</DisableExtraReferences> <DisableExtraReferences>false</DisableExtraReferences>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<GenerateDocumentationFile>false</GenerateDocumentationFile> <GenerateDocumentationFile>false</GenerateDocumentationFile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<!-- sourcelink: Publish the repository URL in the built .nupkg (in the NuSpec <Repository> element) --> <!-- sourcelink: Publish the repository URL in the built .nupkg (in the NuSpec <Repository> element) -->
<PublishRepositoryUrl>true</PublishRepositoryUrl> <PublishRepositoryUrl>true</PublishRepositoryUrl>
<!-- sourcelink: Embed source files that are not tracked by the source control manager in the PDB --> <!-- sourcelink: Embed source files that are not tracked by the source control manager in the PDB -->
<EmbedUntrackedSources>true</EmbedUntrackedSources> <EmbedUntrackedSources>true</EmbedUntrackedSources>
<!-- sourcelink: Include PDB in the built .nupkg --> <!-- sourcelink: Include PDB in the built .nupkg -->
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder> <AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<_NET8 Condition=" $(TargetFramework.Contains('net8')) ">true</_NET8> <_NET8 Condition=" $(TargetFramework.Contains('net8')) ">true</_NET8>
<_DROID Condition=" $(TargetFramework.ToLowerInvariant().Contains('droid')) ">true</_DROID> <_DROID Condition=" $(TargetFramework.ToLowerInvariant().Contains('droid')) ">true</_DROID>
<_IOS Condition=" $(TargetFramework.ToLowerInvariant().Contains('ios')) ">true</_IOS> <_IOS Condition=" $(TargetFramework.ToLowerInvariant().Contains('ios')) ">true</_IOS>
<_MOBILE Condition=" '$(_DROID)' == 'true' OR '$(_IOS)' == 'true' ">true</_MOBILE> <_MOBILE Condition=" '$(_DROID)' == 'true' OR '$(_IOS)' == 'true' ">true</_MOBILE>
<DefineConstants Condition=" '$(_DROID)' == 'true' ">$(DefineConstants);__ANDROID__;__MOBILE__;</DefineConstants> <DefineConstants Condition=" '$(_DROID)' == 'true' ">$(DefineConstants);__ANDROID__;__MOBILE__;</DefineConstants>
<DefineConstants Condition=" '$(_IOS)' == 'true' ">$(DefineConstants);__IOS__;__MOBILE__;</DefineConstants> <DefineConstants Condition=" '$(_IOS)' == 'true' ">$(DefineConstants);__IOS__;__MOBILE__;</DefineConstants>
<DefineConstants Condition=" '$(_NET8)' == 'true' ">$(DefineConstants);__NET8__;</DefineConstants> <DefineConstants Condition=" '$(_NET8)' == 'true' ">$(DefineConstants);__NET8__;</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(_NET8)' == 'true' AND '$(_MOBILE)' == 'true' "> <PropertyGroup Condition=" '$(_NET8)' == 'true' AND '$(_MOBILE)' == 'true' ">
<SupportedOSPlatformVersion Condition="'$(_IOS)' == 'true'">11.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="'$(_IOS)' == 'true'">11.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="'$(_DROID)' == 'true'">21.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="'$(_DROID)' == 'true'">21.0</SupportedOSPlatformVersion>
</PropertyGroup> </PropertyGroup>
<!-- Deterministic Builds (Azure Pipelines) --> <!-- Deterministic Builds (Azure Pipelines) -->
<PropertyGroup Condition="'$(TF_BUILD)' == 'true'"> <PropertyGroup Condition="'$(TF_BUILD)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild> <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup> </PropertyGroup>
<ItemGroup Condition=" '$(Configuration)' == 'Release' "> <ItemGroup Condition=" '$(Configuration)' == 'Release' ">
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="..\..\art\nfc128.png" PackagePath="icon.png" Pack="true" /> <None Include="..\..\art\nfc128.png" PackagePath="icon.png" Pack="true" />
<Compile Include="**\*.shared.cs" /> <Compile Include="**\*.shared.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('netstandard')) OR '$(TargetFramework)' == 'net8.0' "> <ItemGroup Condition=" $(TargetFramework.StartsWith('netstandard')) OR '$(TargetFramework)' == 'net8.0' ">
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(_DROID)' == 'true' "> <ItemGroup Condition=" '$(_DROID)' == 'true' ">
<Compile Include="**\*.android.cs" /> <Compile Include="**\*.android.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(_IOS)' == 'true' "> <ItemGroup Condition=" '$(_IOS)' == 'true' ">
<Compile Include="**\*.iOS.cs" /> <Compile Include="**\*.iOS.cs" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+73 -73
View File
@@ -1,73 +1,73 @@
using System; using System;
namespace Plugin.NFC namespace Plugin.NFC
{ {
/// <summary> /// <summary>
/// Cross NFC /// Cross NFC
/// </summary> /// </summary>
public static partial class CrossNFC public static partial class CrossNFC
{ {
static Lazy<INFC> _implementation = new Lazy<INFC>(() => CreateNFC(), System.Threading.LazyThreadSafetyMode.PublicationOnly); static Lazy<INFC> _implementation = new Lazy<INFC>(() => CreateNFC(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
/// <summary> /// <summary>
/// Gets if the plugin is supported on the current platform. /// Gets if the plugin is supported on the current platform.
/// </summary> /// </summary>
public static bool IsSupported => _implementation.Value != null; public static bool IsSupported => _implementation.Value != null;
/// <summary> /// <summary>
/// Legacy Mode (Supporting Mifare Classic on iOS) /// Legacy Mode (Supporting Mifare Classic on iOS)
/// </summary> /// </summary>
static bool _legacy = false; static bool _legacy = false;
public static bool Legacy public static bool Legacy
{ {
get get
{ {
return _legacy; return _legacy;
} }
set set
{ {
_legacy = value; _legacy = value;
_implementation = new Lazy<INFC>(() => CreateNFC(), System.Threading.LazyThreadSafetyMode.PublicationOnly); _implementation = new Lazy<INFC>(() => CreateNFC(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
} }
} }
/// <summary> /// <summary>
/// Current plugin implementation to use /// Current plugin implementation to use
/// </summary> /// </summary>
public static INFC Current public static INFC Current
{ {
get get
{ {
INFC ret = _implementation.Value; INFC ret = _implementation.Value;
if (ret == null) if (ret == null)
{ {
throw NotImplementedInReferenceAssembly(); throw NotImplementedInReferenceAssembly();
} }
return ret; return ret;
} }
} }
static INFC CreateNFC() static INFC CreateNFC()
{ {
#if NETSTANDARD || !__MOBILE__ #if NETSTANDARD || !__MOBILE__
return null; return null;
#elif __IOS__ #elif __IOS__
ObjCRuntime.Class.ThrowOnInitFailure = false; ObjCRuntime.Class.ThrowOnInitFailure = false;
if (NFCUtils.IsWritingSupported() && !Legacy) if (NFCUtils.IsWritingSupported() && !Legacy)
return new NFCImplementation(); return new NFCImplementation();
return new NFCImplementation_Before_iOS13(); return new NFCImplementation_Before_iOS13();
#else #else
#pragma warning disable IDE0022 // Use expression body for methods #pragma warning disable IDE0022 // Use expression body for methods
return new NFCImplementation(); return new NFCImplementation();
#pragma warning restore IDE0022 // Use expression body for methods #pragma warning restore IDE0022 // Use expression body for methods
#endif #endif
} }
internal static Exception NotImplementedInReferenceAssembly() => internal static Exception NotImplementedInReferenceAssembly() =>
new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."); new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.");
} }
} }
+118 -118
View File
@@ -1,118 +1,118 @@
using System; using System;
namespace Plugin.NFC namespace Plugin.NFC
{ {
#region Event delegates #region Event delegates
public delegate void NdefMessageReceivedEventHandler(ITagInfo tagInfo); public delegate void NdefMessageReceivedEventHandler(ITagInfo tagInfo);
public delegate void NdefMessagePublishedEventHandler(ITagInfo tagInfo); public delegate void NdefMessagePublishedEventHandler(ITagInfo tagInfo);
public delegate void TagDiscoveredEventHandler(ITagInfo tagInfo, bool format); public delegate void TagDiscoveredEventHandler(ITagInfo tagInfo, bool format);
public delegate void OnNfcStatusChangedEventHandler(bool isEnabled); public delegate void OnNfcStatusChangedEventHandler(bool isEnabled);
public delegate void TagListeningStatusChangedEventHandler(bool isListening); public delegate void TagListeningStatusChangedEventHandler(bool isListening);
#endregion #endregion
/// <summary> /// <summary>
/// Main interface for NFC /// Main interface for NFC
/// </summary> /// </summary>
public interface INFC public interface INFC
{ {
/// <summary> /// <summary>
/// Checks if NFC Feature is available /// Checks if NFC Feature is available
/// </summary> /// </summary>
bool IsAvailable { get; } bool IsAvailable { get; }
/// <summary> /// <summary>
/// Checks if NFC Feature is enabled /// Checks if NFC Feature is enabled
/// </summary> /// </summary>
bool IsEnabled { get; } bool IsEnabled { get; }
/// <summary> /// <summary>
/// Checks if writing mode is supported /// Checks if writing mode is supported
/// </summary> /// </summary>
bool IsWritingTagSupported { get; } bool IsWritingTagSupported { get; }
/// <summary> /// <summary>
/// NFC Configuration /// NFC Configuration
/// </summary> /// </summary>
NfcConfiguration Configuration { get; } NfcConfiguration Configuration { get; }
/// <summary> /// <summary>
/// Set Nfc configuration /// Set Nfc configuration
/// </summary> /// </summary>
/// <param name="configuration"><see cref="NfcConfiguration"/></param> /// <param name="configuration"><see cref="NfcConfiguration"/></param>
void SetConfiguration(NfcConfiguration configuration); void SetConfiguration(NfcConfiguration configuration);
/// <summary> /// <summary>
/// Starts tags detection /// Starts tags detection
/// </summary> /// </summary>
void StartListening(); void StartListening();
/// <summary> /// <summary>
/// Stops tags detection /// Stops tags detection
/// </summary> /// </summary>
void StopListening(); void StopListening();
/// <summary> /// <summary>
/// Starts tag publishing (writing or formatting) /// Starts tag publishing (writing or formatting)
/// </summary> /// </summary>
/// <param name="clearMessage">Format tag</param> /// <param name="clearMessage">Format tag</param>
void StartPublishing(bool clearMessage = false); void StartPublishing(bool clearMessage = false);
/// <summary> /// <summary>
/// Stops tag publishing /// Stops tag publishing
/// </summary> /// </summary>
void StopPublishing(); void StopPublishing();
/// <summary> /// <summary>
/// Publish or write a message on a tag /// Publish or write a message on a tag
/// </summary> /// </summary>
/// <param name="tagInfo">see <see cref="ITagInfo"/></param> /// <param name="tagInfo">see <see cref="ITagInfo"/></param>
/// <param name="makeReadOnly">make tag read-only</param> /// <param name="makeReadOnly">make tag read-only</param>
void PublishMessage(ITagInfo tagInfo, bool makeReadOnly = false); void PublishMessage(ITagInfo tagInfo, bool makeReadOnly = false);
/// <summary> /// <summary>
/// Format tag /// Format tag
/// </summary> /// </summary>
/// <param name="tagInfo">see <see cref="ITagInfo"/></param> /// <param name="tagInfo">see <see cref="ITagInfo"/></param>
void ClearMessage(ITagInfo tagInfo); void ClearMessage(ITagInfo tagInfo);
/// <summary> /// <summary>
/// Event raised when tag is connected /// Event raised when tag is connected
/// </summary> /// </summary>
event EventHandler OnTagConnected; event EventHandler OnTagConnected;
/// <summary> /// <summary>
/// Event raised when tag is disconnected /// Event raised when tag is disconnected
/// </summary> /// </summary>
event EventHandler OnTagDisconnected; event EventHandler OnTagDisconnected;
/// <summary> /// <summary>
/// Event raised when ndef message is received /// Event raised when ndef message is received
/// </summary> /// </summary>
event NdefMessageReceivedEventHandler OnMessageReceived; event NdefMessageReceivedEventHandler OnMessageReceived;
/// <summary> /// <summary>
/// Event raised when a tag is discovered (Editing) /// Event raised when a tag is discovered (Editing)
/// </summary> /// </summary>
event TagDiscoveredEventHandler OnTagDiscovered; event TagDiscoveredEventHandler OnTagDiscovered;
/// <summary> /// <summary>
/// Event raised when ndef message has been published /// Event raised when ndef message has been published
/// </summary> /// </summary>
event NdefMessagePublishedEventHandler OnMessagePublished; event NdefMessagePublishedEventHandler OnMessagePublished;
/// <summary> /// <summary>
/// Event raised when iOS NFC reading session is cancelled /// Event raised when iOS NFC reading session is cancelled
/// </summary> /// </summary>
event EventHandler OniOSReadingSessionCancelled; event EventHandler OniOSReadingSessionCancelled;
/// <summary> /// <summary>
/// Event raised when NFC status changes /// Event raised when NFC status changes
/// </summary> /// </summary>
event OnNfcStatusChangedEventHandler OnNfcStatusChanged; event OnNfcStatusChangedEventHandler OnNfcStatusChanged;
/// <summary> /// <summary>
/// Event raised when NFC listener status changes /// Event raised when NFC listener status changes
/// </summary> /// </summary>
event TagListeningStatusChangedEventHandler OnTagListeningStatusChanged; event TagListeningStatusChangedEventHandler OnTagListeningStatusChanged;
} }
} }
+104 -104
View File
@@ -1,104 +1,104 @@
namespace Plugin.NFC namespace Plugin.NFC
{ {
/// <summary> /// <summary>
/// Interface for ITagInfo /// Interface for ITagInfo
/// </summary> /// </summary>
public interface ITagInfo public interface ITagInfo
{ {
/// <summary> /// <summary>
/// Tag Raw Identifier /// Tag Raw Identifier
/// </summary> /// </summary>
byte[] Identifier { get; } byte[] Identifier { get; }
/// <summary> /// <summary>
/// Tag Serial Number /// Tag Serial Number
/// </summary> /// </summary>
string SerialNumber { get; } string SerialNumber { get; }
/// <summary> /// <summary>
/// Writable tag /// Writable tag
/// </summary> /// </summary>
bool IsWritable { get; set; } bool IsWritable { get; set; }
/// <summary> /// <summary>
/// Empty tag /// Empty tag
/// </summary> /// </summary>
bool IsEmpty { get; } bool IsEmpty { get; }
/// <summary> /// <summary>
/// Supported tag /// Supported tag
/// </summary> /// </summary>
bool IsSupported { get; } bool IsSupported { get; }
/// <summary> /// <summary>
/// Capacity of tag in bytes /// Capacity of tag in bytes
/// </summary> /// </summary>
int Capacity { get; set; } int Capacity { get; set; }
/// <summary> /// <summary>
/// Array of <see cref="NFCNdefRecord"/> of tag /// Array of <see cref="NFCNdefRecord"/> of tag
/// </summary> /// </summary>
NFCNdefRecord[] Records { get; set; } NFCNdefRecord[] Records { get; set; }
} }
/// <summary> /// <summary>
/// Class describing the information containing within a NFC tag /// Class describing the information containing within a NFC tag
/// </summary> /// </summary>
public class NFCNdefRecord public class NFCNdefRecord
{ {
/// <summary> /// <summary>
/// NDEF Type /// NDEF Type
/// </summary> /// </summary>
public NFCNdefTypeFormat TypeFormat { get; set; } public NFCNdefTypeFormat TypeFormat { get; set; }
/// <summary> /// <summary>
/// MimeType used for <see cref="NFCNdefTypeFormat.Mime"/> type /// MimeType used for <see cref="NFCNdefTypeFormat.Mime"/> type
/// </summary> /// </summary>
public string MimeType { get; set; } = "text/plain"; public string MimeType { get; set; } = "text/plain";
/// <summary> /// <summary>
/// External domain used for <see cref="NFCNdefTypeFormat.External"/> type /// External domain used for <see cref="NFCNdefTypeFormat.External"/> type
/// </summary> /// </summary>
public string ExternalDomain { get; set; } public string ExternalDomain { get; set; }
/// <summary> /// <summary>
/// External type used for <see cref="NFCNdefTypeFormat.External"/> type /// External type used for <see cref="NFCNdefTypeFormat.External"/> type
/// </summary> /// </summary>
public string ExternalType { get; set; } public string ExternalType { get; set; }
/// <summary> /// <summary>
/// Payload /// Payload
/// </summary> /// </summary>
public byte[] Payload { get; set; } public byte[] Payload { get; set; }
/// <summary> /// <summary>
/// Uri /// Uri
/// </summary> /// </summary>
public string Uri { get; set; } public string Uri { get; set; }
/// <summary> /// <summary>
/// String formatted payload /// String formatted payload
/// </summary> /// </summary>
public string Message => NFCUtils.GetMessage(TypeFormat, Payload, Uri); public string Message => NFCUtils.GetMessage(TypeFormat, Payload, Uri);
/// <summary> /// <summary>
/// Two letters ISO 639-1 Language Code (ex: en, fr, de...) /// Two letters ISO 639-1 Language Code (ex: en, fr, de...)
/// </summary> /// </summary>
public string LanguageCode { get; set; } public string LanguageCode { get; set; }
} }
/// <summary> /// <summary>
/// Enumeration of NDEF type /// Enumeration of NDEF type
/// </summary> /// </summary>
public enum NFCNdefTypeFormat public enum NFCNdefTypeFormat
{ {
Empty = 0x00, Empty = 0x00,
WellKnown = 0x01, WellKnown = 0x01,
Mime = 0x02, Mime = 0x02,
Uri = 0x03, Uri = 0x03,
External = 0x04, External = 0x04,
Unknown = 0x05, Unknown = 0x05,
Unchanged = 0x06, Unchanged = 0x06,
Reserved = 0x07 Reserved = 0x07
} }
} }
+113 -113
View File
@@ -1,113 +1,113 @@
using System.Linq; using System.Linq;
using System.Text; using System.Text;
#if __IOS__ #if __IOS__
using UIKit; using UIKit;
#endif #endif
namespace Plugin.NFC namespace Plugin.NFC
{ {
/// <summary> /// <summary>
/// NFC tools /// NFC tools
/// </summary> /// </summary>
public static class NFCUtils public static class NFCUtils
{ {
/// <summary> /// <summary>
/// Returns the content size of an array of <see cref="NFCNdefRecord"/> /// Returns the content size of an array of <see cref="NFCNdefRecord"/>
/// </summary> /// </summary>
/// <param name="records">array of <see cref="NFCNdefRecord"/></param> /// <param name="records">array of <see cref="NFCNdefRecord"/></param>
/// <returns>Content size</returns> /// <returns>Content size</returns>
internal static int GetSize(NFCNdefRecord[] records) internal static int GetSize(NFCNdefRecord[] records)
{ {
var size = 0; var size = 0;
if (records != null && records.Length > 0) if (records != null && records.Length > 0)
{ {
for (var i = 0; i < records.Length; i++) for (var i = 0; i < records.Length; i++)
{ {
if (records[i] != null) if (records[i] != null)
size += records[i].Payload.Length; size += records[i].Payload.Length;
} }
} }
return size; return size;
} }
/// <summary> /// <summary>
/// Returns the string formatted payload /// Returns the string formatted payload
/// </summary> /// </summary>
/// <param name="type">type of <see cref="NFCNdefTypeFormat"/></param> /// <param name="type">type of <see cref="NFCNdefTypeFormat"/></param>
/// <param name="payload">record payload</param> /// <param name="payload">record payload</param>
/// <param name="uri">record uri</param> /// <param name="uri">record uri</param>
/// <returns>String formatted payload</returns> /// <returns>String formatted payload</returns>
internal static string GetMessage(NFCNdefTypeFormat type, byte[] payload, string uri) internal static string GetMessage(NFCNdefTypeFormat type, byte[] payload, string uri)
{ {
string message; string message;
if (!string.IsNullOrWhiteSpace(uri)) if (!string.IsNullOrWhiteSpace(uri))
message = uri; message = uri;
else else
{ {
if (type == NFCNdefTypeFormat.WellKnown) if (type == NFCNdefTypeFormat.WellKnown)
{ {
// NDEF_WELLKNOWN Text record // NDEF_WELLKNOWN Text record
var status = payload[0]; var status = payload[0];
var enc = status & 0x80; var enc = status & 0x80;
var languageCodeLength = status & 0x3F; var languageCodeLength = status & 0x3F;
if (enc == 0) if (enc == 0)
message = Encoding.UTF8.GetString(payload, languageCodeLength + 1, payload.Length - languageCodeLength - 1); message = Encoding.UTF8.GetString(payload, languageCodeLength + 1, payload.Length - languageCodeLength - 1);
else else
message = Encoding.Unicode.GetString(payload, languageCodeLength + 1, payload.Length - languageCodeLength - 1); message = Encoding.Unicode.GetString(payload, languageCodeLength + 1, payload.Length - languageCodeLength - 1);
} }
else else
{ {
// Other NDEF types // Other NDEF types
message = Encoding.UTF8.GetString(payload, 0, payload.Length); message = Encoding.UTF8.GetString(payload, 0, payload.Length);
} }
} }
return message; return message;
} }
/// <summary> /// <summary>
/// Transforms a string message into an array of bytes /// Transforms a string message into an array of bytes
/// </summary> /// </summary>
/// <param name="text">text message</param> /// <param name="text">text message</param>
/// <returns>Array of bytes</returns> /// <returns>Array of bytes</returns>
public static byte[] EncodeToByteArray(string text) => Encoding.UTF8.GetBytes(text); public static byte[] EncodeToByteArray(string text) => Encoding.UTF8.GetBytes(text);
/// <summary> /// <summary>
/// Returns the string formatted payload /// Returns the string formatted payload
/// </summary> /// </summary>
/// <param name="record">Object <see cref="NFCNdefRecord"/></param> /// <param name="record">Object <see cref="NFCNdefRecord"/></param>
/// <returns>String formatted payload</returns> /// <returns>String formatted payload</returns>
public static string GetMessage(NFCNdefRecord record) public static string GetMessage(NFCNdefRecord record)
{ {
if (record == null) if (record == null)
return string.Empty; return string.Empty;
return GetMessage(record.TypeFormat, record.Payload, record.Uri); return GetMessage(record.TypeFormat, record.Payload, record.Uri);
} }
/// <summary> /// <summary>
/// Convert bytes array into hexadecimal string /// Convert bytes array into hexadecimal string
/// </summary> /// </summary>
/// <param name="bytes">Bytes Array</param> /// <param name="bytes">Bytes Array</param>
/// <param name="separator">Separator</param> /// <param name="separator">Separator</param>
/// <returns>Hexadecimal string</returns> /// <returns>Hexadecimal string</returns>
public static string ByteArrayToHexString(byte[] bytes, string separator = null) public static string ByteArrayToHexString(byte[] bytes, string separator = null)
{ {
return bytes == null ? string.Empty : string.Join(separator ?? string.Empty, bytes.Select(b => b.ToString("X2"))); return bytes == null ? string.Empty : string.Join(separator ?? string.Empty, bytes.Select(b => b.ToString("X2")));
} }
/// <summary> /// <summary>
/// Checks if writing tags is supported /// Checks if writing tags is supported
/// </summary> /// </summary>
/// <returns>boolean</returns> /// <returns>boolean</returns>
public static bool IsWritingSupported() public static bool IsWritingSupported()
{ {
#if __IOS__ #if __IOS__
var splitted = UIDevice.CurrentDevice.SystemVersion?.Split('.'); var splitted = UIDevice.CurrentDevice.SystemVersion?.Split('.');
if (splitted != null && splitted.Length > 0 && int.TryParse(splitted[0], out var majorVersion)) if (splitted != null && splitted.Length > 0 && int.TryParse(splitted[0], out var majorVersion))
return majorVersion >= 13; return majorVersion >= 13;
return false; return false;
#else #else
return true; return true;
#endif #endif
} }
} }
} }
+282 -282
View File
@@ -1,282 +1,282 @@
namespace Plugin.NFC namespace Plugin.NFC
{ {
/// <summary> /// <summary>
/// NFC Configuration class /// NFC Configuration class
/// </summary> /// </summary>
public class NfcConfiguration public class NfcConfiguration
{ {
/// <summary> /// <summary>
/// List of user defined messages /// List of user defined messages
/// </summary> /// </summary>
public UserDefinedMessages Messages { get; set; } public UserDefinedMessages Messages { get; set; }
/// <summary> /// <summary>
/// Sets ISO 639-1 Language Code for all ndef records (default is "en") /// Sets ISO 639-1 Language Code for all ndef records (default is "en")
/// </summary> /// </summary>
public string DefaultLanguageCode { get; set; } public string DefaultLanguageCode { get; set; }
/// <summary> /// <summary>
/// Update Nfc Configuration with a new configuration object /// Update Nfc Configuration with a new configuration object
/// </summary> /// </summary>
/// <param name="newCfg"><see cref="NfcConfiguration"/></param> /// <param name="newCfg"><see cref="NfcConfiguration"/></param>
public void Update(NfcConfiguration newCfg) public void Update(NfcConfiguration newCfg)
{ {
if (newCfg == null || newCfg.Messages == null) if (newCfg == null || newCfg.Messages == null)
return; return;
Messages = newCfg.Messages; Messages = newCfg.Messages;
DefaultLanguageCode = newCfg.DefaultLanguageCode; DefaultLanguageCode = newCfg.DefaultLanguageCode;
} }
/// <summary> /// <summary>
/// Get the default Nfc configuration /// Get the default Nfc configuration
/// </summary> /// </summary>
/// <returns>Default <see cref="NfcConfiguration"/></returns> /// <returns>Default <see cref="NfcConfiguration"/></returns>
public static NfcConfiguration GetDefaultConfiguration() public static NfcConfiguration GetDefaultConfiguration()
=> new NfcConfiguration { Messages = new UserDefinedMessages(), DefaultLanguageCode = "en" }; => new NfcConfiguration { Messages = new UserDefinedMessages(), DefaultLanguageCode = "en" };
} }
/// <summary> /// <summary>
/// User defined UI messages /// User defined UI messages
/// </summary> /// </summary>
public class UserDefinedMessages public class UserDefinedMessages
{ {
string _nfcSessionInvalidated = "Session Invalidated"; string _nfcSessionInvalidated = "Session Invalidated";
string _nfcSessionInvalidatedButton = "OK"; string _nfcSessionInvalidatedButton = "OK";
string _nfcWritingNotSupported = "Writing NFC Tag is not supported on this device"; string _nfcWritingNotSupported = "Writing NFC Tag is not supported on this device";
string _nfcDialogAlertMessage = "Please hold your phone near a NFC tag"; string _nfcDialogAlertMessage = "Please hold your phone near a NFC tag";
string _nfcErrorRead = "Read error. Please try again"; string _nfcErrorRead = "Read error. Please try again";
string _nfcErrorEmptyTag = "Tag is empty"; string _nfcErrorEmptyTag = "Tag is empty";
string _nfcErrorReadOnlyTag = "Tag is not writable"; string _nfcErrorReadOnlyTag = "Tag is not writable";
string _nfcErrorCapacityTag = "Tag's capacity is too low"; string _nfcErrorCapacityTag = "Tag's capacity is too low";
string _nfcErrorMissingTag = "Tag is missing"; string _nfcErrorMissingTag = "Tag is missing";
string _nfcErrorMissingTagInfo = "No Tag Informations: nothing to write"; string _nfcErrorMissingTagInfo = "No Tag Informations: nothing to write";
string _nfcErrorNotSupportedTag = "Tag is not supported"; string _nfcErrorNotSupportedTag = "Tag is not supported";
string _nfcErrorNotCompliantTag = "Tag is not NDEF compliant"; string _nfcErrorNotCompliantTag = "Tag is not NDEF compliant";
string _nfcErrorWrite = "Nothing to write"; string _nfcErrorWrite = "Nothing to write";
string _nfcSuccessRead = "Read Operation Successful"; string _nfcSuccessRead = "Read Operation Successful";
string _nfcSuccessWrite = "Write Operation Successful"; string _nfcSuccessWrite = "Write Operation Successful";
string _nfcSuccessClear = "Clear Operation Successful"; string _nfcSuccessClear = "Clear Operation Successful";
string _nfcSessionTimeout = "session timeout"; string _nfcSessionTimeout = "session timeout";
/// <summary> /// <summary>
/// Session timeout /// Session timeout
/// </summary> /// </summary>
public string NFCSessionTimeout public string NFCSessionTimeout
{ {
get => _nfcSessionTimeout; get => _nfcSessionTimeout;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcSessionTimeout = value; _nfcSessionTimeout = value;
} }
} }
/// <summary> /// <summary>
/// Session invalidated /// Session invalidated
/// </summary> /// </summary>
public string NFCSessionInvalidatedButton public string NFCSessionInvalidatedButton
{ {
get => _nfcSessionInvalidatedButton; get => _nfcSessionInvalidatedButton;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcSessionInvalidatedButton = value; _nfcSessionInvalidatedButton = value;
} }
} }
/// <summary> /// <summary>
/// Session invalidated /// Session invalidated
/// </summary> /// </summary>
public string NFCSessionInvalidated public string NFCSessionInvalidated
{ {
get => _nfcSessionInvalidated; get => _nfcSessionInvalidated;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcSessionInvalidated = value; _nfcSessionInvalidated = value;
} }
} }
/// <summary> /// <summary>
/// Writing feature not supported /// Writing feature not supported
/// </summary> /// </summary>
public string NFCWritingNotSupported public string NFCWritingNotSupported
{ {
get => _nfcWritingNotSupported; get => _nfcWritingNotSupported;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcWritingNotSupported = value; _nfcWritingNotSupported = value;
} }
} }
/// <summary> /// <summary>
/// [iOS] NFC Scan dialog alert message /// [iOS] NFC Scan dialog alert message
/// </summary> /// </summary>
public string NFCDialogAlertMessage public string NFCDialogAlertMessage
{ {
get => _nfcDialogAlertMessage; get => _nfcDialogAlertMessage;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcDialogAlertMessage = value; _nfcDialogAlertMessage = value;
} }
} }
/// <summary> /// <summary>
/// Read operation error /// Read operation error
/// </summary> /// </summary>
public string NFCErrorRead public string NFCErrorRead
{ {
get => _nfcErrorRead; get => _nfcErrorRead;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorRead = value; _nfcErrorRead = value;
} }
} }
/// <summary> /// <summary>
/// Write operation error /// Write operation error
/// </summary> /// </summary>
public string NFCErrorWrite public string NFCErrorWrite
{ {
get => _nfcErrorWrite; get => _nfcErrorWrite;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorWrite = value; _nfcErrorWrite = value;
} }
} }
/// <summary> /// <summary>
/// Empty tag error /// Empty tag error
/// </summary> /// </summary>
public string NFCErrorEmptyTag public string NFCErrorEmptyTag
{ {
get => _nfcErrorEmptyTag; get => _nfcErrorEmptyTag;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorEmptyTag = value; _nfcErrorEmptyTag = value;
} }
} }
/// <summary> /// <summary>
/// Read-only tag error /// Read-only tag error
/// </summary> /// </summary>
public string NFCErrorReadOnlyTag public string NFCErrorReadOnlyTag
{ {
get => _nfcErrorReadOnlyTag; get => _nfcErrorReadOnlyTag;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorReadOnlyTag = value; _nfcErrorReadOnlyTag = value;
} }
} }
/// <summary> /// <summary>
/// Tag capacity error /// Tag capacity error
/// </summary> /// </summary>
public string NFCErrorCapacityTag public string NFCErrorCapacityTag
{ {
get => _nfcErrorCapacityTag; get => _nfcErrorCapacityTag;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorCapacityTag = value; _nfcErrorCapacityTag = value;
} }
} }
/// <summary> /// <summary>
/// Missing tag error /// Missing tag error
/// </summary> /// </summary>
public string NFCErrorMissingTag public string NFCErrorMissingTag
{ {
get => _nfcErrorMissingTag; get => _nfcErrorMissingTag;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorMissingTag = value; _nfcErrorMissingTag = value;
} }
} }
/// <summary> /// <summary>
/// Missing tag info error /// Missing tag info error
/// </summary> /// </summary>
public string NFCErrorMissingTagInfo public string NFCErrorMissingTagInfo
{ {
get => _nfcErrorMissingTagInfo; get => _nfcErrorMissingTagInfo;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorMissingTagInfo = value; _nfcErrorMissingTagInfo = value;
} }
} }
/// <summary> /// <summary>
/// Not supported tag error /// Not supported tag error
/// </summary> /// </summary>
public string NFCErrorNotSupportedTag public string NFCErrorNotSupportedTag
{ {
get => _nfcErrorNotSupportedTag; get => _nfcErrorNotSupportedTag;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorNotSupportedTag = value; _nfcErrorNotSupportedTag = value;
} }
} }
/// <summary> /// <summary>
/// Not NDEF compliant tag error /// Not NDEF compliant tag error
/// </summary> /// </summary>
public string NFCErrorNotCompliantTag public string NFCErrorNotCompliantTag
{ {
get => _nfcErrorNotCompliantTag; get => _nfcErrorNotCompliantTag;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcErrorNotCompliantTag = value; _nfcErrorNotCompliantTag = value;
} }
} }
/// <summary> /// <summary>
/// [iOS] Successful read operation message /// [iOS] Successful read operation message
/// </summary> /// </summary>
public string NFCSuccessRead public string NFCSuccessRead
{ {
get => _nfcSuccessRead; get => _nfcSuccessRead;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcSuccessRead = value; _nfcSuccessRead = value;
} }
} }
/// <summary> /// <summary>
/// [iOS] Successful write operation message /// [iOS] Successful write operation message
/// </summary> /// </summary>
public string NFCSuccessWrite public string NFCSuccessWrite
{ {
get => _nfcSuccessWrite; get => _nfcSuccessWrite;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcSuccessWrite = value; _nfcSuccessWrite = value;
} }
} }
/// <summary> /// <summary>
/// [iOS] Successful clear operation message /// [iOS] Successful clear operation message
/// </summary> /// </summary>
public string NFCSuccessClear public string NFCSuccessClear
{ {
get => _nfcSuccessClear; get => _nfcSuccessClear;
set set
{ {
if (!string.IsNullOrWhiteSpace(value)) if (!string.IsNullOrWhiteSpace(value))
_nfcSuccessClear = value; _nfcSuccessClear = value;
} }
} }
} }
} }
+62 -62
View File
@@ -1,62 +1,62 @@
namespace Plugin.NFC namespace Plugin.NFC
{ {
/// <summary> /// <summary>
/// Default implementation of <see cref="ITagInfo"/> /// Default implementation of <see cref="ITagInfo"/>
/// </summary> /// </summary>
public class TagInfo : ITagInfo public class TagInfo : ITagInfo
{ {
public byte[] Identifier { get; } public byte[] Identifier { get; }
/// <summary> /// <summary>
/// Tag Serial Number /// Tag Serial Number
/// </summary> /// </summary>
public string SerialNumber { get; } public string SerialNumber { get; }
/// <summary> /// <summary>
/// Writable tag /// Writable tag
/// </summary> /// </summary>
public bool IsWritable { get; set; } public bool IsWritable { get; set; }
/// <summary> /// <summary>
/// Capacity of tag in bytes /// Capacity of tag in bytes
/// </summary> /// </summary>
public int Capacity { get; set; } public int Capacity { get; set; }
/// <summary> /// <summary>
/// Array of <see cref="NFCNdefRecord"/> of tag /// Array of <see cref="NFCNdefRecord"/> of tag
/// </summary> /// </summary>
public NFCNdefRecord[] Records { get; set; } public NFCNdefRecord[] Records { get; set; }
/// <summary> /// <summary>
/// Empty tag /// Empty tag
/// </summary> /// </summary>
public bool IsEmpty => Records == null || Records.Length == 0 || Records[0] == null ||Records[0].TypeFormat == NFCNdefTypeFormat.Empty; public bool IsEmpty => Records == null || Records.Length == 0 || Records[0] == null ||Records[0].TypeFormat == NFCNdefTypeFormat.Empty;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public bool IsSupported { get; private set; } public bool IsSupported { get; private set; }
/// <summary> /// <summary>
/// Default constructor /// Default constructor
/// </summary> /// </summary>
public TagInfo() public TagInfo()
{ {
IsSupported = true; IsSupported = true;
} }
/// <summary> /// <summary>
/// Custom contructor /// Custom contructor
/// </summary> /// </summary>
/// <param name="identifier">Tag Identifier</param> /// <param name="identifier">Tag Identifier</param>
/// <param name="isNdef">Is Ndef tag</param> /// <param name="isNdef">Is Ndef tag</param>
public TagInfo(byte[] identifier, bool isNdef = true) public TagInfo(byte[] identifier, bool isNdef = true)
{ {
Identifier = identifier; Identifier = identifier;
SerialNumber = NFCUtils.ByteArrayToHexString(identifier); SerialNumber = NFCUtils.ByteArrayToHexString(identifier);
IsSupported = isNdef; IsSupported = isNdef;
} }
public override string ToString() => $"TagInfo: identifier: {Identifier}, SerialNumber:{SerialNumber}, Capacity:{Capacity} bytes, IsSupported:{IsSupported}, IsEmpty:{IsEmpty}, IsWritable:{IsWritable}"; public override string ToString() => $"TagInfo: identifier: {Identifier}, SerialNumber:{SerialNumber}, Capacity:{Capacity} bytes, IsSupported:{IsSupported}, IsEmpty:{IsEmpty}, IsWritable:{IsWritable}";
} }
} }
+1303 -1303
View File
File diff suppressed because it is too large Load Diff
+46 -46
View File
@@ -1,46 +1,46 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 18
VisualStudioVersion = 17.12.35527.113 VisualStudioVersion = 18.2.11408.102 d18.0
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.API", "WorkFlowCheck.API\WorkFlowCheck.API.csproj", "{2466E04A-CB0C-4421-9074-A928F819926C}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.API", "WorkFlowCheck.API\WorkFlowCheck.API.csproj", "{2466E04A-CB0C-4421-9074-A928F819926C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.DL", "WorkFlowCheck.DL\WorkFlowCheck.DL.csproj", "{25A8C0E7-18C7-4672-ABE8-29596E7E9B72}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.DL", "WorkFlowCheck.DL\WorkFlowCheck.DL.csproj", "{25A8C0E7-18C7-4672-ABE8-29596E7E9B72}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.BL", "WorkFlowCheck.BL\WorkFlowCheck.BL.csproj", "{73049F81-7A5D-4819-ADB8-A9926672365E}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.BL", "WorkFlowCheck.BL\WorkFlowCheck.BL.csproj", "{73049F81-7A5D-4819-ADB8-A9926672365E}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.Common", "WorkFlowCheck.Common\WorkFlowCheck.Common.csproj", "{7F94D6CB-3358-4687-88E1-FA46053D6B71}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.Common", "WorkFlowCheck.Common\WorkFlowCheck.Common.csproj", "{7F94D6CB-3358-4687-88E1-FA46053D6B71}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.Web", "WorkFlowCheck.Web\WorkFlowCheck.Web.csproj", "{B4D9960A-9BCF-41DA-9103-5DABA8D2623F}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkFlowCheck.Web", "WorkFlowCheck.Web\WorkFlowCheck.Web.csproj", "{B4D9960A-9BCF-41DA-9103-5DABA8D2623F}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2466E04A-CB0C-4421-9074-A928F819926C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2466E04A-CB0C-4421-9074-A928F819926C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2466E04A-CB0C-4421-9074-A928F819926C}.Debug|Any CPU.Build.0 = Debug|Any CPU {2466E04A-CB0C-4421-9074-A928F819926C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2466E04A-CB0C-4421-9074-A928F819926C}.Release|Any CPU.ActiveCfg = Release|Any CPU {2466E04A-CB0C-4421-9074-A928F819926C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2466E04A-CB0C-4421-9074-A928F819926C}.Release|Any CPU.Build.0 = Release|Any CPU {2466E04A-CB0C-4421-9074-A928F819926C}.Release|Any CPU.Build.0 = Release|Any CPU
{25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Debug|Any CPU.Build.0 = Debug|Any CPU {25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Debug|Any CPU.Build.0 = Debug|Any CPU
{25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Release|Any CPU.ActiveCfg = Release|Any CPU {25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Release|Any CPU.ActiveCfg = Release|Any CPU
{25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Release|Any CPU.Build.0 = Release|Any CPU {25A8C0E7-18C7-4672-ABE8-29596E7E9B72}.Release|Any CPU.Build.0 = Release|Any CPU
{73049F81-7A5D-4819-ADB8-A9926672365E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {73049F81-7A5D-4819-ADB8-A9926672365E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{73049F81-7A5D-4819-ADB8-A9926672365E}.Debug|Any CPU.Build.0 = Debug|Any CPU {73049F81-7A5D-4819-ADB8-A9926672365E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{73049F81-7A5D-4819-ADB8-A9926672365E}.Release|Any CPU.ActiveCfg = Release|Any CPU {73049F81-7A5D-4819-ADB8-A9926672365E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{73049F81-7A5D-4819-ADB8-A9926672365E}.Release|Any CPU.Build.0 = Release|Any CPU {73049F81-7A5D-4819-ADB8-A9926672365E}.Release|Any CPU.Build.0 = Release|Any CPU
{7F94D6CB-3358-4687-88E1-FA46053D6B71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7F94D6CB-3358-4687-88E1-FA46053D6B71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F94D6CB-3358-4687-88E1-FA46053D6B71}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F94D6CB-3358-4687-88E1-FA46053D6B71}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F94D6CB-3358-4687-88E1-FA46053D6B71}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F94D6CB-3358-4687-88E1-FA46053D6B71}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F94D6CB-3358-4687-88E1-FA46053D6B71}.Release|Any CPU.Build.0 = Release|Any CPU {7F94D6CB-3358-4687-88E1-FA46053D6B71}.Release|Any CPU.Build.0 = Release|Any CPU
{B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Debug|Any CPU.Build.0 = Debug|Any CPU {B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Release|Any CPU.ActiveCfg = Release|Any CPU {B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Release|Any CPU.Build.0 = Release|Any CPU {B4D9960A-9BCF-41DA-9103-5DABA8D2623F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal
+12 -12
View File
@@ -1,13 +1,13 @@
{ {
"version": 1, "version": 1,
"isRoot": true, "isRoot": true,
"tools": { "tools": {
"dotnet-ef": { "dotnet-ef": {
"version": "9.0.0", "version": "9.0.0",
"commands": [ "commands": [
"dotnet-ef" "dotnet-ef"
], ],
"rollForward": false "rollForward": false
} }
} }
} }
@@ -1,440 +1,481 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Serilog; using Serilog;
using WorkFlowCheck.BL.Services; using WorkFlowCheck.BL.Services;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DataTables;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.API.Controllers
{ namespace WorkFlowCheck.API.Controllers
[Route("api/[controller]")] {
[ApiController] [Route("api/[controller]")]
public class CheckListController : ControllerBase [ApiController]
{ public class CheckListController : ControllerBase
private ICheckListService _checkListService; {
public CheckListController(ICheckListService checkListService) private ICheckListService _checkListService;
{ public CheckListController(ICheckListService checkListService)
_checkListService = checkListService; {
} _checkListService = checkListService;
}
[HttpGet("GetCheckListHeader/{id}")]
public async Task<ApiResponseDTO<CheckListHeaderDTO>> GetCheckListHeader(int id) [HttpGet("GetDashboardInfo")]
{ public async Task<ApiResponseDTO<DashboardDTO>> GetDashboardInfo()
var retVal = new ApiResponseDTO<CheckListHeaderDTO>() {
{ var retVal = new ApiResponseDTO<DashboardDTO>();
IsSuccess = true, try
}; {
var checkListHeaderDTO = await _checkListService.GetCheckListHeaderAsync(id); retVal.Data = await _checkListService.GetDashboardInfoAsync();
retVal.IsSuccess = true;
if (checkListHeaderDTO != null) }
{ catch (Exception ex)
{
retVal.IsSuccess = true; retVal.IsSuccess = false;
retVal.Data = checkListHeaderDTO; retVal.Errors.Add("A műszerfal adatainak lekérése sikertelen.");
} Log.Error(ex, "GetDashboardInfo failed");
else }
{ return retVal;
retVal.IsSuccess = false; }
retVal.Errors.Add("No data!");
} [HttpGet("GetCheckListHeader/{id}")]
public async Task<ApiResponseDTO<CheckListHeaderDTO>> GetCheckListHeader(int id)
return retVal; {
} var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
[HttpGet("CreatePDF/{id}")] {
public async Task<ApiResponseDTO<byte[]>> CreatePDF(int id) IsSuccess = true,
{ };
var retVal = new ApiResponseDTO<byte[]>() var checkListHeaderDTO = await _checkListService.GetCheckListHeaderAsync(id);
{
IsSuccess = true, if (checkListHeaderDTO != null)
}; {
var checkListHeader = await _checkListService.GetCheckListHeaderAsync(id);
var response = await _checkListService.CreateCheckListHeaderPDFAsync(id); retVal.IsSuccess = true;
retVal.Data = checkListHeaderDTO;
if (response != null) }
{ else
{
retVal.IsSuccess = true; retVal.IsSuccess = false;
retVal.Data = response; retVal.Errors.Add("No data!");
} }
else
{ return retVal;
retVal.IsSuccess = false; }
retVal.Errors.Add("No data!"); [HttpPost("GetFilteredCheckListHeader")]
} public async Task<ApiResponseListDTO<List<CheckListHeaderDTO>>> GetFilteredCheckListHeader([FromBody] DataTablesRequest dataTablesRequest)
{
return retVal; var retVal = new ApiResponseListDTO<List<CheckListHeaderDTO>>()
} {
[HttpGet("GetAllCheckListHeaders")] IsSuccess = true
public async Task<ApiResponseDTO<List<CheckListHeaderDTO>>> GetAllCheckListHeadersAsync() };
{
var retVal = new ApiResponseDTO<List<CheckListHeaderDTO>>() try
{ {
IsSuccess = true, var result = await _checkListService.GetFilteredCheckListHeaderAsync(dataTablesRequest);
}; retVal.Data = result.Data;
var checkPointListDTO = await _checkListService.GetAllCheckListHeaderAsync(); retVal.Total = result.Total;
retVal.Filtered = result.Filtered;
if (checkPointListDTO != null) }
{ catch (Exception ex)
{
retVal.IsSuccess = true; retVal.IsSuccess = false;
retVal.Data = checkPointListDTO; Log.Error(ex.Message);
} }
else return retVal;
{ }
retVal.IsSuccess = false; [HttpGet("CreatePDF/{id}")]
retVal.Errors.Add("No data!"); public async Task<ApiResponseDTO<byte[]>> CreatePDF(int id)
} {
var retVal = new ApiResponseDTO<byte[]>()
return retVal; {
} IsSuccess = true,
[HttpPost("UpdateCheckListHeader")] };
public async Task<ApiResponseDTO<CheckListHeaderDTO>> UpdateCheckListHeader([FromBody] CheckListHeaderDTO checkListHeaderDTO) var checkListHeader = await _checkListService.GetCheckListHeaderAsync(id);
{ var response = await _checkListService.CreateCheckListHeaderPDFAsync(id);
var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
{ if (response != null)
IsSuccess = true {
};
retVal.IsSuccess = true;
try retVal.Data = response;
{ }
var result = await _checkListService.UpdateCheckListHeaderAsync(checkListHeaderDTO); else
retVal.Data = result; {
retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
catch (Exception ex) }
{
retVal.IsSuccess = false; return retVal;
Log.Error(ex.Message); }
} [HttpGet("GetAllCheckListHeaders/{mode}")]
return retVal; public async Task<ApiResponseDTO<List<CheckListHeaderDTO>>> GetAllCheckListHeadersAsync(int mode = 0)
} {
[HttpPost("StartNewCheckList")] var retVal = new ApiResponseDTO<List<CheckListHeaderDTO>>()
public async Task<ApiResponseDTO<CheckListHeaderDTO>> StartNew([FromBody] CheckListHeaderNewDTO checkListHeaderNewDTO) {
{ IsSuccess = true,
var retVal = new ApiResponseDTO<CheckListHeaderDTO>() };
{ var checkPointListDTO = await _checkListService.GetAllCheckListHeaderAsync(mode);
IsSuccess = true
}; if (checkPointListDTO != null)
{
try
{ retVal.IsSuccess = true;
var response = await _checkListService.StartNewCheckListAsync(checkListHeaderNewDTO); retVal.Data = checkPointListDTO;
if (response != null) }
{ else
retVal.Data = response; {
} retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
catch (Exception ex) }
{
return retVal;
Log.Error(ex.Message); }
} [HttpPost("UpdateCheckListHeader")]
return retVal; public async Task<ApiResponseDTO<CheckListHeaderDTO>> UpdateCheckListHeader([FromBody] CheckListHeaderDTO checkListHeaderDTO)
} {
[HttpPost("CloseCheckListHeader")] var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
public async Task<ApiResponseDTO<bool>> CloseCheckListHeader([FromBody] CheckListHeaderCloseDTO checkListHeaderCloseDTO) {
{ IsSuccess = true
var retVal = new ApiResponseDTO<bool>() { IsSuccess = false }; };
try try
{ {
var result = await _checkListService.CloseCheckListHeader(checkListHeaderCloseDTO); var result = await _checkListService.UpdateCheckListHeaderAsync(checkListHeaderDTO);
retVal.Data = result; retVal.Data = result;
retVal.IsSuccess = result;
}
} catch (Exception ex)
catch (Exception ex) {
{ retVal.IsSuccess = false;
retVal.IsSuccess = false; Log.Error(ex.Message);
Log.Error(ex.Message); }
} return retVal;
return retVal; }
} [HttpPost("StartNewCheckList")]
public async Task<ApiResponseDTO<CheckListHeaderDTO>> StartNew([FromBody] CheckListHeaderNewDTO checkListHeaderNewDTO)
[HttpGet("AcceptCheckListHeader/{id}/{userId}")] {
public async Task<ApiResponseDTO<bool>> AcceptCheckListHeader(int id, int userId) var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
{ {
var retVal = new ApiResponseDTO<bool> { IsSuccess = false }; IsSuccess = true
};
var response = await _checkListService.AcceptCheckListHeaderAsync(id, userId);
try
if (response) {
{ var response = await _checkListService.StartNewCheckListAsync(checkListHeaderNewDTO);
retVal.IsSuccess = true; if (response != null)
retVal.Data = response; {
} retVal.Data = response;
else }
{ }
retVal.IsSuccess = false; catch (Exception ex)
retVal.Errors.Add("No data!"); {
}
Log.Error(ex.Message);
return retVal; }
} return retVal;
[HttpGet("BlockCheckListHeader/{id}/{userId}")] }
public async Task<ApiResponseDTO<bool>> BlockCheckListHeader(int id, int userId) [HttpPost("CloseCheckListHeader")]
{ public async Task<ApiResponseDTO<bool>> CloseCheckListHeader([FromBody] CheckListHeaderCloseDTO checkListHeaderCloseDTO)
var retVal = new ApiResponseDTO<bool> { IsSuccess = false }; {
var retVal = new ApiResponseDTO<bool>() { IsSuccess = false };
var response = await _checkListService.BlockCheckListHeaderAsync(id, userId);
try
if (response) {
{ var result = await _checkListService.CloseCheckListHeader(checkListHeaderCloseDTO);
retVal.IsSuccess = true; retVal.Data = result;
retVal.Data = response; retVal.IsSuccess = result;
}
else }
{ catch (Exception ex)
retVal.IsSuccess = false; {
retVal.Errors.Add("No data!"); retVal.IsSuccess = false;
} Log.Error(ex.Message);
}
return retVal; return retVal;
} }
[HttpGet("UnBlockCheckListHeader/{id}/{userId}")]
public async Task<ApiResponseDTO<bool>> UnBlockCheckListHeader(int id, int userId) [HttpGet("AcceptCheckListHeader/{id}/{userId}")]
{ public async Task<ApiResponseDTO<bool>> AcceptCheckListHeader(int id, int userId)
var retVal = new ApiResponseDTO<bool> { IsSuccess = false }; {
var retVal = new ApiResponseDTO<bool> { IsSuccess = false };
var response = await _checkListService.UnBlockCheckListHeaderAsync(id, userId);
var response = await _checkListService.AcceptCheckListHeaderAsync(id, userId);
if (response)
{ if (response)
retVal.IsSuccess = true; {
retVal.Data = response; retVal.IsSuccess = true;
} retVal.Data = response;
else }
{ else
retVal.IsSuccess = false; {
retVal.Errors.Add("No data!"); retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
}
return retVal;
} return retVal;
}
[HttpGet("BlockCheckListHeader/{id}/{userId}")]
[HttpGet("GetCheckListTemplateHeader/{id}")] public async Task<ApiResponseDTO<bool>> BlockCheckListHeader(int id, int userId)
public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> GetCheckListTemplateHeader(int id) {
{ var retVal = new ApiResponseDTO<bool> { IsSuccess = false };
var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
{ var response = await _checkListService.BlockCheckListHeaderAsync(id, userId);
IsSuccess = true,
}; if (response)
var CheckListTemplateHeaderDTO = await _checkListService.GetCheckListTemplateHeaderAsync(id); {
retVal.IsSuccess = true;
if (CheckListTemplateHeaderDTO != null) retVal.Data = response;
{ }
else
retVal.IsSuccess = true; {
retVal.Data = CheckListTemplateHeaderDTO; retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
else }
{
retVal.IsSuccess = false; return retVal;
retVal.Errors.Add("No data!"); }
} [HttpGet("UnBlockCheckListHeader/{id}/{userId}")]
public async Task<ApiResponseDTO<bool>> UnBlockCheckListHeader(int id, int userId)
return retVal; {
} var retVal = new ApiResponseDTO<bool> { IsSuccess = false };
[HttpGet("GetAllCheckListTemplateHeaders")]
public async Task<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>> GetAllCheckListTemplateHeadersAsync() var response = await _checkListService.UnBlockCheckListHeaderAsync(id, userId);
{
var retVal = new ApiResponseDTO<List<CheckListTemplateHeaderDTO>>() if (response)
{ {
IsSuccess = true, retVal.IsSuccess = true;
}; retVal.Data = response;
var checkPointListDTO = await _checkListService.GetAllCheckListTemplateHeaderAsync(); }
else
if (checkPointListDTO != null) {
{ retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
retVal.IsSuccess = true; }
retVal.Data = checkPointListDTO;
} return retVal;
else }
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); [HttpGet("GetCheckListTemplateHeader/{id}")]
} public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> GetCheckListTemplateHeader(int id)
{
return retVal; var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
} {
[HttpPost("UpdateCheckListTemplateHeader")] IsSuccess = true,
public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> UpdateCheckListTemplateHeader([FromBody] CheckListTemplateHeaderDTO CheckListTemplateHeaderDTO) };
{ var CheckListTemplateHeaderDTO = await _checkListService.GetCheckListTemplateHeaderAsync(id);
var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
{ if (CheckListTemplateHeaderDTO != null)
IsSuccess = true {
};
retVal.IsSuccess = true;
try retVal.Data = CheckListTemplateHeaderDTO;
{ }
var result = await _checkListService.UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO); else
retVal.Data = result; {
retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
catch (Exception ex) }
{
retVal.IsSuccess = false; return retVal;
Log.Error(ex.Message); }
} [HttpGet("GetAllCheckListTemplateHeaders")]
return retVal; public async Task<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>> GetAllCheckListTemplateHeadersAsync()
} {
[HttpGet("DeleteCheckListTemplateHeader/{id}")] var retVal = new ApiResponseDTO<List<CheckListTemplateHeaderDTO>>()
public async Task<ApiResponseDTO<bool>> DeleteCheckListTemplateHeader(int id) {
{ IsSuccess = true,
var retVal = new ApiResponseDTO<bool>() };
{ var checkPointListDTO = await _checkListService.GetAllCheckListTemplateHeaderAsync();
IsSuccess = true,
}; if (checkPointListDTO != null)
var result = await _checkListService.DeleteCheckListTemplateHeaderAsync(id); {
if (result != null) retVal.IsSuccess = true;
{ retVal.Data = checkPointListDTO;
retVal.IsSuccess = true; }
retVal.Data = result; else
} {
else retVal.IsSuccess = false;
{ retVal.Errors.Add("No data!");
retVal.IsSuccess = false; }
retVal.Errors.Add("No data!");
} return retVal;
}
return retVal; [HttpPost("UpdateCheckListTemplateHeader")]
} public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> UpdateCheckListTemplateHeader([FromBody] CheckListTemplateHeaderDTO CheckListTemplateHeaderDTO)
{
[HttpGet("CloneCheckListTemplateHeader/{id}")] var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
public async Task<ApiResponseDTO<bool>> CloneCheckListTemplateHeader(int id) {
{ IsSuccess = true
var retVal = new ApiResponseDTO<bool>() };
{
IsSuccess = true, try
}; {
var result = await _checkListService.CloneCheckListTemplateHeaderAsync(id); var result = await _checkListService.UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO);
retVal.Data = result;
if (result != null)
{ }
retVal.IsSuccess = true; catch (Exception ex)
retVal.Data = result; {
} retVal.IsSuccess = false;
else Log.Error(ex.Message);
{ }
retVal.IsSuccess = false; return retVal;
retVal.Errors.Add("No data!"); }
} [HttpGet("DeleteCheckListTemplateHeader/{id}")]
public async Task<ApiResponseDTO<bool>> DeleteCheckListTemplateHeader(int id)
return retVal; {
} var retVal = new ApiResponseDTO<bool>()
{
[HttpGet("GetCheckListTemplateRow/{id}")] IsSuccess = true,
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> GetCheckListTemplateRow(int id) };
{ var result = await _checkListService.DeleteCheckListTemplateHeaderAsync(id);
var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>()
{ if (result != null)
IsSuccess = true, {
}; retVal.IsSuccess = true;
var checkListTemplateRowDTO = await _checkListService.GetCheckListTemplateRowAsync(id); retVal.Data = result;
}
if (checkListTemplateRowDTO != null) else
{ {
retVal.IsSuccess = false;
retVal.IsSuccess = true; retVal.Errors.Add("No data!");
retVal.Data = checkListTemplateRowDTO; }
}
else return retVal;
{ }
retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); [HttpGet("CloneCheckListTemplateHeader/{id}")]
} public async Task<ApiResponseDTO<bool>> CloneCheckListTemplateHeader(int id)
{
return retVal; var retVal = new ApiResponseDTO<bool>()
} {
[HttpGet("DeleteCheckListTemplateRow/{id}")] IsSuccess = true,
public async Task<ApiResponseDTO<bool>> DeleteCheckListTemplateRow(int id) };
{ var result = await _checkListService.CloneCheckListTemplateHeaderAsync(id);
var retVal = new ApiResponseDTO<bool>()
{ if (result != null)
IsSuccess = true, {
}; retVal.IsSuccess = true;
var result = await _checkListService.DeleteCheckListTemplateRowAsync(id); retVal.Data = result;
}
if (result != null) else
{ {
retVal.IsSuccess = true; retVal.IsSuccess = false;
retVal.Data = result; retVal.Errors.Add("No data!");
} }
else
{ return retVal;
retVal.IsSuccess = false; }
retVal.Errors.Add("No data!");
} [HttpGet("GetCheckListTemplateRow/{id}")]
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> GetCheckListTemplateRow(int id)
return retVal; {
} var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>()
[HttpPost("UpdateCheckListTemplateRow")] {
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> UpdateCheckListTemplateRow([FromBody] CheckListTemplateRowDTO CheckListTemplateRowDTO) IsSuccess = true,
{ };
var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>() var checkListTemplateRowDTO = await _checkListService.GetCheckListTemplateRowAsync(id);
{
IsSuccess = true if (checkListTemplateRowDTO != null)
}; {
try retVal.IsSuccess = true;
{ retVal.Data = checkListTemplateRowDTO;
var result = await _checkListService.UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO); }
retVal.Data = result; else
{
} retVal.IsSuccess = false;
catch (Exception ex) retVal.Errors.Add("No data!");
{ }
retVal.IsSuccess = false;
Log.Error(ex.Message); return retVal;
} }
return retVal; [HttpGet("DeleteCheckListTemplateRow/{id}")]
} public async Task<ApiResponseDTO<bool>> DeleteCheckListTemplateRow(int id)
{
[HttpGet("GetCheckListRow/{id}")] var retVal = new ApiResponseDTO<bool>()
public async Task<ApiResponseDTO<CheckListRowDTO>> GetCheckListRow(int id) {
{ IsSuccess = true,
var retVal = new ApiResponseDTO<CheckListRowDTO>() };
{ var result = await _checkListService.DeleteCheckListTemplateRowAsync(id);
IsSuccess = true,
}; if (result != null)
var checkListRowDTO = await _checkListService.GetCheckListRowAsync(id); {
retVal.IsSuccess = true;
if (checkListRowDTO != null) retVal.Data = result;
{ }
else
retVal.IsSuccess = true; {
retVal.Data = checkListRowDTO; retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
else }
{
retVal.IsSuccess = false; return retVal;
retVal.Errors.Add("No data!"); }
} [HttpPost("UpdateCheckListTemplateRow")]
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> UpdateCheckListTemplateRow([FromBody] CheckListTemplateRowDTO CheckListTemplateRowDTO)
return retVal; {
} var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>()
[HttpPost("UpdateCheckListRow")] {
public async Task<ApiResponseDTO<CheckListRowDTO>> UpdateCheckListRow([FromBody] CheckListRowDTO CheckListRowDTO) IsSuccess = true
{ };
var retVal = new ApiResponseDTO<CheckListRowDTO>()
{ try
IsSuccess = true {
}; var result = await _checkListService.UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO);
retVal.Data = result;
try
{ }
var result = await _checkListService.UpdateCheckListRowAsync(CheckListRowDTO); catch (Exception ex)
retVal.Data = result; {
retVal.IsSuccess = false;
} Log.Error(ex.Message);
catch (Exception ex) }
{ return retVal;
retVal.IsSuccess = false; }
Log.Error(ex.Message);
} [HttpGet("GetCheckListRow/{id}")]
return retVal; public async Task<ApiResponseDTO<CheckListRowDTO>> GetCheckListRow(int id)
} {
} var retVal = new ApiResponseDTO<CheckListRowDTO>()
} {
IsSuccess = true,
};
var checkListRowDTO = await _checkListService.GetCheckListRowAsync(id);
if (checkListRowDTO != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListRowDTO;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpPost("UpdateCheckListRow")]
public async Task<ApiResponseDTO<CheckListRowDTO>> UpdateCheckListRow([FromBody] CheckListRowDTO CheckListRowDTO)
{
var retVal = new ApiResponseDTO<CheckListRowDTO>()
{
IsSuccess = true
};
try
{
var result = await _checkListService.UpdateCheckListRowAsync(CheckListRowDTO);
retVal.Data = result;
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
}
}
@@ -1,83 +1,83 @@
using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json; using Newtonsoft.Json;
using Serilog; using Serilog;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.API.Controllers namespace WorkFlowCheck.API.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [ApiController]
public class FCMController : ControllerBase public class FCMController : ControllerBase
{ {
private readonly IMessageService _messageService; private readonly IMessageService _messageService;
public FCMController(IMessageService messageService) public FCMController(IMessageService messageService)
{ {
_messageService = messageService; _messageService = messageService;
} }
[HttpPost("SendFCMMessage")] [HttpPost("SendFCMMessage")]
public async Task<ApiResponseDTO<bool>> SendFCMMessage([FromBody] FCMMessageDTO fCMMessageDTO) public async Task<ApiResponseDTO<bool>> SendFCMMessage([FromBody] FCMMessageDTO fCMMessageDTO)
{ {
var retVal = new ApiResponseDTO<bool>() var retVal = new ApiResponseDTO<bool>()
{ {
IsSuccess = true IsSuccess = true
}; };
try try
{ {
retVal.IsSuccess = await _messageService.SendFCMMessage(fCMMessageDTO); retVal.IsSuccess = await _messageService.SendFCMMessage(fCMMessageDTO);
} }
catch (Exception ex) catch (Exception ex)
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
[HttpPost("SendFCMMessageToLastToken")] [HttpPost("SendFCMMessageToLastToken")]
public async Task<ApiResponseDTO<bool>> SendFCMMessageToLastToken([FromBody] FCMMessageDTO fCMMessageDTO) public async Task<ApiResponseDTO<bool>> SendFCMMessageToLastToken([FromBody] FCMMessageDTO fCMMessageDTO)
{ {
var retVal = new ApiResponseDTO<bool>() var retVal = new ApiResponseDTO<bool>()
{ {
IsSuccess = true IsSuccess = true
}; };
try try
{ {
retVal.IsSuccess = await _messageService.SendFCMMessageToLastToken(fCMMessageDTO); retVal.IsSuccess = await _messageService.SendFCMMessageToLastToken(fCMMessageDTO);
} }
catch (Exception ex) catch (Exception ex)
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
[HttpPost("SendFCMToken")] [HttpPost("SendFCMToken")]
public async Task<ApiResponseDTO<bool>> SendFCMToken([FromBody] FCMMessageDTO fCMMessageDTO) public async Task<ApiResponseDTO<bool>> SendFCMToken([FromBody] FCMMessageDTO fCMMessageDTO)
{ {
var retVal = new ApiResponseDTO<bool>() var retVal = new ApiResponseDTO<bool>()
{ {
IsSuccess = true IsSuccess = true
}; };
try try
{ {
await _messageService.SendFCMTokenAsync(fCMMessageDTO.Token); await _messageService.SendFCMTokenAsync(fCMMessageDTO.Token);
} }
catch (Exception ex) catch (Exception ex)
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
} }
} }
File diff suppressed because it is too large Load Diff
@@ -1,399 +1,399 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Serilog; using Serilog;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.API.Controllers namespace WorkFlowCheck.API.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [ApiController]
public class SystemController : ControllerBase public class SystemController : ControllerBase
{ {
private readonly ISystemService _systemService; private readonly ISystemService _systemService;
public SystemController(ISystemService systemService) public SystemController(ISystemService systemService)
{ {
_systemService = systemService; _systemService = systemService;
} }
[HttpGet("GetDatabaseAndVersionInfo")] [HttpGet("GetDatabaseAndVersionInfo")]
public async Task<ApiResponseDTO<string>> GetDatabaseAndVersionInfo() public async Task<ApiResponseDTO<string>> GetDatabaseAndVersionInfo()
{ {
var retVal = new ApiResponseDTO<string>() var retVal = new ApiResponseDTO<string>()
{ {
IsSuccess = true, IsSuccess = true,
}; };
var result = await _systemService.GetDatabaseAndVersionInfoAsync(); var result = await _systemService.GetDatabaseAndVersionInfoAsync();
if (result != null) if (result != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = result; retVal.Data = result;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
return retVal; return retVal;
} }
[HttpGet("GetAllImageFiles")] [HttpGet("GetAllImageFiles")]
public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllImageFilesAsync() public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllImageFilesAsync()
{ {
var retVal = new ApiResponseDTO<List<ImageFileDTO>>() var retVal = new ApiResponseDTO<List<ImageFileDTO>>()
{ {
IsSuccess = true, IsSuccess = true,
}; };
try try
{ {
var allowedExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".tiff" }; var allowedExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".tiff" };
var imageFolder = Path.Combine(Directory.GetCurrentDirectory(), "Images"); var imageFolder = Path.Combine(Directory.GetCurrentDirectory(), "Images");
var files = Directory.GetFiles(imageFolder) var files = Directory.GetFiles(imageFolder)
.Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLower())) .Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLower()))
.Select(f => .Select(f =>
{ {
var fileInfo = new FileInfo(f); var fileInfo = new FileInfo(f);
return new return new
{ {
FileName = fileInfo.Name, FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length), FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"), CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
}; };
}); });
var checkListFileInfos = new List<ImageFileDTO>(); var checkListFileInfos = new List<ImageFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList()) foreach (var file in files.OrderBy(o => o.FileName).ToList())
{ {
var checkListFileInfoDTO = new ImageFileDTO() var checkListFileInfoDTO = new ImageFileDTO()
{ {
FileName = file.FileName, FileName = file.FileName,
FileSize = file.FileSize, FileSize = file.FileSize,
CreateDate = file.CreatedDate, CreateDate = file.CreatedDate,
}; };
checkListFileInfos.Add(checkListFileInfoDTO); checkListFileInfos.Add(checkListFileInfoDTO);
} }
if (checkListFileInfos != null) if (checkListFileInfos != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = checkListFileInfos; retVal.Data = checkListFileInfos;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
[HttpGet("GetAllPDFFiles")] [HttpGet("GetAllPDFFiles")]
public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllPDFilesAsync() public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllPDFilesAsync()
{ {
var retVal = new ApiResponseDTO<List<ImageFileDTO>>() var retVal = new ApiResponseDTO<List<ImageFileDTO>>()
{ {
IsSuccess = true, IsSuccess = true,
}; };
try try
{ {
var pdfFolder = Path.Combine(Directory.GetCurrentDirectory(), "PDF"); var pdfFolder = Path.Combine(Directory.GetCurrentDirectory(), "PDF");
var files = Directory.GetFiles(pdfFolder, "*.pdf") var files = Directory.GetFiles(pdfFolder, "*.pdf")
.Select(f => .Select(f =>
{ {
var fileInfo = new FileInfo(f); var fileInfo = new FileInfo(f);
return new return new
{ {
FileName = fileInfo.Name, FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length), FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"), CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
}; };
}); });
var checkListFileInfos = new List<ImageFileDTO>(); var checkListFileInfos = new List<ImageFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList()) foreach (var file in files.OrderBy(o => o.FileName).ToList())
{ {
var checkListFileInfoDTO = new ImageFileDTO() var checkListFileInfoDTO = new ImageFileDTO()
{ {
FileName = file.FileName, FileName = file.FileName,
FileSize = file.FileSize, FileSize = file.FileSize,
CreateDate = file.CreatedDate, CreateDate = file.CreatedDate,
}; };
checkListFileInfos.Add(checkListFileInfoDTO); checkListFileInfos.Add(checkListFileInfoDTO);
} }
if (checkListFileInfos != null) if (checkListFileInfos != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = checkListFileInfos; retVal.Data = checkListFileInfos;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
[HttpGet("GetAllLogAuditFiles")] [HttpGet("GetAllLogAuditFiles")]
public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogAuditFilesAsync() public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogAuditFilesAsync()
{ {
var retVal = new ApiResponseDTO<List<LogFileDTO>>() var retVal = new ApiResponseDTO<List<LogFileDTO>>()
{ {
IsSuccess = true, IsSuccess = true,
}; };
try try
{ {
var logAuditFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow"); var logAuditFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow");
var files = Directory.GetFiles(logAuditFiles, "*.log") var files = Directory.GetFiles(logAuditFiles, "*.log")
.Select(f => .Select(f =>
{ {
var fileInfo = new FileInfo(f); var fileInfo = new FileInfo(f);
return new return new
{ {
FileName = fileInfo.Name, FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length), FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"), CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
}; };
}); });
var checkListFileInfos = new List<LogFileDTO>(); var checkListFileInfos = new List<LogFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList()) foreach (var file in files.OrderBy(o => o.FileName).ToList())
{ {
var checkListFileInfoDTO = new LogFileDTO() var checkListFileInfoDTO = new LogFileDTO()
{ {
FileName = file.FileName, FileName = file.FileName,
FileSize = file.FileSize, FileSize = file.FileSize,
CreateDate = file.CreatedDate, CreateDate = file.CreatedDate,
}; };
checkListFileInfos.Add(checkListFileInfoDTO); checkListFileInfos.Add(checkListFileInfoDTO);
} }
if (checkListFileInfos != null) if (checkListFileInfos != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = checkListFileInfos; retVal.Data = checkListFileInfos;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
[HttpGet("GetAllLogBusinessFiles")] [HttpGet("GetAllLogBusinessFiles")]
public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogBusinessFilesAsync() public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogBusinessFilesAsync()
{ {
var retVal = new ApiResponseDTO<List<LogFileDTO>>() var retVal = new ApiResponseDTO<List<LogFileDTO>>()
{ {
IsSuccess = true, IsSuccess = true,
}; };
try try
{ {
var logBusinessFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow"); var logBusinessFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow");
var files = Directory.GetFiles(logBusinessFiles, "*.log") var files = Directory.GetFiles(logBusinessFiles, "*.log")
.Select(f => .Select(f =>
{ {
var fileInfo = new FileInfo(f); var fileInfo = new FileInfo(f);
return new return new
{ {
FileName = fileInfo.Name, FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length), FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"), CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
}; };
}); });
var checkListFileInfos = new List<LogFileDTO>(); var checkListFileInfos = new List<LogFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList()) foreach (var file in files.OrderBy(o => o.FileName).ToList())
{ {
var checkListFileInfoDTO = new LogFileDTO() var checkListFileInfoDTO = new LogFileDTO()
{ {
FileName = file.FileName, FileName = file.FileName,
FileSize = file.FileSize, FileSize = file.FileSize,
CreateDate = file.CreatedDate, CreateDate = file.CreatedDate,
}; };
checkListFileInfos.Add(checkListFileInfoDTO); checkListFileInfos.Add(checkListFileInfoDTO);
} }
if (checkListFileInfos != null) if (checkListFileInfos != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = checkListFileInfos; retVal.Data = checkListFileInfos;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
[HttpGet("DownloadFile/{filename}")] [HttpGet("DownloadFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadFile(string filename) public async Task<ApiResponseDTO<byte[]>> DownloadFile(string filename)
{ {
var retVal = new ApiResponseDTO<byte[]>() var retVal = new ApiResponseDTO<byte[]>()
{ {
IsSuccess = false, IsSuccess = false,
}; };
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Images", filename); var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Images", filename);
if (!System.IO.File.Exists(imageFile)) if (!System.IO.File.Exists(imageFile))
{ {
retVal.Errors.Add($"{filename} does not exist"); retVal.Errors.Add($"{filename} does not exist");
return retVal; return retVal;
} }
byte[] response = System.IO.File.ReadAllBytes(imageFile); byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null) if (response != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = response; retVal.Data = response;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
return retVal; return retVal;
} }
[HttpGet("DownloadPDFFile/{filename}")] [HttpGet("DownloadPDFFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadPDFFile(string filename) public async Task<ApiResponseDTO<byte[]>> DownloadPDFFile(string filename)
{ {
var retVal = new ApiResponseDTO<byte[]>() var retVal = new ApiResponseDTO<byte[]>()
{ {
IsSuccess = false, IsSuccess = false,
}; };
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "PDF", filename); var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "PDF", filename);
if (!System.IO.File.Exists(imageFile)) if (!System.IO.File.Exists(imageFile))
{ {
retVal.Errors.Add($"{filename} does not exist"); retVal.Errors.Add($"{filename} does not exist");
return retVal; return retVal;
} }
byte[] response = System.IO.File.ReadAllBytes(imageFile); byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null) if (response != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = response; retVal.Data = response;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
return retVal; return retVal;
} }
[HttpGet("DownloadAuditLogFile/{filename}")] [HttpGet("DownloadAuditLogFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadAuditLogFile(string filename) public async Task<ApiResponseDTO<byte[]>> DownloadAuditLogFile(string filename)
{ {
var retVal = new ApiResponseDTO<byte[]>() var retVal = new ApiResponseDTO<byte[]>()
{ {
IsSuccess = false, IsSuccess = false,
}; };
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow", filename); var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow", filename);
if (!System.IO.File.Exists(imageFile)) if (!System.IO.File.Exists(imageFile))
{ {
retVal.Errors.Add($"{filename} does not exist"); retVal.Errors.Add($"{filename} does not exist");
return retVal; return retVal;
} }
byte[] response = System.IO.File.ReadAllBytes(imageFile); byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null) if (response != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = response; retVal.Data = response;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
return retVal; return retVal;
} }
[HttpGet("DownloadBusinessLogFile/{filename}")] [HttpGet("DownloadBusinessLogFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadBusinessLogFile(string filename) public async Task<ApiResponseDTO<byte[]>> DownloadBusinessLogFile(string filename)
{ {
var retVal = new ApiResponseDTO<byte[]>() var retVal = new ApiResponseDTO<byte[]>()
{ {
IsSuccess = false, IsSuccess = false,
}; };
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow", filename); var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow", filename);
if (!System.IO.File.Exists(imageFile)) if (!System.IO.File.Exists(imageFile))
{ {
retVal.Errors.Add($"{filename} does not exist"); retVal.Errors.Add($"{filename} does not exist");
return retVal; return retVal;
} }
byte[] response = System.IO.File.ReadAllBytes(imageFile); byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null) if (response != null)
{ {
retVal.IsSuccess = true; retVal.IsSuccess = true;
retVal.Data = response; retVal.Data = response;
} }
else else
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); retVal.Errors.Add("No data!");
} }
return retVal; return retVal;
} }
private string FormatFileSize(long bytes) private string FormatFileSize(long bytes)
{ {
string[] sizes = { "B", "KB", "MB", "GB", "TB" }; string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes; double len = bytes;
int order = 0; int order = 0;
while (len >= 1024 && order < sizes.Length - 1) while (len >= 1024 && order < sizes.Length - 1)
{ {
order++; order++;
len /= 1024; len /= 1024;
} }
return $"{len:0.##} {sizes[order]}"; return $"{len:0.##} {sizes[order]}";
} }
} }
} }
File diff suppressed because it is too large Load Diff
@@ -1,42 +1,42 @@
namespace WorkFlowCheck.API.Middleware namespace WorkFlowCheck.API.Middleware
{ {
public class ApiKeyMiddleware public class ApiKeyMiddleware
{ {
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
private const string ApiKeyHeaderName = "X-Api-Key"; private const string ApiKeyHeaderName = "X-Api-Key";
private readonly ILogger<ApiKeyMiddleware> _logger; private readonly ILogger<ApiKeyMiddleware> _logger;
public ApiKeyMiddleware(RequestDelegate next, ILogger<ApiKeyMiddleware> logger) public ApiKeyMiddleware(RequestDelegate next, ILogger<ApiKeyMiddleware> logger)
{ {
_next = next; _next = next;
_logger = logger; _logger = logger;
} }
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context)
{ {
if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey)) if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey))
{ {
_logger.LogWarning("API Key is missing."); _logger.LogWarning("API Key is missing.");
context.Response.StatusCode = 401; // Unauthorized context.Response.StatusCode = 401; // Unauthorized
context.Response.ContentType = "text/html; charset=utf-8"; context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync("API Key hiányzik."); await context.Response.WriteAsync("API Key hiányzik.");
return; return;
} }
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>(); var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = appSettings.GetValue<string>("ApiKey"); var apiKey = appSettings.GetValue<string>("ApiKey");
if (!apiKey.Equals(extractedApiKey)) if (!apiKey.Equals(extractedApiKey))
{ {
_logger.LogWarning("Invalid API Key."); _logger.LogWarning("Invalid API Key.");
context.Response.StatusCode = 403; // Forbidden context.Response.StatusCode = 403; // Forbidden
context.Response.ContentType = "text/html; charset=utf-8"; context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync("Helytelen API Key."); await context.Response.WriteAsync("Helytelen API Key.");
return; return;
} }
await _next(context); await _next(context);
} }
} }
} }
@@ -1,55 +1,55 @@
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
namespace WorkFlowCheck.API.Middleware namespace WorkFlowCheck.API.Middleware
{ {
public class JwtMiddleware public class JwtMiddleware
{ {
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
public readonly IConfiguration _configuration; public readonly IConfiguration _configuration;
public JwtMiddleware(RequestDelegate next, IConfiguration configuration) public JwtMiddleware(RequestDelegate next, IConfiguration configuration)
{ {
_next = next; _next = next;
_configuration = configuration; _configuration = configuration;
} }
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
if (!string.IsNullOrEmpty(token) && ValidateToken(token, out var claims)) if (!string.IsNullOrEmpty(token) && ValidateToken(token, out var claims))
{ {
context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
} }
await _next(context); await _next(context);
} }
private bool ValidateToken(string token, out Claim[] claims) private bool ValidateToken(string token, out Claim[] claims)
{ {
var jwtSettings = _configuration.GetSection("Jwt"); var jwtSettings = _configuration.GetSection("Jwt");
var secretKey = jwtSettings["SecretKey"]; var secretKey = jwtSettings["SecretKey"];
claims = null; claims = null;
var tokenHandler = new JwtSecurityTokenHandler(); var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(secretKey); var key = Encoding.UTF8.GetBytes(secretKey);
try try
{ {
var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
{ {
ValidateIssuerSigningKey = true, ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key), IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false, ValidateIssuer = false,
ValidateAudience = false, ValidateAudience = false,
ClockSkew = TimeSpan.Zero ClockSkew = TimeSpan.Zero
}, out var validatedToken); }, out var validatedToken);
claims = principal.Claims.ToArray(); claims = principal.Claims.ToArray();
return true; return true;
} }
catch catch
{ {
return false; return false;
} }
} }
} }
} }
+177 -177
View File
@@ -1,177 +1,177 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using WorkFlowCheck.DL; using WorkFlowCheck.DL;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Serilog; using Serilog;
using WorkFlowCheck.BL.Mappings; using WorkFlowCheck.BL.Mappings;
using WorkFlowCheck.BL.Infra; using WorkFlowCheck.BL.Infra;
using WorkFlowCheck.DL.Seed; using WorkFlowCheck.DL.Seed;
using WorkFlowCheck.Common.RequestContext; using WorkFlowCheck.Common.RequestContext;
using WorkFlowCheck.API.RequestContext; using WorkFlowCheck.API.RequestContext;
using WorkFlowCheck.API.Middleware; using WorkFlowCheck.API.Middleware;
using Serilog.Filters; using Serilog.Filters;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
//------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------
string baseLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs"); string baseLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs");
if (!Directory.Exists(baseLogPath)) if (!Directory.Exists(baseLogPath))
Directory.CreateDirectory(baseLogPath); Directory.CreateDirectory(baseLogPath);
string auditLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "AuditFlow"); string auditLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "AuditFlow");
if (!Directory.Exists(auditLogPath)) if (!Directory.Exists(auditLogPath))
Directory.CreateDirectory(auditLogPath); Directory.CreateDirectory(auditLogPath);
string businessLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "BusinessFlow"); string businessLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "BusinessFlow");
if (!Directory.Exists(businessLogPath)) if (!Directory.Exists(businessLogPath))
Directory.CreateDirectory(businessLogPath); Directory.CreateDirectory(businessLogPath);
Log.Logger = new LoggerConfiguration() Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration) // Konfiguráció betöltése .ReadFrom.Configuration(builder.Configuration) // Konfiguráció betöltése
.WriteTo.Console() .WriteTo.Console()
.WriteTo.File("logs/log-.log", rollingInterval: RollingInterval.Day) .WriteTo.File("logs/log-.log", rollingInterval: RollingInterval.Day)
.WriteTo.Logger(lc => lc .WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.WithProperty("TAG", "AuditFlow")) .Filter.ByIncludingOnly(Matching.WithProperty("TAG", "AuditFlow"))
.WriteTo.File("Logs/AuditFlow/au-.log", rollingInterval: RollingInterval.Day) .WriteTo.File("Logs/AuditFlow/au-.log", rollingInterval: RollingInterval.Day)
) )
.WriteTo.Logger(lc => lc .WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.WithProperty("TAG", "BusinessFlow")) .Filter.ByIncludingOnly(Matching.WithProperty("TAG", "BusinessFlow"))
.WriteTo.File("Logs/BusinessFlow/bs-.log", rollingInterval: RollingInterval.Day) .WriteTo.File("Logs/BusinessFlow/bs-.log", rollingInterval: RollingInterval.Day)
) )
.CreateLogger(); .CreateLogger();
//------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------
Log.ForContext("TAG", "BusinessFlow").Information("API indítása..."); Log.ForContext("TAG", "BusinessFlow").Information("API indítása...");
builder.Services.AddAutoMapper(typeof(MapperProfile)); builder.Services.AddAutoMapper(typeof(MapperProfile));
builder.Services.AddMemoryCache(); builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IRequestContext, HttpRequestContext>(); builder.Services.AddScoped<IRequestContext, HttpRequestContext>();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options => builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString, x => x.MigrationsAssembly("WorkFlowCheck.DL"))); options.UseSqlServer(connectionString, x => x.MigrationsAssembly("WorkFlowCheck.DL")));
//DI //DI
DIConfig.DIInit(builder.Services); DIConfig.DIInit(builder.Services);
// SWAGGER !!! // SWAGGER !!!
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c => builder.Services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WorkFlowCheck API", Version = "v1" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "WorkFlowCheck API", Version = "v1" });
// API Key Auth definíció // API Key Auth definíció
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{ {
Description = "API Key szükséges. Használat: 'ApiKey: {kulcs}'", Description = "API Key szükséges. Használat: 'ApiKey: {kulcs}'",
Name = "X-Api-Key", // A fejlécek között keresendõ Name = "X-Api-Key", // A fejlécek között keresendõ
In = ParameterLocation.Header, In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey, Type = SecuritySchemeType.ApiKey,
Scheme = "ApiKey" Scheme = "ApiKey"
}); });
c.AddSecurityRequirement(new OpenApiSecurityRequirement c.AddSecurityRequirement(new OpenApiSecurityRequirement
{ {
{ {
new OpenApiSecurityScheme new OpenApiSecurityScheme
{ {
Reference = new OpenApiReference Reference = new OpenApiReference
{ {
Type = ReferenceType.SecurityScheme, Type = ReferenceType.SecurityScheme,
Id = "ApiKey" Id = "ApiKey"
}, },
Scheme = "ApiKey", Scheme = "ApiKey",
Name = "ApiKey", Name = "ApiKey",
In = ParameterLocation.Header, In = ParameterLocation.Header,
}, },
Array.Empty<string>() Array.Empty<string>()
} }
}); });
}); });
builder.Host.UseSerilog(); builder.Host.UseSerilog();
builder.Services.AddControllers() builder.Services.AddControllers()
.AddNewtonsoftJson(options => .AddNewtonsoftJson(options =>
{ {
// Itt konfigurálhatod az egyedi beállításokat // Itt konfigurálhatod az egyedi beállításokat
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}); });
builder.Services.AddCors(options => builder.Services.AddCors(options =>
{ {
options.AddDefaultPolicy(policy => options.AddDefaultPolicy(policy =>
{ {
policy.WithOrigins("*").AllowAnyMethod().AllowAnyHeader(); policy.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}); });
}); });
builder.WebHost.ConfigureKestrel(options => builder.WebHost.ConfigureKestrel(options =>
{ {
var kestrelConfig = builder.Configuration.GetSection("Kestrel"); var kestrelConfig = builder.Configuration.GetSection("Kestrel");
options.Configure(kestrelConfig); options.Configure(kestrelConfig);
}); });
var app = builder.Build(); var app = builder.Build();
//----------------- Munkakönyvtárak létrehozása ----------------------------- //----------------- Munkakönyvtárak létrehozása -----------------------------
string imageDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Images"); string imageDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Images");
if (!Directory.Exists(imageDirectory)) if (!Directory.Exists(imageDirectory))
{ {
Directory.CreateDirectory(imageDirectory); Directory.CreateDirectory(imageDirectory);
} }
string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf"); string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf");
// Ensure the Images directory exists // Ensure the Images directory exists
if (!Directory.Exists(pdfDirectory)) if (!Directory.Exists(pdfDirectory))
{ {
Directory.CreateDirectory(pdfDirectory); Directory.CreateDirectory(pdfDirectory);
} }
string downloadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Downloads"); string downloadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Downloads");
if (!Directory.Exists(downloadDirectory)) if (!Directory.Exists(downloadDirectory))
{ {
Directory.CreateDirectory(downloadDirectory); Directory.CreateDirectory(downloadDirectory);
} }
string downloadAPKDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Downloads","APK"); string downloadAPKDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Downloads","APK");
if (!Directory.Exists(downloadAPKDirectory)) if (!Directory.Exists(downloadAPKDirectory))
{ {
Directory.CreateDirectory(downloadAPKDirectory); Directory.CreateDirectory(downloadAPKDirectory);
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
using (var scope = app.Services.CreateScope()) using (var scope = app.Services.CreateScope())
{ {
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
DBInitializer.Seed(context); DBInitializer.Seed(context);
} }
// Swagger middleware // Swagger middleware
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(c => app.UseSwaggerUI(c =>
{ {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkFlowCheck API v1"); c.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkFlowCheck API v1");
}); });
} }
// Routing és endpointok // Routing és endpointok
//app.UseHttpsRedirection(); //app.UseHttpsRedirection();
app.UseRouting(); app.UseRouting();
app.UseMiddleware<ApiKeyMiddleware>(); app.UseMiddleware<ApiKeyMiddleware>();
app.UseMiddleware<JwtMiddleware>(); app.UseMiddleware<JwtMiddleware>();
app.MapControllers(); app.MapControllers();
app.UseAuthorization(); app.UseAuthorization();
app.UseCors(); app.UseCors();
Log.ForContext("TAG", "BusinessFlow").Information("API fut."); Log.ForContext("TAG", "BusinessFlow").Information("API fut.");
app.Run(); app.Run();
@@ -1,31 +1,41 @@
{ {
"profiles": { "profiles": {
"http": { "http": {
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
}, },
"dotnetRunMessages": true, "dotnetRunMessages": true,
"applicationUrl": "https://localhost:5069" "applicationUrl": "https://localhost:5069"
}, },
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
} },
}, "WSL": {
"$schema": "http://json.schemastore.org/launchsettings.json", "commandName": "WSL2",
"iisSettings": { "launchBrowser": true,
"windowsAuthentication": false, "launchUrl": "https://localhost:5069/swagger",
"anonymousAuthentication": true, "environmentVariables": {
"iisExpress": { "ASPNETCORE_ENVIRONMENT": "Development",
"applicationUrl": "http://localhost:59027/", "ASPNETCORE_URLS": "https://localhost:5069"
"sslPort": 44382 },
} "distributionName": ""
} }
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:59027/",
"sslPort": 44382
}
}
} }
@@ -1,37 +1,37 @@
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using System.Diagnostics; using System.Diagnostics;
using System.Security.Claims; using System.Security.Claims;
using WorkFlowCheck.Common.Constants; using WorkFlowCheck.Common.Constants;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Common.RequestContext; using WorkFlowCheck.Common.RequestContext;
namespace WorkFlowCheck.API.RequestContext namespace WorkFlowCheck.API.RequestContext
{ {
public class HttpRequestContext : IRequestContext public class HttpRequestContext : IRequestContext
{ {
private readonly IHttpContextAccessor _httpContextAccessor; private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IMemoryCache _memoryCache; private readonly IMemoryCache _memoryCache;
public HttpRequestContext(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache) public HttpRequestContext(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache)
{ {
_httpContextAccessor = httpContextAccessor; _httpContextAccessor = httpContextAccessor;
_memoryCache = memoryCache; _memoryCache = memoryCache;
TraceId = Activity.Current?.Id; TraceId = Activity.Current?.Id;
} }
public string TraceId { get; } public string TraceId { get; }
public int? CurrentUserId => CurrentDbUser?.Id; public int? CurrentUserId => CurrentDbUser?.Id;
public string CurrentUsername => CurrentHttpUser?.Identity.Name; public string CurrentUsername => CurrentHttpUser?.Identity.Name;
public string CurrentUserEmail => CurrentHttpUser?.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value; public string CurrentUserEmail => CurrentHttpUser?.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value;
public CancellationToken RequestAborted => _httpContextAccessor.HttpContext.RequestAborted; public CancellationToken RequestAborted => _httpContextAccessor.HttpContext.RequestAborted;
private UserDTO CurrentDbUser => _memoryCache.Get<UserDTO>(MemoryCacheNames.UsersNamePrefix + CurrentUserEmail); private UserDTO CurrentDbUser => _memoryCache.Get<UserDTO>(MemoryCacheNames.UsersNamePrefix + CurrentUserEmail);
private ClaimsPrincipal CurrentHttpUser => _httpContextAccessor.HttpContext.User; private ClaimsPrincipal CurrentHttpUser => _httpContextAccessor.HttpContext.User;
} }
} }
+57 -56
View File
@@ -1,56 +1,57 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel> <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained> <SelfContained>true</SelfContained>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>false</InvariantGlobalization> <InvariantGlobalization>false</InvariantGlobalization>
<PublishAot>false</PublishAot> <PublishAot>false</PublishAot>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled> <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup> <UserSecretsId>4081cb25-5ca2-40a1-a788-0d8396b4f50e</UserSecretsId>
<ItemGroup> </PropertyGroup>
<ProjectReference Include="..\WorkFlowCheck.BL\WorkFlowCheck.BL.csproj" /> <ItemGroup>
<ProjectReference Include="..\WorkFlowCheck.DL\WorkFlowCheck.DL.csproj" /> <ProjectReference Include="..\WorkFlowCheck.BL\WorkFlowCheck.BL.csproj" />
</ItemGroup> <ProjectReference Include="..\WorkFlowCheck.DL\WorkFlowCheck.DL.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Google.Apis.Auth" Version="1.69.0" /> <ItemGroup>
<PackageReference Include="MailKit" Version="4.11.0" /> <PackageReference Include="Google.Apis.Auth" Version="1.69.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" /> <PackageReference Include="MailKit" Version="4.11.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.12"> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" />
<PrivateAssets>all</PrivateAssets> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.12">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> </PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" /> <PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" /> <PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" /> <PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
</ItemGroup> <PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>
<ItemGroup>
<None Update="Certs\SwaggerCert.pfx"> <ItemGroup>
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <None Update="Certs\SwaggerCert.pfx">
</None> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
<None Update="Pdf\CheckList_Template_V1.docx"> </None>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <None Update="Pdf\CheckList_Template_V1.docx">
</None> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</ItemGroup> </None>
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.Development.json"> <ItemGroup>
<CopyToOutputDirectory>Never</CopyToOutputDirectory> <Content Update="appsettings.Development.json">
</Content> <CopyToOutputDirectory>Never</CopyToOutputDirectory>
</ItemGroup> </Content>
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" /> <ItemGroup>
</ItemGroup> <Folder Include="Logs\" />
</ItemGroup>
</Project>
</Project>
+11 -11
View File
@@ -1,11 +1,11 @@
@WorkFlowCheck.API_HostAddress = http://localhost:5069 @WorkFlowCheck.API_HostAddress = http://localhost:5069
GET {{WorkFlowCheck.API_HostAddress}}/todos/ GET {{WorkFlowCheck.API_HostAddress}}/todos/
Accept: application/json Accept: application/json
### ###
GET {{WorkFlowCheck.API_HostAddress}}/todos/1 GET {{WorkFlowCheck.API_HostAddress}}/todos/1
Accept: application/json Accept: application/json
### ###
@@ -1,13 +1,20 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
//"DefaultConnection": "Data Source=NSINB-37\\WFC;Initial Catalog=WFC;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False" //"DefaultConnection": "Data Source=NSINB-37\\WFC;Initial Catalog=WFC;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
//"DefaultConnection": "Data Source=WS2016DC\\SQLEXPRESS;Initial Catalog=WFC;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False", //"DefaultConnection": "Data Source=WS2016DC\\SQLEXPRESS;Initial Catalog=WFC;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False",
"DefaultConnection": "Data Source=WS2016DC\\SQLEXPRESS;Initial Catalog=WFCUAT;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False" "DefaultConnection": "Data Source=MASERVER;Initial Catalog=WFCUAT;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
} },
} "Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:59027"
}
}
}
}
+74 -74
View File
@@ -1,74 +1,74 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Data Source=WS2016DC\\SQLEXPRESS;Initial Catalog=WFCUAT;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False" "DefaultConnection": "Data Source=MASERVER;Initial Catalog=WFCUAT;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
}, },
"ApiKey": "RUJeLSpSMzVASUdaRCEzUyYxRSE0VyFISFRSJC0zRzhLM1hCSDU=", "ApiKey": "RUJeLSpSMzVASUdaRCEzUyYxRSE0VyFISFRSJC0zRzhLM1hCSDU=",
"Jwt": { "Jwt": {
"SecretKey": "9aLxV2t7RpM8BfKqZwXy3GehYJDUNTCrHkVZ", "SecretKey": "9aLxV2t7RpM8BfKqZwXy3GehYJDUNTCrHkVZ",
"Issuer": "https://wfcapi.nuvolar.hu/", "Issuer": "https://wfcapi.nuvolar.hu/",
"Audience": "wfc-application", "Audience": "wfc-application",
"TokenLifetimeMinutes": 1440 "TokenLifetimeMinutes": 1440
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Information" "Microsoft.AspNetCore": "Information"
} }
}, },
"Serilog": { "Serilog": {
"MinimumLevel": "Information", "MinimumLevel": "Information",
"WriteTo": [ "WriteTo": [
{ {
"Name": "Console" "Name": "Console"
}, },
{ {
"Name": "Logger", "Name": "Logger",
"Args": { "Args": {
"filter": "Equals(TAG, 'AuditFlow')", "filter": "Equals(TAG, 'AuditFlow')",
"writeTo": [ "writeTo": [
{ {
"Name": "File", "Name": "File",
"Args": { "Args": {
"path": "Logs/AuditFlow/log-.txt", "path": "Logs/AuditFlow/log-.txt",
"rollingInterval": "Day", "rollingInterval": "Day",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
} }
} }
] ]
} }
}, },
{ {
"Name": "Logger", "Name": "Logger",
"Args": { "Args": {
"filter": "Equals(TAG, 'BusinessFlow')", "filter": "Equals(TAG, 'BusinessFlow')",
"writeTo": [ "writeTo": [
{ {
"Name": "File", "Name": "File",
"Args": { "Args": {
"path": "Logs/BusinessFlow/log-.txt", "path": "Logs/BusinessFlow/log-.txt",
"rollingInterval": "Day", "rollingInterval": "Day",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
} }
} }
] ]
} }
} }
], ],
"Enrich": [ "FromLogContext" ] "Enrich": [ "FromLogContext" ]
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"Kestrel": { "Kestrel": {
"Endpoints": { "Endpoints": {
"Http": { "Http": {
"Url": "http://localhost:8660" "Url": "http://localhost:8660"
} }
} }
}, },
"EmailSettings": { "EmailSettings": {
"SmtpServer": "smtp.gmail.com", "SmtpServer": "smtp.gmail.com",
"SmtpPort": 587, "SmtpPort": 587,
"Username": "nuvolarsetup@gmail.com", "Username": "nuvolarsetup@gmail.com",
"Password": "reiq pgfr nxub pvrb", "Password": "reiq pgfr nxub pvrb",
"SenderName": "Nuvolar System" "SenderName": "Nuvolar System"
} }
} }
@@ -1,13 +1,13 @@
{ {
"type": "service_account", "type": "service_account",
"project_id": "com-nuvolar-wfcapp", "project_id": "com-nuvolar-wfcapp",
"private_key_id": "37642626e4a61fea715f3ef02a35d53fa9227666", "private_key_id": "37642626e4a61fea715f3ef02a35d53fa9227666",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVQKzCOgEhaQFo\nxtOYCpOc6XQNOVfNm8Z1xu1uoQtSZZIH3ivJy1IBqlyP/+sQ+7FO3Af5v90ae3rf\nvzd42QC4hrbBPyLGbVJWDHNPOzwg7bbez3waaU4i/7m4YJ61hlOObo888mjAxG8t\nz0cDEQzWPPUlLBCvtzY8Zv3jWdYaBxGUUzHxfemjTVLG7YCUjyt057HJVSH7AJpV\ndhnBi+3xlogsnK227ou/rLWoNyZVDOUaSiMor+LNiQx82eXc+UUaJgjpbI5AMk9z\n7CgAM8CSMOw7BHhCImVXaxH9rLZCsw0xpZnCJuOJKRyIMhrfcWKcHjrgkEW+xErj\nWN9lSkHRAgMBAAECggEAAwH5FUcrVom13b9bfF3ysnPdKwbNvVrLN5yDFIKV7oK1\n3Bca42u3rulIqR15doe275GVLtASL+ZfABcrslGPr1hGIqvvusdRVGL2+CjXveti\nbvgoDmVyvddwzf2S9zIiOQ2i8PHK4P8YZTg/DGmVnFPhRg7utWbMFtClw0UQQKkd\nzRwRDsw0jx9wDpP4EaO+czNvVZnnj+miL8QICN4gjbTdyQiVw2D1KzabwmozfEkM\nqTP+yH9mSC4gAEkG+X3i48QxiXZXvLflfnhF58+mT4yjIBIQbRTi0w9yLWRkcs8n\nmCq/89PZMncpNdCSJqdNOsYXgVaW8OMePxPNER2g4QKBgQDHl47N9AGyukpqEJJK\nR/8u3IwcCjLBb0wk5UxtZyz2JpoyqXoaKw7teqCqhg6lVd8MdIcVITKe0nZ+P29z\nyL+RVC+hGm/OQj6mAVyFEZptMgtQZGA2ThLY4ozZgzTW7uNyChhnUcqTiMCJ0g5g\n05imd6nQFKxI1ZfCsE7qlq6yYQKBgQC/bxKYno/6OT+9TTS+OCYVx9WJ8JCzOqFh\n/S+7qV14Bmml/JmYoSo/umxNOlKu3c7QtjU6caD/r4q/r6RHvvBxMlBu4K+vTEXh\nhFeqYORwTcEkcTDpjAGDekeJsRSxv5bg6QtsW30mtreBBC1/fOAvHD03Tz8GmFsp\nHry7b1WlcQKBgQCrnb51iix3oETh5DPVWQirI4n5hi9UMb24L81CeKepU1Hc4+qQ\nW5uvSHSjizdGpIpwLDYGThA3jeHC9gp/9Qn7DPcTQCcIo984YA1MgfFVmOUvj89G\ngmUkRdA0KuQhNzEsWk/XbvWPW9Op7YrdaLNl15iUyWHGEpo2FeEVRtEZoQKBgF5Z\nM+UcYQGGLa/y2UfXDI43izsM4YQ0JU3SJzBqbLK3FmLEeD8NT3FRRAdb81xT3ZZn\n9xvy3NKnhc6rll/17zMbBSFgg7X19YsMWtiSIIRpDgQT9XNlmWlfXtqx9+0S7B21\nPfgNr0ThUNe5Y2Mt/J+7X0BfQkTR2jwN9h665I9BAoGADx/oQLMXgKGdes4adF1Z\np9miGNsmUgXHdT+CdWkRx5uRd1a5s1Di6sOEUBPyFJ9hYc5ObRuC5q1A24ApASak\n0YCbUV1lqzFI4loXyM5ABqRTRCVGH94PXDAvsRUTTLvRIOliOeOBa8bNGGPlXtFw\nXzrkDjsz71JdNxgvT2Zz7nA=\n-----END PRIVATE KEY-----\n", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVQKzCOgEhaQFo\nxtOYCpOc6XQNOVfNm8Z1xu1uoQtSZZIH3ivJy1IBqlyP/+sQ+7FO3Af5v90ae3rf\nvzd42QC4hrbBPyLGbVJWDHNPOzwg7bbez3waaU4i/7m4YJ61hlOObo888mjAxG8t\nz0cDEQzWPPUlLBCvtzY8Zv3jWdYaBxGUUzHxfemjTVLG7YCUjyt057HJVSH7AJpV\ndhnBi+3xlogsnK227ou/rLWoNyZVDOUaSiMor+LNiQx82eXc+UUaJgjpbI5AMk9z\n7CgAM8CSMOw7BHhCImVXaxH9rLZCsw0xpZnCJuOJKRyIMhrfcWKcHjrgkEW+xErj\nWN9lSkHRAgMBAAECggEAAwH5FUcrVom13b9bfF3ysnPdKwbNvVrLN5yDFIKV7oK1\n3Bca42u3rulIqR15doe275GVLtASL+ZfABcrslGPr1hGIqvvusdRVGL2+CjXveti\nbvgoDmVyvddwzf2S9zIiOQ2i8PHK4P8YZTg/DGmVnFPhRg7utWbMFtClw0UQQKkd\nzRwRDsw0jx9wDpP4EaO+czNvVZnnj+miL8QICN4gjbTdyQiVw2D1KzabwmozfEkM\nqTP+yH9mSC4gAEkG+X3i48QxiXZXvLflfnhF58+mT4yjIBIQbRTi0w9yLWRkcs8n\nmCq/89PZMncpNdCSJqdNOsYXgVaW8OMePxPNER2g4QKBgQDHl47N9AGyukpqEJJK\nR/8u3IwcCjLBb0wk5UxtZyz2JpoyqXoaKw7teqCqhg6lVd8MdIcVITKe0nZ+P29z\nyL+RVC+hGm/OQj6mAVyFEZptMgtQZGA2ThLY4ozZgzTW7uNyChhnUcqTiMCJ0g5g\n05imd6nQFKxI1ZfCsE7qlq6yYQKBgQC/bxKYno/6OT+9TTS+OCYVx9WJ8JCzOqFh\n/S+7qV14Bmml/JmYoSo/umxNOlKu3c7QtjU6caD/r4q/r6RHvvBxMlBu4K+vTEXh\nhFeqYORwTcEkcTDpjAGDekeJsRSxv5bg6QtsW30mtreBBC1/fOAvHD03Tz8GmFsp\nHry7b1WlcQKBgQCrnb51iix3oETh5DPVWQirI4n5hi9UMb24L81CeKepU1Hc4+qQ\nW5uvSHSjizdGpIpwLDYGThA3jeHC9gp/9Qn7DPcTQCcIo984YA1MgfFVmOUvj89G\ngmUkRdA0KuQhNzEsWk/XbvWPW9Op7YrdaLNl15iUyWHGEpo2FeEVRtEZoQKBgF5Z\nM+UcYQGGLa/y2UfXDI43izsM4YQ0JU3SJzBqbLK3FmLEeD8NT3FRRAdb81xT3ZZn\n9xvy3NKnhc6rll/17zMbBSFgg7X19YsMWtiSIIRpDgQT9XNlmWlfXtqx9+0S7B21\nPfgNr0ThUNe5Y2Mt/J+7X0BfQkTR2jwN9h665I9BAoGADx/oQLMXgKGdes4adF1Z\np9miGNsmUgXHdT+CdWkRx5uRd1a5s1Di6sOEUBPyFJ9hYc5ObRuC5q1A24ApASak\n0YCbUV1lqzFI4loXyM5ABqRTRCVGH94PXDAvsRUTTLvRIOliOeOBa8bNGGPlXtFw\nXzrkDjsz71JdNxgvT2Zz7nA=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-fbsvc@com-nuvolar-wfcapp.iam.gserviceaccount.com", "client_email": "firebase-adminsdk-fbsvc@com-nuvolar-wfcapp.iam.gserviceaccount.com",
"client_id": "109975038898567298706", "client_id": "109975038898567298706",
"auth_uri": "https://accounts.google.com/o/oauth2/auth", "auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token", "token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40com-nuvolar-wfcapp.iam.gserviceaccount.com", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40com-nuvolar-wfcapp.iam.gserviceaccount.com",
"universe_domain": "googleapis.com" "universe_domain": "googleapis.com"
} }
+14 -2
View File
@@ -1,2 +1,14 @@
dotnet publish -c Release -o e:\wfcapi\ @echo off
pause
REM ha van paraméter, azt használjuk, különben default
set PUBLISH_DIR=%1
if "%PUBLISH_DIR%"=="" (
set PUBLISH_DIR=c:\Publish\wfcapi
)
echo Publish to: %PUBLISH_DIR%
dotnet publish -c Release -o "%PUBLISH_DIR%"
pause
@@ -1,225 +1,225 @@
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics; using System.Diagnostics;
namespace WorkFlowCheck.BL.DocumentGenerator namespace WorkFlowCheck.BL.DocumentGenerator
{ {
public class DokumentumGenerator public class DokumentumGenerator
{ {
public static byte[] DocxToPdfL(byte[] wordBytes, List<string> imagePaths = null) public static byte[] DocxToPdfL(byte[] wordBytes, List<string> imagePaths = null)
{ {
string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf"); string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf");
string fileName = Guid.NewGuid().ToString(); string fileName = Guid.NewGuid().ToString();
string tempWordPath = Path.Combine(pdfDirectory, fileName + ".docx"); string tempWordPath = Path.Combine(pdfDirectory, fileName + ".docx");
string tempPdfPath = Path.Combine(pdfDirectory, fileName + ".pdf"); string tempPdfPath = Path.Combine(pdfDirectory, fileName + ".pdf");
try try
{ {
// Word fájl mentése ideiglenes fájlba // Word fájl mentése ideiglenes fájlba
File.WriteAllBytes(tempWordPath, wordBytes); File.WriteAllBytes(tempWordPath, wordBytes);
if (imagePaths != null && imagePaths.Count > 0) if (imagePaths != null && imagePaths.Count > 0)
{ {
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(tempWordPath, true)) using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(tempWordPath, true))
{ {
MainDocumentPart mainPart = wordDoc.MainDocumentPart; MainDocumentPart mainPart = wordDoc.MainDocumentPart;
foreach (string imagePath in imagePaths) foreach (string imagePath in imagePaths)
{ {
if (File.Exists(imagePath)) if (File.Exists(imagePath))
{ {
InsertImageAsNewPage(mainPart, imagePath); InsertImageAsNewPage(mainPart, imagePath);
} }
} }
wordDoc.MainDocumentPart.Document.Save(); wordDoc.MainDocumentPart.Document.Save();
} }
} }
// LibreOffice parancssori konverzió // LibreOffice parancssori konverzió
ProcessStartInfo startInfo = new ProcessStartInfo ProcessStartInfo startInfo = new ProcessStartInfo
{ {
#if !DEBUG #if !DEBUG
FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs
#else #else
//FileName = "c:\\Program Files\\LibreOffice\\program\\soffice", // LibreOffice parancs //FileName = "c:\\Program Files\\LibreOffice\\program\\soffice", // LibreOffice parancs
FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs
#endif #endif
Arguments = $"--headless --convert-to pdf \"{tempWordPath}\" --outdir \"{pdfDirectory}", Arguments = $"--headless --convert-to pdf \"{tempWordPath}\" --outdir \"{pdfDirectory}",
RedirectStandardOutput = true, RedirectStandardOutput = true,
UseShellExecute = false, UseShellExecute = false,
CreateNoWindow = true CreateNoWindow = true
}; };
using (Process process = Process.Start(startInfo)) using (Process process = Process.Start(startInfo))
{ {
process.WaitForExit(); process.WaitForExit();
} }
// Ellenőrzés, hogy létrejött-e a PDF // Ellenőrzés, hogy létrejött-e a PDF
if (File.Exists(tempPdfPath)) if (File.Exists(tempPdfPath))
{ {
byte[] pdfBytes = File.ReadAllBytes(tempPdfPath); byte[] pdfBytes = File.ReadAllBytes(tempPdfPath);
// Ideiglenes fájlok törlése // Ideiglenes fájlok törlése
File.Delete(tempWordPath); File.Delete(tempWordPath);
File.Delete(tempPdfPath); File.Delete(tempPdfPath);
return pdfBytes; return pdfBytes;
} }
else else
{ {
throw new Exception("PDF konverzió sikertelen."); throw new Exception("PDF konverzió sikertelen.");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Hiba a PDF konverzió során: " + ex.Message); Console.WriteLine("Hiba a PDF konverzió során: " + ex.Message);
return null; return null;
} }
} }
private static void InsertImageAsNewPage(MainDocumentPart mainPart, string imagePath) private static void InsertImageAsNewPage(MainDocumentPart mainPart, string imagePath)
{ {
string fileName = Path.GetFileName(imagePath); string fileName = Path.GetFileName(imagePath);
// Kép méretezés – max szélesség/magasság A4 hasznos területhez igazítva // Kép méretezés – max szélesség/magasság A4 hasznos területhez igazítva
using var image = SixLabors.ImageSharp.Image.Load(imagePath); using var image = SixLabors.ImageSharp.Image.Load(imagePath);
int pixelWidth = image.Width; int pixelWidth = image.Width;
int pixelHeight = image.Height; int pixelHeight = image.Height;
long maxWidth = 5760000L; // kb. 16 cm long maxWidth = 5760000L; // kb. 16 cm
long maxHeight = 7200000L; // kb. 20 cm long maxHeight = 7200000L; // kb. 20 cm
double aspectRatio = (double)pixelHeight / pixelWidth; double aspectRatio = (double)pixelHeight / pixelWidth;
long finalWidth = maxWidth; long finalWidth = maxWidth;
long finalHeight = (long)(maxWidth * aspectRatio); long finalHeight = (long)(maxWidth * aspectRatio);
if (finalHeight > maxHeight) if (finalHeight > maxHeight)
{ {
finalHeight = maxHeight; finalHeight = maxHeight;
finalWidth = (long)(maxHeight / aspectRatio); finalWidth = (long)(maxHeight / aspectRatio);
} }
// Kép hozzáadása Word dokumentumhoz // Kép hozzáadása Word dokumentumhoz
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(imagePath, FileMode.Open)) using (FileStream stream = new FileStream(imagePath, FileMode.Open))
{ {
imagePart.FeedData(stream); imagePart.FeedData(stream);
} }
string imagePartId = mainPart.GetIdOfPart(imagePart); string imagePartId = mainPart.GetIdOfPart(imagePart);
Drawing drawing = CreateImageDrawing(imagePartId, finalWidth, finalHeight); Drawing drawing = CreateImageDrawing(imagePartId, finalWidth, finalHeight);
// Kép beillesztése középre igazítva // Kép beillesztése középre igazítva
Paragraph imageParagraph = new Paragraph(new Run(drawing)) Paragraph imageParagraph = new Paragraph(new Run(drawing))
{ {
ParagraphProperties = new ParagraphProperties( ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Center } new Justification() { Val = JustificationValues.Center }
) )
}; };
TableCell imageCell = new TableCell(imageParagraph, TableCell imageCell = new TableCell(imageParagraph,
new TableCellProperties( new TableCellProperties(
new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center }, new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center },
new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" } new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" }
)); ));
// Képes sor (magas, kitölti az oldalt) // Képes sor (magas, kitölti az oldalt)
TableRow imageRow = new TableRow(imageCell); TableRow imageRow = new TableRow(imageCell);
imageRow.AppendChild(new TableRowProperties( imageRow.AppendChild(new TableRowProperties(
new TableRowHeight() { Val = 9000, HeightType = HeightRuleValues.Exact } new TableRowHeight() { Val = 9000, HeightType = HeightRuleValues.Exact }
)); ));
// Fájlnév beillesztése középre // Fájlnév beillesztése középre
Paragraph fileNamePara = new Paragraph(new Run(new Text(fileName))) Paragraph fileNamePara = new Paragraph(new Run(new Text(fileName)))
{ {
ParagraphProperties = new ParagraphProperties( ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Center } new Justification() { Val = JustificationValues.Center }
) )
}; };
TableCell fileNameCell = new TableCell(fileNamePara, TableCell fileNameCell = new TableCell(fileNamePara,
new TableCellProperties( new TableCellProperties(
new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center }, new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center },
new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" } new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" }
)); ));
// Fájlnév sor (normál magasság) // Fájlnév sor (normál magasság)
TableRow fileNameRow = new TableRow(fileNameCell); TableRow fileNameRow = new TableRow(fileNameCell);
fileNameRow.AppendChild(new TableRowProperties( fileNameRow.AppendChild(new TableRowProperties(
new TableRowHeight() { Val = 400, HeightType = HeightRuleValues.Auto } new TableRowHeight() { Val = 400, HeightType = HeightRuleValues.Auto }
)); ));
// Táblázat – szegély nélkül, teljes oldalszélességben // Táblázat – szegély nélkül, teljes oldalszélességben
Table table = new Table( Table table = new Table(
new TableProperties( new TableProperties(
new TableWidth { Width = "10000", Type = TableWidthUnitValues.Pct }, new TableWidth { Width = "10000", Type = TableWidthUnitValues.Pct },
new TableBorders( new TableBorders(
new TopBorder { Val = BorderValues.None }, new TopBorder { Val = BorderValues.None },
new BottomBorder { Val = BorderValues.None }, new BottomBorder { Val = BorderValues.None },
new LeftBorder { Val = BorderValues.None }, new LeftBorder { Val = BorderValues.None },
new RightBorder { Val = BorderValues.None }, new RightBorder { Val = BorderValues.None },
new InsideHorizontalBorder { Val = BorderValues.None }, new InsideHorizontalBorder { Val = BorderValues.None },
new InsideVerticalBorder { Val = BorderValues.None } new InsideVerticalBorder { Val = BorderValues.None }
) )
), ),
imageRow, imageRow,
fileNameRow fileNameRow
); );
// Új oldal és a táblázat beszúrása a dokumentum végére // Új oldal és a táblázat beszúrása a dokumentum végére
Body body = mainPart.Document.Body; Body body = mainPart.Document.Body;
body.Append(new Paragraph(new Run(new Break() { Type = BreakValues.Page }))); body.Append(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
body.Append(table); body.Append(table);
} }
private static Drawing CreateImageDrawing(string relationshipId, long width, long height) private static Drawing CreateImageDrawing(string relationshipId, long width, long height)
{ {
return new Drawing( return new Drawing(
new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline( new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline(
new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = width, Cy = height }, new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = width, Cy = height },
new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent() new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent()
{ {
LeftEdge = 0L, LeftEdge = 0L,
TopEdge = 0L, TopEdge = 0L,
RightEdge = 0L, RightEdge = 0L,
BottomEdge = 0L BottomEdge = 0L
}, },
new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties() new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties()
{ {
Id = (UInt32Value)1U, Id = (UInt32Value)1U,
Name = "Inserted Image" Name = "Inserted Image"
}, },
new DocumentFormat.OpenXml.Drawing.Graphic( new DocumentFormat.OpenXml.Drawing.Graphic(
new DocumentFormat.OpenXml.Drawing.GraphicData( new DocumentFormat.OpenXml.Drawing.GraphicData(
new DocumentFormat.OpenXml.Drawing.Pictures.Picture( new DocumentFormat.OpenXml.Drawing.Pictures.Picture(
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureProperties( new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureProperties(
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualDrawingProperties() new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualDrawingProperties()
{ {
Id = (UInt32Value)0U, Id = (UInt32Value)0U,
Name = "Picture" Name = "Picture"
}, },
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureDrawingProperties()), new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureDrawingProperties()),
new DocumentFormat.OpenXml.Drawing.Pictures.BlipFill( new DocumentFormat.OpenXml.Drawing.Pictures.BlipFill(
new DocumentFormat.OpenXml.Drawing.Blip() new DocumentFormat.OpenXml.Drawing.Blip()
{ {
Embed = relationshipId Embed = relationshipId
}, },
new DocumentFormat.OpenXml.Drawing.Stretch( new DocumentFormat.OpenXml.Drawing.Stretch(
new DocumentFormat.OpenXml.Drawing.FillRectangle())), new DocumentFormat.OpenXml.Drawing.FillRectangle())),
new DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties( new DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties(
new DocumentFormat.OpenXml.Drawing.Transform2D( new DocumentFormat.OpenXml.Drawing.Transform2D(
new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L }, new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L },
new DocumentFormat.OpenXml.Drawing.Extents() { Cx = width, Cy = height }), new DocumentFormat.OpenXml.Drawing.Extents() { Cx = width, Cy = height }),
new DocumentFormat.OpenXml.Drawing.PresetGeometry( new DocumentFormat.OpenXml.Drawing.PresetGeometry(
new DocumentFormat.OpenXml.Drawing.AdjustValueList()) new DocumentFormat.OpenXml.Drawing.AdjustValueList())
{ Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle })) { Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle }))
) )
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
) )
{ DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }); { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U });
} }
} }
} }
File diff suppressed because it is too large Load Diff
@@ -1,18 +1,18 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="hu"> <html lang="hu">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Értesítés jóváhagyásról</title> <title>Értesítés jóváhagyásról</title>
</head> </head>
<body style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;"> <body style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;">
<p style="font-size: 18px;"> <p style="font-size: 18px;">
A következő munkafolyamat jóvá lett hagyva: A következő munkafolyamat jóvá lett hagyva:
</p> </p>
<p style="font-size: 28px; font-weight: bold; color: #333; margin-top: 10px;"> <p style="font-size: 28px; font-weight: bold; color: #333; margin-top: 10px;">
#DocumentNumber# #DocumentNumber#
</p> </p>
</body> </body>
</html> </html>
@@ -1,18 +1,18 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="hu"> <html lang="hu">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Megerősítő kód</title> <title>Megerősítő kód</title>
</head> </head>
<body style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;"> <body style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;">
<p style="font-size: 18px;"> <p style="font-size: 18px;">
<strong>Workflow Check Application Web</strong> megerősítő kódja: <strong>Workflow Check Application Web</strong> megerősítő kódja:
</p> </p>
<p style="font-size: 28px; font-weight: bold; color: #333; margin-top: 10px;"> <p style="font-size: 28px; font-weight: bold; color: #333; margin-top: 10px;">
#token2F# #token2F#
</p> </p>
</body> </body>
</html> </html>
+24 -24
View File
@@ -1,24 +1,24 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.BL.Services; using WorkFlowCheck.BL.Services;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
namespace WorkFlowCheck.BL.Infra namespace WorkFlowCheck.BL.Infra
{ {
public static class DIConfig public static class DIConfig
{ {
public static void DIInit(IServiceCollection service) public static void DIInit(IServiceCollection service)
{ {
service.AddScoped<IUserService, UserService>(); service.AddScoped<IUserService, UserService>();
service.AddScoped<ISyncService, SyncService>(); service.AddScoped<ISyncService, SyncService>();
service.AddScoped<ICheckListService, CheckListService>(); service.AddScoped<ICheckListService, CheckListService>();
service.AddScoped<INumberGeneratorService, NumberGeneratorService>(); service.AddScoped<INumberGeneratorService, NumberGeneratorService>();
service.AddScoped<IMessageService, MessageService>(); service.AddScoped<IMessageService, MessageService>();
service.AddScoped<ISystemService, SystemService>(); service.AddScoped<ISystemService, SystemService>();
} }
} }
} }
+91 -91
View File
@@ -1,91 +1,91 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutoMapper; using AutoMapper;
using AutoMapper.Configuration.Conventions; using AutoMapper.Configuration.Conventions;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.DL.Entities;
namespace WorkFlowCheck.BL.Mappings namespace WorkFlowCheck.BL.Mappings
{ {
public class MapperProfile : Profile public class MapperProfile : Profile
{ {
public MapperProfile() public MapperProfile()
{ {
CreateMap<User, UserDTO>().ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.UserRoles.Select(ur => ur.Role))); CreateMap<User, UserDTO>().ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.UserRoles.Select(ur => ur.Role)));
CreateMap<Role, RoleDTO>() CreateMap<Role, RoleDTO>()
.ForMember(dest => dest.ParentId, opt => opt.MapFrom(src => src.ParentId)) .ForMember(dest => dest.ParentId, opt => opt.MapFrom(src => src.ParentId))
.ForMember(dest => dest.ParentRoleName, opt => opt.MapFrom(src => src.Parent != null ? src.Parent.RoleName : null)); .ForMember(dest => dest.ParentRoleName, opt => opt.MapFrom(src => src.Parent != null ? src.Parent.RoleName : null));
CreateMap<UserRole, UserRoleDTO>() CreateMap<UserRole, UserRoleDTO>()
.ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role)) .ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role))
.ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User)); .ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User));
CreateMap<UserDTO, User>() CreateMap<UserDTO, User>()
.ForMember(dest => dest.PasswordHash, opt => opt.MapFrom<PasswordHashResolver>()); .ForMember(dest => dest.PasswordHash, opt => opt.MapFrom<PasswordHashResolver>());
CreateMap<CheckListTemplateHeader, CheckListTemplateHeaderDTO>() CreateMap<CheckListTemplateHeader, CheckListTemplateHeaderDTO>()
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows)); .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
CreateMap<CheckListTemplateRow, CheckListTemplateRowDTO>() CreateMap<CheckListTemplateRow, CheckListTemplateRowDTO>()
.ForMember(dest => dest.EquipmentDTO, opt => opt.MapFrom(src => src.Equipment)) .ForMember(dest => dest.EquipmentDTO, opt => opt.MapFrom(src => src.Equipment))
.ForMember(dest => dest.CheckPointDTO, opt => opt.MapFrom(src => src.CheckPoint)); .ForMember(dest => dest.CheckPointDTO, opt => opt.MapFrom(src => src.CheckPoint));
CreateMap<CheckPoint, CheckPointDTO>() CreateMap<CheckPoint, CheckPointDTO>()
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows)); .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
CreateMap<CheckPoint, CheckPointDTO>() CreateMap<CheckPoint, CheckPointDTO>()
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows)); .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
CreateMap<CheckPointDTO, CheckPoint>(); CreateMap<CheckPointDTO, CheckPoint>();
CreateMap<Location, LocationDTO>(); CreateMap<Location, LocationDTO>();
CreateMap<LocationDTO, Location>(); CreateMap<LocationDTO, Location>();
CreateMap<Equipment, EquipmentDTO>(); CreateMap<Equipment, EquipmentDTO>();
CreateMap<EquipmentDTO, Equipment>(); CreateMap<EquipmentDTO, Equipment>();
CreateMap<DeviceMessage, DeviceMessageDTO>(); CreateMap<DeviceMessage, DeviceMessageDTO>();
CreateMap<DeviceMessageDTO, DeviceMessage>(); CreateMap<DeviceMessageDTO, DeviceMessage>();
CreateMap<CheckListHeader, CheckListHeaderDTO>() CreateMap<CheckListHeader, CheckListHeaderDTO>()
.ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User)) .ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User))
.ForMember(dest => dest.AcceptUserId, opt => opt.MapFrom(src => src.AcceptUser != null ? src.AcceptUser.Id : (int?)null)) .ForMember(dest => dest.AcceptUserId, opt => opt.MapFrom(src => src.AcceptUser != null ? src.AcceptUser.Id : (int?)null))
.ForMember(dest => dest.AcceptUserDTO, opt => opt.MapFrom(src => src.AcceptUser)) .ForMember(dest => dest.AcceptUserDTO, opt => opt.MapFrom(src => src.AcceptUser))
.ForMember(dest => dest.CheckListRowDTO, opt => opt.MapFrom(src => src.CheckListRows)); .ForMember(dest => dest.CheckListRowDTO, opt => opt.MapFrom(src => src.CheckListRows));
CreateMap<CheckListRow, CheckListRowDTO>() CreateMap<CheckListRow, CheckListRowDTO>()
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRow)) .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRow))
.ForMember(dest => dest.Photo, opt => opt.MapFrom(src => GetImageBytes(src.PhotoFileName))); .ForMember(dest => dest.Photo, opt => opt.MapFrom(src => GetImageBytes(src.PhotoFileName)));
CreateMap<RoleCheckListTemplateHeader, RoleCheckListTemplateHeaderDTO>() CreateMap<RoleCheckListTemplateHeader, RoleCheckListTemplateHeaderDTO>()
.ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role)) .ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role))
.ForMember(dest => dest.CheckListTemplateHeaderDTO, opt => opt.MapFrom(src => src.CheckListTemplateHeader)); .ForMember(dest => dest.CheckListTemplateHeaderDTO, opt => opt.MapFrom(src => src.CheckListTemplateHeader));
} }
private byte[] GetImageBytes(string fileName) private byte[] GetImageBytes(string fileName)
{ {
try try
{ {
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Images", fileName); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Images", fileName);
if (File.Exists(filePath)) if (File.Exists(filePath))
{ {
return File.ReadAllBytes(filePath); return File.ReadAllBytes(filePath);
} }
return Array.Empty<byte>(); // Visszaad egy üres byte[]-ot, ha a fájl nem található return Array.Empty<byte>(); // Visszaad egy üres byte[]-ot, ha a fájl nem található
} }
catch (Exception) catch (Exception)
{ {
return Array.Empty<byte>(); // Hiba esetén is üres byte[]-ot ad vissza return Array.Empty<byte>(); // Hiba esetén is üres byte[]-ot ad vissza
} }
} }
} }
} }
@@ -1,20 +1,20 @@
using AutoMapper; using AutoMapper;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Common.Security; using WorkFlowCheck.Common.Security;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.DL.Entities;
namespace WorkFlowCheck.BL.Mappings namespace WorkFlowCheck.BL.Mappings
{ {
public class PasswordHashResolver : IValueResolver<UserDTO, User, string> public class PasswordHashResolver : IValueResolver<UserDTO, User, string>
{ {
public string Resolve(UserDTO source, User destination, string destMember, ResolutionContext context) public string Resolve(UserDTO source, User destination, string destMember, ResolutionContext context)
{ {
return PasswordHasher.HashPassword(source.Password); return PasswordHasher.HashPassword(source.Password);
} }
} }
} }
+17 -17
View File
@@ -1,17 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.BL.Models namespace WorkFlowCheck.BL.Models
{ {
public class EmailSettings public class EmailSettings
{ {
public string SmtpServer { get; set; } = string.Empty; public string SmtpServer { get; set; } = string.Empty;
public int SmtpPort { get; set; } public int SmtpPort { get; set; }
public string Username { get; set; } = string.Empty; public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
} }
} }
+149 -149
View File
@@ -1,149 +1,149 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Serilog; using Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.DL; using WorkFlowCheck.DL;
namespace WorkFlowCheck.BL.Services namespace WorkFlowCheck.BL.Services
{ {
public class BaseService public class BaseService
{ {
public readonly AppDbContext _dbContext; public readonly AppDbContext _dbContext;
public readonly IMapper _mapper; public readonly IMapper _mapper;
private readonly ILogger _logger; private readonly ILogger _logger;
public BaseService(AppDbContext db_dbContext, IMapper mapper) public BaseService(AppDbContext db_dbContext, IMapper mapper)
{ {
_dbContext = db_dbContext; _dbContext = db_dbContext;
_mapper = mapper; _mapper = mapper;
_logger = Log.ForContext("Tag", "PROGSEC"); _logger = Log.ForContext("Tag", "PROGSEC");
} }
public async Task<bool> DeleteEntityByIdAsync<T>(int id) where T : class public async Task<bool> DeleteEntityByIdAsync<T>(int id) where T : class
{ {
try try
{ {
var entity = await _dbContext.Set<T>().FindAsync(id); var entity = await _dbContext.Set<T>().FindAsync(id);
if (entity == null) if (entity == null)
return false; return false;
_dbContext.Set<T>().Remove(entity); _dbContext.Set<T>().Remove(entity);
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error($"Hiba történt a törlés során: {ex.Message}"); Log.Error($"Hiba történt a törlés során: {ex.Message}");
return false; return false;
} }
} }
public async Task<T?> GetEntityByIdAsync<T>(int id) where T : class public async Task<T?> GetEntityByIdAsync<T>(int id) where T : class
{ {
try try
{ {
var entity = await _dbContext.Set<T>().FindAsync(id); var entity = await _dbContext.Set<T>().FindAsync(id);
return entity; return entity;
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error($"Hiba történt a lekérdezés során: {ex.Message}"); Log.Error($"Hiba történt a lekérdezés során: {ex.Message}");
return null; return null;
} }
} }
public async Task<List<TEntity>> GetEntityByFilterAsync<TEntity, TFilter>(TFilter filter) where TEntity : class where TFilter : class public async Task<List<TEntity>> GetEntityByFilterAsync<TEntity, TFilter>(TFilter filter) where TEntity : class where TFilter : class
{ {
try try
{ {
IQueryable<TEntity> query = _dbContext.Set<TEntity>(); IQueryable<TEntity> query = _dbContext.Set<TEntity>();
foreach (var property in typeof(TFilter).GetProperties()) foreach (var property in typeof(TFilter).GetProperties())
{ {
var value = property.GetValue(filter); var value = property.GetValue(filter);
if (value != null) if (value != null)
{ {
var parameter = Expression.Parameter(typeof(TEntity), "x"); var parameter = Expression.Parameter(typeof(TEntity), "x");
var member = Expression.Property(parameter, property.Name); var member = Expression.Property(parameter, property.Name);
var constant = Expression.Constant(value); var constant = Expression.Constant(value);
var equal = Expression.Equal(member, constant); var equal = Expression.Equal(member, constant);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter); var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
query = query.Where(lambda); query = query.Where(lambda);
} }
} }
// Adatok lekérdezése // Adatok lekérdezése
return await query.ToListAsync(); return await query.ToListAsync();
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error($"Hiba történt a lekérdezés során: {ex.Message}"); Log.Error($"Hiba történt a lekérdezés során: {ex.Message}");
return new List<TEntity>(); return new List<TEntity>();
} }
} }
public async Task<PagedResult<TEntity>> GetPagedEntityByFilterAsync<TEntity, TFilter>(TFilter filter, int pageNumber, int pageSize) where TEntity : class where TFilter : class public async Task<PagedResult<TEntity>> GetPagedEntityByFilterAsync<TEntity, TFilter>(TFilter filter, int pageNumber, int pageSize) where TEntity : class where TFilter : class
{ {
try try
{ {
// Az IQueryable típusú lista létrehozása // Az IQueryable típusú lista létrehozása
IQueryable<TEntity> query = _dbContext.Set<TEntity>(); IQueryable<TEntity> query = _dbContext.Set<TEntity>();
// Dinamikus szűrés a filter tulajdonságai alapján // Dinamikus szűrés a filter tulajdonságai alapján
foreach (var property in typeof(TFilter).GetProperties()) foreach (var property in typeof(TFilter).GetProperties())
{ {
var value = property.GetValue(filter); var value = property.GetValue(filter);
if (value != null) if (value != null)
{ {
var parameter = Expression.Parameter(typeof(TEntity), "x"); var parameter = Expression.Parameter(typeof(TEntity), "x");
var member = Expression.Property(parameter, property.Name); var member = Expression.Property(parameter, property.Name);
var constant = Expression.Constant(value); var constant = Expression.Constant(value);
var equal = Expression.Equal(member, constant); var equal = Expression.Equal(member, constant);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter); var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
query = query.Where(lambda); query = query.Where(lambda);
} }
} }
// Teljes rekordok száma a szűrő után // Teljes rekordok száma a szűrő után
int totalCount = await query.CountAsync(); int totalCount = await query.CountAsync();
// Lapozás alkalmazása // Lapozás alkalmazása
var items = await query var items = await query
.Skip((pageNumber - 1) * pageSize) .Skip((pageNumber - 1) * pageSize)
.Take(pageSize) .Take(pageSize)
.ToListAsync(); .ToListAsync();
// Lapozási eredmény összerakása // Lapozási eredmény összerakása
return new PagedResult<TEntity> return new PagedResult<TEntity>
{ {
Items = items, Items = items,
TotalCount = totalCount, TotalCount = totalCount,
PageNumber = pageNumber, PageNumber = pageNumber,
PageSize = pageSize PageSize = pageSize
}; };
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Hiba történt a lekérdezés során: {ex.Message}"); Console.WriteLine($"Hiba történt a lekérdezés során: {ex.Message}");
return new PagedResult<TEntity>(); return new PagedResult<TEntity>();
} }
} }
} }
public class PagedResult<TEntity> public class PagedResult<TEntity>
{ {
public List<TEntity> Items { get; set; } = new List<TEntity>(); public List<TEntity> Items { get; set; } = new List<TEntity>();
public int TotalCount { get; set; } public int TotalCount { get; set; }
public int PageNumber { get; set; } public int PageNumber { get; set; }
public int PageSize { get; set; } public int PageSize { get; set; }
} }
} }
File diff suppressed because it is too large Load Diff
@@ -1,35 +1,38 @@
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DataTables;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services.Interfaces
{ namespace WorkFlowCheck.BL.Services.Interfaces
{
public interface ICheckListService public interface ICheckListService
{ {
Task<DashboardDTO> GetDashboardInfoAsync();
Task<CheckListHeaderDTO> GetCheckListHeaderAsync(int Id); Task<CheckListHeaderDTO> GetCheckListHeaderAsync(int Id);
Task<List<CheckListHeaderDTO>> GetAllCheckListHeaderAsync(); Task<ApiResponseListDTO<List<CheckListHeaderDTO>>> GetFilteredCheckListHeaderAsync(DataTablesRequest dataTablesRequest);
Task<CheckListHeaderDTO> UpdateCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO); Task<List<CheckListHeaderDTO>> GetAllCheckListHeaderAsync(int mode = 0);
Task<bool> AcceptCheckListHeaderAsync(int id, int userid); Task<CheckListHeaderDTO> UpdateCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO);
Task<bool> BlockCheckListHeaderAsync(int id, int userid); Task<bool> AcceptCheckListHeaderAsync(int id, int userid);
Task<bool> UnBlockCheckListHeaderAsync(int id, int userid); Task<bool> BlockCheckListHeaderAsync(int id, int userid);
Task<bool> CloseCheckListHeader(CheckListHeaderCloseDTO closeCheckListHeaderCloseDTO); Task<bool> UnBlockCheckListHeaderAsync(int id, int userid);
Task<byte[]> CreateCheckListHeaderPDFAsync(int checkListHeaderId); Task<bool> CloseCheckListHeader(CheckListHeaderCloseDTO closeCheckListHeaderCloseDTO);
Task<CheckListHeaderDTO> StartNewCheckListAsync(CheckListHeaderNewDTO checkListHeaderNewDTO); Task<byte[]> CreateCheckListHeaderPDFAsync(int checkListHeaderId);
Task<CheckListHeaderDTO> StartNewCheckListAsync(CheckListHeaderNewDTO checkListHeaderNewDTO);
Task<CheckListTemplateHeaderDTO> GetCheckListTemplateHeaderAsync(int Id);
Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateHeaderAsync(); Task<CheckListTemplateHeaderDTO> GetCheckListTemplateHeaderAsync(int Id);
Task<CheckListTemplateHeaderDTO> UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO); Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateHeaderAsync();
Task<bool> DeleteCheckListTemplateHeaderAsync(int id); Task<CheckListTemplateHeaderDTO> UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO);
Task<bool> CloneCheckListTemplateHeaderAsync(int id); Task<bool> DeleteCheckListTemplateHeaderAsync(int id);
Task<CheckListTemplateRowDTO> GetCheckListTemplateRowAsync(int id); Task<bool> CloneCheckListTemplateHeaderAsync(int id);
Task<bool> DeleteCheckListTemplateRowAsync(int id); Task<CheckListTemplateRowDTO> GetCheckListTemplateRowAsync(int id);
Task<CheckListTemplateRowDTO> UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO checkListTemplateRowDTO); Task<bool> DeleteCheckListTemplateRowAsync(int id);
Task<CheckListTemplateRowDTO> UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO checkListTemplateRowDTO);
Task<CheckListRowDTO> GetCheckListRowAsync(int id);
Task<CheckListRowDTO> UpdateCheckListRowAsync(CheckListRowDTO checkListRowDTO); Task<CheckListRowDTO> GetCheckListRowAsync(int id);
Task<CheckListRowDTO> UpdateCheckListRowAsync(CheckListRowDTO checkListRowDTO);
}
} }
}
@@ -1,19 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services.Interfaces namespace WorkFlowCheck.BL.Services.Interfaces
{ {
public interface IMessageService public interface IMessageService
{ {
Task<bool> SendMailAsync(List<string> recipients, string subject, string htmlBody, string? attachmentFilePath = null); Task<bool> SendMailAsync(List<string> recipients, string subject, string htmlBody, string? attachmentFilePath = null);
Task<bool> SendFCMTokenAsync(string token); Task<bool> SendFCMTokenAsync(string token);
Task<string> GetLastFCMTokensAsync(); Task<string> GetLastFCMTokensAsync();
Task<bool> SendFCMMessage(FCMMessageDTO fCMMessageDTO); Task<bool> SendFCMMessage(FCMMessageDTO fCMMessageDTO);
Task<bool> SendFCMMessageToLastToken(FCMMessageDTO fCMMessageDTO); Task<bool> SendFCMMessageToLastToken(FCMMessageDTO fCMMessageDTO);
} }
} }
@@ -1,17 +1,17 @@
using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services.Interfaces namespace WorkFlowCheck.BL.Services.Interfaces
{ {
public interface INumberGeneratorService public interface INumberGeneratorService
{ {
Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null); Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null);
Task<string> GetSampleAsync(int templateId, DateTime? baseDate = null); Task<string> GetSampleAsync(int templateId, DateTime? baseDate = null);
Task<List<NumberGeneratorTemplateDTO>> GetAllNumbergeneratorsAsync(); Task<List<NumberGeneratorTemplateDTO>> GetAllNumbergeneratorsAsync();
} }
} }
@@ -1,39 +1,39 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services.Interfaces namespace WorkFlowCheck.BL.Services.Interfaces
{ {
public interface ISyncService public interface ISyncService
{ {
Task<List<CheckPointDTO>> GetAllCheckPointAsync(); Task<List<CheckPointDTO>> GetAllCheckPointAsync();
Task<CheckPointDTO> GetCheckPointAsync(int id); Task<CheckPointDTO> GetCheckPointAsync(int id);
Task<bool> DeleteCheckPointAsync(int id); Task<bool> DeleteCheckPointAsync(int id);
Task<CheckPointDTO> UpdateCheckPointAsync(CheckPointDTO checkPointDTO); Task<CheckPointDTO> UpdateCheckPointAsync(CheckPointDTO checkPointDTO);
Task<List<CheckPointDTO>> UpdateAllCheckPointAsync(List<CheckPointDTO> checkPointListDTO); Task<List<CheckPointDTO>> UpdateAllCheckPointAsync(List<CheckPointDTO> checkPointListDTO);
Task<List<LocationDTO>> GetAllLocationAsync(); Task<List<LocationDTO>> GetAllLocationAsync();
Task<LocationDTO> GetLocationAsync(int id); Task<LocationDTO> GetLocationAsync(int id);
Task<bool> DeleteLocationAsync(int id); Task<bool> DeleteLocationAsync(int id);
Task<LocationDTO> UpdateLocationAsync(LocationDTO LocationDTO); Task<LocationDTO> UpdateLocationAsync(LocationDTO LocationDTO);
Task<List<EquipmentDTO>> GetAllEquipmentAsync(); Task<List<EquipmentDTO>> GetAllEquipmentAsync();
Task<EquipmentDTO> GetEquipmentAsync(int id); Task<EquipmentDTO> GetEquipmentAsync(int id);
Task<bool> DeleteEquipmentAsync(int id); Task<bool> DeleteEquipmentAsync(int id);
Task<EquipmentDTO> UpdateEquipmentAsync(EquipmentDTO EquipmentDTO); Task<EquipmentDTO> UpdateEquipmentAsync(EquipmentDTO EquipmentDTO);
Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateAsync(int userId); Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateAsync(int userId);
Task<List<CheckListHeaderDTO>> GetAllCheckListAsync(int userId); Task<List<CheckListHeaderDTO>> GetAllCheckListAsync(int userId);
Task<CheckListHeaderDTO> SendCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO); Task<CheckListHeaderDTO> SendCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO);
Task<bool> DeviceMessageSend(DeviceMessageDTO deviceMessageDTO); Task<bool> DeviceMessageSend(DeviceMessageDTO deviceMessageDTO);
Task<List<DeviceMessageDTO>> DeviceMessageReadUnreaded(string deviceId); Task<List<DeviceMessageDTO>> DeviceMessageReadUnreaded(string deviceId);
Task<List<DeviceMessageDTO>> DeviceMessageReadUnreadedRole(int roleId); Task<List<DeviceMessageDTO>> DeviceMessageReadUnreadedRole(int roleId);
} }
} }
@@ -1,13 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.BL.Services.Interfaces namespace WorkFlowCheck.BL.Services.Interfaces
{ {
public interface ISystemService public interface ISystemService
{ {
Task<string> GetDatabaseAndVersionInfoAsync(); Task<string> GetDatabaseAndVersionInfoAsync();
} }
} }
@@ -1,45 +1,45 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services.Interfaces namespace WorkFlowCheck.BL.Services.Interfaces
{ {
public interface IUserService public interface IUserService
{ {
Task<UserDTO> GetUserAsync(int Id); Task<UserDTO> GetUserAsync(int Id);
Task<List<UserDTO>> GetAllUserAsync(); Task<List<UserDTO>> GetAllUserAsync();
Task<bool> DeleteUserAsync(int Id); Task<bool> DeleteUserAsync(int Id);
Task<UserDTO> UpdateUserAsync(UserDTO userDTO); Task<UserDTO> UpdateUserAsync(UserDTO userDTO);
Task<UserDTO> Authenticate(string UserName, string Password); Task<UserDTO> Authenticate(string UserName, string Password);
Task<string> Authenticate2F1(string UserName, string Password); Task<string> Authenticate2F1(string UserName, string Password);
Task<UserDTO> Authenticate2F2(string UserName, string Password, string Code, string token2FA); Task<UserDTO> Authenticate2F2(string UserName, string Password, string Code, string token2FA);
Task<UserDTO> Authenticate2F2ChangePassword(string UserName, string OldPassword, string NewPassword, string Code, string token2FA); Task<UserDTO> Authenticate2F2ChangePassword(string UserName, string OldPassword, string NewPassword, string Code, string token2FA);
Task<UserDTO> AuthenticateNFC(string NFCCode); Task<UserDTO> AuthenticateNFC(string NFCCode);
Task<RoleDTO> GetRoleAsync(int Id); Task<RoleDTO> GetRoleAsync(int Id);
Task<List<RoleDTO>> GetAllRoleAsync(); Task<List<RoleDTO>> GetAllRoleAsync();
Task<bool> DeleteRoleAsync(int Id); Task<bool> DeleteRoleAsync(int Id);
Task<RoleDTO> UpdateRoleAsync(RoleDTO roleDTO); Task<RoleDTO> UpdateRoleAsync(RoleDTO roleDTO);
Task<UserRoleDTO> GetUserRoleAsync(int Id); Task<UserRoleDTO> GetUserRoleAsync(int Id);
Task<List<UserRoleDTO>> GetAllUserRoleAsync(); Task<List<UserRoleDTO>> GetAllUserRoleAsync();
Task<bool> DeleteUserRoleAsync(int Id); Task<bool> DeleteUserRoleAsync(int Id);
Task<UserRoleDTO> UpdateUserRoleAsync(UserRoleDTO userRoleDTO); Task<UserRoleDTO> UpdateUserRoleAsync(UserRoleDTO userRoleDTO);
Task<RoleCheckListTemplateHeaderDTO> GetRoleCheckListTemplateHeaderAsync(int Id); Task<RoleCheckListTemplateHeaderDTO> GetRoleCheckListTemplateHeaderAsync(int Id);
Task<List<RoleCheckListTemplateHeaderDTO>> GetAllRoleCheckListTemplateHeadersAsync(); Task<List<RoleCheckListTemplateHeaderDTO>> GetAllRoleCheckListTemplateHeadersAsync();
Task<bool> DeleteRoleCheckListTemplateHeaderAsync(int Id); Task<bool> DeleteRoleCheckListTemplateHeaderAsync(int Id);
Task<RoleCheckListTemplateHeaderDTO> UpdateRoleCheckListTemplateHeaderAsync(RoleCheckListTemplateHeaderDTO roleCheckListTemplateHeaderDTO); Task<RoleCheckListTemplateHeaderDTO> UpdateRoleCheckListTemplateHeaderAsync(RoleCheckListTemplateHeaderDTO roleCheckListTemplateHeaderDTO);
Task<RoleCheckPointDTO> GetRoleCheckPointAsync(int Id); Task<RoleCheckPointDTO> GetRoleCheckPointAsync(int Id);
Task<List<RoleCheckPointDTO>> GetAllRoleCheckPointsAsync(); Task<List<RoleCheckPointDTO>> GetAllRoleCheckPointsAsync();
Task<bool> DeleteRoleCheckPointAsync(int Id); Task<bool> DeleteRoleCheckPointAsync(int Id);
Task<RoleCheckPointDTO> UpdateRoleCheckPointAsync(RoleCheckPointDTO roleCheckPointDTO); Task<RoleCheckPointDTO> UpdateRoleCheckPointAsync(RoleCheckPointDTO roleCheckPointDTO);
string GenerateJwtToken(UserDTO userDTO); string GenerateJwtToken(UserDTO userDTO);
} }
} }
+216 -184
View File
@@ -1,184 +1,216 @@
using MailKit.Net.Smtp; using MailKit.Net.Smtp;
using MailKit.Security; using MailKit.Security;
using MimeKit; using MimeKit;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using WorkFlowCheck.BL.Models; using WorkFlowCheck.BL.Models;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using Serilog; using Serilog;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.DL.Entities;
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using WorkFlowCheck.DL; using WorkFlowCheck.DL;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace WorkFlowCheck.BL.Services namespace WorkFlowCheck.BL.Services
{ {
public class MessageService : BaseService, IMessageService public class MessageService : BaseService, IMessageService
{ {
private readonly EmailSettings _settings; private readonly EmailSettings _settings;
public MessageService(AppDbContext dbContext, public MessageService(AppDbContext dbContext,
IMapper mapper, IMapper mapper,
IConfiguration configuration) : base(dbContext, mapper) IConfiguration configuration) : base(dbContext, mapper)
{ {
_settings = configuration.GetSection("EmailSettings").Get<EmailSettings>()!; _settings = configuration.GetSection("EmailSettings").Get<EmailSettings>()!;
} }
public async Task<bool> SendMailAsync(List<string> recipients, string subject, string htmlBody, string? attachmentFilePath = null) public async Task<bool> SendMailAsync(List<string> recipients, string subject, string htmlBody, string? attachmentFilePath = null)
{ {
var message = new MimeMessage(); var message = new MimeMessage();
message.From.Add(new MailboxAddress(_settings.SenderName, _settings.Username)); message.From.Add(new MailboxAddress(_settings.SenderName, _settings.Username));
foreach (var recipient in recipients) foreach (var recipient in recipients)
{ {
message.To.Add(MailboxAddress.Parse(recipient)); message.To.Add(MailboxAddress.Parse(recipient));
} }
message.Subject = subject; message.Subject = subject;
var builder = new BodyBuilder var builder = new BodyBuilder
{ {
HtmlBody = htmlBody HtmlBody = htmlBody
}; };
if (!string.IsNullOrEmpty(attachmentFilePath) && File.Exists(attachmentFilePath)) if (!string.IsNullOrEmpty(attachmentFilePath) && File.Exists(attachmentFilePath))
{ {
builder.Attachments.Add(attachmentFilePath); builder.Attachments.Add(attachmentFilePath);
} }
message.Body = builder.ToMessageBody(); message.Body = builder.ToMessageBody();
using var smtp = new SmtpClient(); const int maxRetries = 10;
await smtp.ConnectAsync(_settings.SmtpServer, _settings.SmtpPort, SecureSocketOptions.StartTls); const int delayMs = 2000;
await smtp.AuthenticateAsync(_settings.Username, _settings.Password);
await smtp.SendAsync(message); bool authenticated = false;
await smtp.DisconnectAsync(true); Exception lastException = null;
return true; for (int attempt = 1; attempt <= maxRetries; attempt++)
} {
public async Task<bool> SendFCMTokenAsync(string token) try
{ {
var retVal = true; using var smtp = new SmtpClient();
try
{ await smtp.ConnectAsync(_settings.SmtpServer, _settings.SmtpPort, SecureSocketOptions.StartTls);
if (!string.IsNullOrEmpty(token)) await smtp.AuthenticateAsync(_settings.Username, _settings.Password);
{ await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);
var FCMToken = await _dbContext.FCMTokens.Where(w => w.Token == token).FirstOrDefaultAsync();
if (FCMToken == null) authenticated = true;
{ break; // 🎯 siker
FCMToken = new FCMToken(); }
FCMToken.Token = token; catch (Exception ex)
await _dbContext.FCMTokens.AddAsync(FCMToken); {
} lastException = ex;
else Log.ForContext("TAG", "BusinessFlow").Error(lastException?.Message ?? "E-mail küldése sikertelen!");
{ if (attempt == maxRetries)
FCMToken.LastModAt = DateTime.UtcNow; break;
}
await _dbContext.SaveChangesAsync(); // ⏳ várunk 1 másodpercet és újrapróbáljuk
} await Task.Delay(delayMs);
} }
catch (Exception ex) }
{
retVal = false; if (!authenticated)
Log.ForContext("TAG", "BusinessFlow").Error(ex.Message); {
} // 🔴 IDE ÍRHATSZ MAJD SAJÁT LOGIKÁT
Log.ForContext("TAG", "BusinessFlow").Error(lastException?.Message ?? "E-mail küldése sikertelen!");
return retVal; }
}
public async Task<string> GetLastFCMTokensAsync() return true;
{ }
var retVal = ""; public async Task<bool> SendFCMTokenAsync(string token)
try {
{ var retVal = true;
var FCMToken = await _dbContext.FCMTokens try
.AsNoTracking() {
.OrderByDescending(x => x.LastModAt) if (!string.IsNullOrEmpty(token))
.Take(1) {
.FirstOrDefaultAsync();
if (FCMToken != null && !string.IsNullOrEmpty(FCMToken.Token)) var FCMToken = await _dbContext.FCMTokens.Where(w => w.Token == token).FirstOrDefaultAsync();
{ if (FCMToken == null)
retVal += FCMToken.Token; {
} FCMToken = new FCMToken();
} FCMToken.Token = token;
catch (Exception ex) await _dbContext.FCMTokens.AddAsync(FCMToken);
{ }
retVal = ""; else
Log.ForContext("TAG", "BusinessFlow").Error(ex.Message); {
} FCMToken.LastModAt = DateTime.UtcNow;
return retVal; }
} await _dbContext.SaveChangesAsync();
public async Task<bool> SendFCMMessage(FCMMessageDTO fCMMessageDTO) }
{ }
var retVal = true; catch (Exception ex)
try {
{ retVal = false;
var pathToJsonKey = "com-nuvolar-wfcapp-firebase-adminsdk-fbsvc-37642626e4.json"; Log.ForContext("TAG", "BusinessFlow").Error(ex.Message);
var projectId = "com-nuvolar-wfcapp"; }
var credential = GoogleCredential
.FromFile(pathToJsonKey) return retVal;
.CreateScoped("https://www.googleapis.com/auth/firebase.messaging"); }
var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync(); public async Task<string> GetLastFCMTokensAsync()
{
var client = new HttpClient(); var retVal = "";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); try
{
var FCMToken = await _dbContext.FCMTokens
var message = new .AsNoTracking()
{ .OrderByDescending(x => x.LastModAt)
message = new .Take(1)
{ .FirstOrDefaultAsync();
token = fCMMessageDTO.Token, if (FCMToken != null && !string.IsNullOrEmpty(FCMToken.Token))
notification = new {
{ retVal += FCMToken.Token;
title = fCMMessageDTO.Title, }
body = fCMMessageDTO.Body, }
}, catch (Exception ex)
android = new {
{ retVal = "";
notification = new Log.ForContext("TAG", "BusinessFlow").Error(ex.Message);
{ }
channel_id = "com.nuvolar.wfcapp.general" return retVal;
} }
} public async Task<bool> SendFCMMessage(FCMMessageDTO fCMMessageDTO)
} {
}; var retVal = true;
try
var json = JsonConvert.SerializeObject(message); {
var content = new StringContent(json, Encoding.UTF8, "application/json"); var pathToJsonKey = "com-nuvolar-wfcapp-firebase-adminsdk-fbsvc-37642626e4.json";
var projectId = "com-nuvolar-wfcapp";
var credential = GoogleCredential
var response = await client.PostAsync($"https://fcm.googleapis.com/v1/projects/{projectId}/messages:send", content); .FromFile(pathToJsonKey)
.CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
var result = await response.Content.ReadAsStringAsync(); var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
var client = new HttpClient();
} client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
catch (Exception ex)
{
retVal = false; var message = new
Log.Error(ex.Message); {
} message = new
return retVal; {
} token = fCMMessageDTO.Token,
public async Task<bool> SendFCMMessageToLastToken(FCMMessageDTO fCMMessageDTO) notification = new
{ {
var retVal = true; title = fCMMessageDTO.Title,
try body = fCMMessageDTO.Body,
{ },
fCMMessageDTO.Token = await GetLastFCMTokensAsync(); android = new
{
retVal = await SendFCMMessage(fCMMessageDTO); notification = new
} {
catch (Exception ex) channel_id = "com.nuvolar.wfcapp.general"
{ }
Log.Error(ex.Message); }
} }
return retVal; };
}
} var json = JsonConvert.SerializeObject(message);
var content = new StringContent(json, Encoding.UTF8, "application/json");
}
var response = await client.PostAsync($"https://fcm.googleapis.com/v1/projects/{projectId}/messages:send", content);
var result = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
retVal = false;
Log.Error(ex.Message);
}
return retVal;
}
public async Task<bool> SendFCMMessageToLastToken(FCMMessageDTO fCMMessageDTO)
{
var retVal = true;
try
{
fCMMessageDTO.Token = await GetLastFCMTokensAsync();
retVal = await SendFCMMessage(fCMMessageDTO);
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
}
}
@@ -1,164 +1,164 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage;
using Serilog; using Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.DL; using WorkFlowCheck.DL;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.DL.Entities;
namespace WorkFlowCheck.BL.Services namespace WorkFlowCheck.BL.Services
{ {
public class NumberGeneratorService : INumberGeneratorService public class NumberGeneratorService : INumberGeneratorService
{ {
private readonly AppDbContext _dbContext; private readonly AppDbContext _dbContext;
private static readonly Dictionary<int, SemaphoreSlim> _templateLocks = new(); private static readonly Dictionary<int, SemaphoreSlim> _templateLocks = new();
public NumberGeneratorService(AppDbContext dbContext) public NumberGeneratorService(AppDbContext dbContext)
{ {
_dbContext = dbContext; _dbContext = dbContext;
} }
public async Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null) public async Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null)
{ {
var semaphore = GetOrCreateSemaphore(templateId); var semaphore = GetOrCreateSemaphore(templateId);
await semaphore.WaitAsync(); await semaphore.WaitAsync();
try try
{ {
var template = await _dbContext.Set<NumberGeneratorTemplate>() var template = await _dbContext.Set<NumberGeneratorTemplate>()
.FirstOrDefaultAsync(t => t.Id == templateId); .FirstOrDefaultAsync(t => t.Id == templateId);
if (template == null) if (template == null)
throw new InvalidOperationException($"Template with ID {templateId} not found."); throw new InvalidOperationException($"Template with ID {templateId} not found.");
var now = baseDate ?? DateTime.Now; var now = baseDate ?? DateTime.Now;
var (year, month) = GetKeyDateParts(template, now); var (year, month) = GetKeyDateParts(template, now);
var templateDate = await _dbContext.Set<NumberGeneratorTemplateDate>() var templateDate = await _dbContext.Set<NumberGeneratorTemplateDate>()
.FirstOrDefaultAsync(td => td.NumberGeneratorTemplateId == templateId && td.Year == year && td.Month == month); .FirstOrDefaultAsync(td => td.NumberGeneratorTemplateId == templateId && td.Year == year && td.Month == month);
if (templateDate == null) if (templateDate == null)
{ {
templateDate = new NumberGeneratorTemplateDate templateDate = new NumberGeneratorTemplateDate
{ {
NumberGeneratorTemplateId = template.Id, NumberGeneratorTemplateId = template.Id,
Year = year, Year = year,
Month = month, Month = month,
CurrentNumber = 0 CurrentNumber = 0
}; };
_dbContext.Add(templateDate); _dbContext.Add(templateDate);
} }
templateDate.CurrentNumber++; templateDate.CurrentNumber++;
var formatted = templateDate.CurrentNumber.ToString(template.DigitFormat); var formatted = templateDate.CurrentNumber.ToString(template.DigitFormat);
var dynamicSuffix = BuildDynamicSuffix(template, now); var dynamicSuffix = BuildDynamicSuffix(template, now);
var result = BuildFormattedNumber(template, formatted, dynamicSuffix); var result = BuildFormattedNumber(template, formatted, dynamicSuffix);
templateDate.LastGeneratedNumber = result; templateDate.LastGeneratedNumber = result;
await _dbContext.SaveChangesAsync(); await _dbContext.SaveChangesAsync();
return result; return result;
} }
catch catch
{ {
throw; throw;
} }
finally finally
{ {
semaphore.Release(); semaphore.Release();
} }
} }
public async Task<string> GetSampleAsync(int templateId, DateTime? baseDate = null) public async Task<string> GetSampleAsync(int templateId, DateTime? baseDate = null)
{ {
var template = await _dbContext.Set<NumberGeneratorTemplate>() var template = await _dbContext.Set<NumberGeneratorTemplate>()
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(t => t.Id == templateId); .FirstOrDefaultAsync(t => t.Id == templateId);
if (template == null) if (template == null)
throw new InvalidOperationException($"Template with ID {templateId} not found."); throw new InvalidOperationException($"Template with ID {templateId} not found.");
var now = baseDate ?? DateTime.Now; var now = baseDate ?? DateTime.Now;
var formatted = 1.ToString(template.DigitFormat); var formatted = 1.ToString(template.DigitFormat);
var dynamicSuffix = BuildDynamicSuffix(template, now); var dynamicSuffix = BuildDynamicSuffix(template, now);
return BuildFormattedNumber(template, formatted, dynamicSuffix); return BuildFormattedNumber(template, formatted, dynamicSuffix);
} }
public async Task<List<NumberGeneratorTemplateDTO>> GetAllNumbergeneratorsAsync() public async Task<List<NumberGeneratorTemplateDTO>> GetAllNumbergeneratorsAsync()
{ {
var retVal = new List<NumberGeneratorTemplateDTO>(); var retVal = new List<NumberGeneratorTemplateDTO>();
try try
{ {
var numbergenerators = await _dbContext.NumberGeneratorTemplates.ToListAsync(); var numbergenerators = await _dbContext.NumberGeneratorTemplates.ToListAsync();
foreach (var numbergenerator in numbergenerators) foreach (var numbergenerator in numbergenerators)
{ {
var numbergeneratortemplateDTO = new NumberGeneratorTemplateDTO(); var numbergeneratortemplateDTO = new NumberGeneratorTemplateDTO();
numbergeneratortemplateDTO.Id = numbergenerator.Id; numbergeneratortemplateDTO.Id = numbergenerator.Id;
numbergeneratortemplateDTO.ShortName = numbergenerator.ShortName; numbergeneratortemplateDTO.ShortName = numbergenerator.ShortName;
numbergeneratortemplateDTO.Sample = await this.GetSampleAsync(numbergenerator.Id, DateTime.Now); numbergeneratortemplateDTO.Sample = await this.GetSampleAsync(numbergenerator.Id, DateTime.Now);
retVal.Add(numbergeneratortemplateDTO); retVal.Add(numbergeneratortemplateDTO);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
private SemaphoreSlim GetOrCreateSemaphore(int templateId) private SemaphoreSlim GetOrCreateSemaphore(int templateId)
{ {
lock (_templateLocks) lock (_templateLocks)
{ {
if (!_templateLocks.ContainsKey(templateId)) if (!_templateLocks.ContainsKey(templateId))
_templateLocks[templateId] = new SemaphoreSlim(1, 1); _templateLocks[templateId] = new SemaphoreSlim(1, 1);
return _templateLocks[templateId]; return _templateLocks[templateId];
} }
} }
private static (int year, int? month) GetKeyDateParts(NumberGeneratorTemplate template, DateTime date) private static (int year, int? month) GetKeyDateParts(NumberGeneratorTemplate template, DateTime date)
{ {
int year = date.Year; int year = date.Year;
int? month = template.GenerateType == GenerateType.YearAndMonth ? date.Month : null; int? month = template.GenerateType == GenerateType.YearAndMonth ? date.Month : null;
return (year, month); return (year, month);
} }
private static string BuildDynamicSuffix(NumberGeneratorTemplate template, DateTime date) private static string BuildDynamicSuffix(NumberGeneratorTemplate template, DateTime date)
{ {
return template.GenerateType switch return template.GenerateType switch
{ {
GenerateType.OnlyYear => date.Year.ToString(), GenerateType.OnlyYear => date.Year.ToString(),
GenerateType.YearAndMonth => $"{date.Year}/{date.Month:D2}", GenerateType.YearAndMonth => $"{date.Year}/{date.Month:D2}",
_ => template.Suffix _ => template.Suffix
}; };
} }
private static string BuildFormattedNumber(NumberGeneratorTemplate template, string formattedNumber, string dynamicSuffix) private static string BuildFormattedNumber(NumberGeneratorTemplate template, string formattedNumber, string dynamicSuffix)
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
if (!string.IsNullOrEmpty(template.Prefix)) if (!string.IsNullOrEmpty(template.Prefix))
sb.Append(template.Prefix); sb.Append(template.Prefix);
if (!string.IsNullOrEmpty(template.PrefixSeparator) && !string.IsNullOrEmpty(template.Prefix)) if (!string.IsNullOrEmpty(template.PrefixSeparator) && !string.IsNullOrEmpty(template.Prefix))
sb.Append(template.PrefixSeparator); sb.Append(template.PrefixSeparator);
sb.Append(formattedNumber); sb.Append(formattedNumber);
if (!string.IsNullOrEmpty(dynamicSuffix)) if (!string.IsNullOrEmpty(dynamicSuffix))
{ {
if (!string.IsNullOrEmpty(template.SuffixSeparator)) if (!string.IsNullOrEmpty(template.SuffixSeparator))
sb.Append(template.SuffixSeparator); sb.Append(template.SuffixSeparator);
sb.Append(dynamicSuffix); sb.Append(dynamicSuffix);
} }
return sb.ToString(); return sb.ToString();
} }
} }
} }
File diff suppressed because it is too large Load Diff
+49 -49
View File
@@ -1,49 +1,49 @@
using AutoMapper; using AutoMapper;
using DocumentFormat.OpenXml.InkML; using DocumentFormat.OpenXml.InkML;
using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.BL.Services.Interfaces; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.DL; using WorkFlowCheck.DL;
namespace WorkFlowCheck.BL.Services namespace WorkFlowCheck.BL.Services
{ {
public class SystemService : ISystemService public class SystemService : ISystemService
{ {
public readonly AppDbContext _dbContext; public readonly AppDbContext _dbContext;
public readonly IMapper _mapper; public readonly IMapper _mapper;
public readonly IConfiguration _config; public readonly IConfiguration _config;
public SystemService(AppDbContext dbContext, public SystemService(AppDbContext dbContext,
IMapper mapper, IMapper mapper,
IConfiguration configuration) IConfiguration configuration)
{ {
_config = configuration; _config = configuration;
_dbContext = dbContext; _dbContext = dbContext;
_mapper = mapper; _mapper = mapper;
} }
public async Task<string> GetDatabaseAndVersionInfoAsync() public async Task<string> GetDatabaseAndVersionInfoAsync()
{ {
var retVal = ""; var retVal = "";
var connection = _dbContext.Database.GetDbConnection(); var connection = _dbContext.Database.GetDbConnection();
var typeName = connection.GetType().Name; var typeName = connection.GetType().Name;
//if (typeName.Contains("Npgsql")) //if (typeName.Contains("Npgsql"))
//{ //{
// var builder = new NpgsqlConnectionStringBuilder(connection.ConnectionString); // var builder = new NpgsqlConnectionStringBuilder(connection.ConnectionString);
// retVal= builder.Database; // retVal= builder.Database;
//} //}
if (typeName.Contains("SqlConnection")) if (typeName.Contains("SqlConnection"))
{ {
var builder = new SqlConnectionStringBuilder(connection.ConnectionString); var builder = new SqlConnectionStringBuilder(connection.ConnectionString);
retVal= builder.InitialCatalog; retVal= builder.InitialCatalog;
} }
return retVal; return retVal;
} }
} }
} }
File diff suppressed because it is too large Load Diff
+72 -72
View File
@@ -1,72 +1,72 @@
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.BL.Static namespace WorkFlowCheck.BL.Static
{ {
public static class CodeGenerator2F public static class CodeGenerator2F
{ {
private static readonly Random _random = new Random(); private static readonly Random _random = new Random();
private const string SecretKey = "874512WcfApplicationNuvolar.hu!%mBX210jUUKL"; private const string SecretKey = "874512WcfApplicationNuvolar.hu!%mBX210jUUKL";
private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes(SecretKey); private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes(SecretKey);
public static string GenerateSixDigitCode() public static string GenerateSixDigitCode()
{ {
return _random.Next(100000, 1000000).ToString(); // 100000 - 999999 return _random.Next(100000, 1000000).ToString(); // 100000 - 999999
} }
public static string GenerateToken2F(string value1, string value2, string value3) public static string GenerateToken2F(string value1, string value2, string value3)
{ {
var tokenHandler = new JwtSecurityTokenHandler(); var tokenHandler = new JwtSecurityTokenHandler();
var claims = new[] var claims = new[]
{ {
new Claim("val1", value1), new Claim("val1", value1),
new Claim("val2", value2), new Claim("val2", value2),
new Claim("val3", value3) new Claim("val3", value3)
}; };
var descriptor = new SecurityTokenDescriptor var descriptor = new SecurityTokenDescriptor
{ {
Subject = new ClaimsIdentity(claims), Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddSeconds(60 * 60 * 2), Expires = DateTime.UtcNow.AddSeconds(60 * 60 * 2),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(KeyBytes), SecurityAlgorithms.HmacSha256Signature) SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(KeyBytes), SecurityAlgorithms.HmacSha256Signature)
}; };
var token = tokenHandler.CreateToken(descriptor); var token = tokenHandler.CreateToken(descriptor);
return tokenHandler.WriteToken(token); return tokenHandler.WriteToken(token);
} }
public static bool ValidateToken2F(string token, string expected1, string expected2, string expected3) public static bool ValidateToken2F(string token, string expected1, string expected2, string expected3)
{ {
var tokenHandler = new JwtSecurityTokenHandler(); var tokenHandler = new JwtSecurityTokenHandler();
try try
{ {
var parameters = new TokenValidationParameters var parameters = new TokenValidationParameters
{ {
ValidateIssuer = false, ValidateIssuer = false,
ValidateAudience = false, ValidateAudience = false,
ValidateIssuerSigningKey = true, ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(KeyBytes), IssuerSigningKey = new SymmetricSecurityKey(KeyBytes),
ClockSkew = TimeSpan.Zero // nincs türelmi idő ClockSkew = TimeSpan.Zero // nincs türelmi idő
}; };
var principal = tokenHandler.ValidateToken(token, parameters, out var validatedToken); var principal = tokenHandler.ValidateToken(token, parameters, out var validatedToken);
var val1 = principal.FindFirst("val1")?.Value; var val1 = principal.FindFirst("val1")?.Value;
var val2 = principal.FindFirst("val2")?.Value; var val2 = principal.FindFirst("val2")?.Value;
var val3 = principal.FindFirst("val3")?.Value; var val3 = principal.FindFirst("val3")?.Value;
return val1 == expected1 && val2 == expected2 && val3 == expected3; return val1 == expected1 && val2 == expected2 && val3 == expected3;
} }
catch catch
{ {
return false; return false;
} }
} }
} }
} }
+35 -35
View File
@@ -1,35 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Remove="HtmlTemplates\Token2FBody.html" /> <None Remove="HtmlTemplates\Token2FBody.html" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="HtmlTemplates\AcceptCheckListHeaderBody.html" /> <EmbeddedResource Include="HtmlTemplates\AcceptCheckListHeaderBody.html" />
<EmbeddedResource Include="HtmlTemplates\Token2FBody.html" /> <EmbeddedResource Include="HtmlTemplates\Token2FBody.html" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" /> <PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" /> <PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Google.Apis.Auth" Version="1.69.0" /> <PackageReference Include="Google.Apis.Auth" Version="1.69.0" />
<PackageReference Include="MailKit" Version="4.11.0" /> <PackageReference Include="MailKit" Version="4.11.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" /> <PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" /> <PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" /> <PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\WorkFlowCheck.Common\WorkFlowCheck.Common.csproj" /> <ProjectReference Include="..\WorkFlowCheck.Common\WorkFlowCheck.Common.csproj" />
<ProjectReference Include="..\WorkFlowCheck.DL\WorkFlowCheck.DL.csproj" /> <ProjectReference Include="..\WorkFlowCheck.DL\WorkFlowCheck.DL.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
File diff suppressed because it is too large Load Diff
@@ -1,15 +1,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.Constants namespace WorkFlowCheck.Common.Constants
{ {
public static class MemoryCacheNames public static class MemoryCacheNames
{ {
public const string UsersNamePrefix = "Users_"; public const string UsersNamePrefix = "Users_";
public const string TranslationsNamePrefix = "Translations_"; public const string TranslationsNamePrefix = "Translations_";
public const string Languages = "Languages"; public const string Languages = "Languages";
} }
} }
+14 -14
View File
@@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class ApiRequestDTO<T> public class ApiRequestDTO<T>
{ {
public UserDTO UserDTO { get; set; } public UserDTO UserDTO { get; set; }
public T Data { get; set; } public T Data { get; set; }
} }
} }
+45 -43
View File
@@ -1,43 +1,45 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class ApiResponseBaseDTO public class ApiResponseBaseDTO
{ {
public ApiResponseBaseDTO() public ApiResponseBaseDTO()
{ {
Errors = new List<string>(); Errors = new List<string>();
} }
public bool IsSuccess { get; set; } public bool IsSuccess { get; set; }
public List<string> Errors { get; set; } public List<string> Errors { get; set; }
public bool HandleError { get; set; } public bool HandleError { get; set; }
public string Error public string Error
{ {
get get
{ {
if (Errors == null || Errors.Count() == 0) return string.Empty; if (Errors == null || Errors.Count() == 0) return string.Empty;
return string.Join(';', Errors); return string.Join(';', Errors);
} }
} }
} }
public class ApiResponseDTO : ApiResponseBaseDTO public class ApiResponseDTO : ApiResponseBaseDTO
{ {
public object Data { get; set; } public object Data { get; set; }
} }
public interface IApiResponseDTO<out T> public interface IApiResponseDTO<out T>
{ {
} }
public class ApiResponseDTO<T> : ApiResponseBaseDTO, IApiResponseDTO<T> public class ApiResponseDTO<T> : ApiResponseBaseDTO, IApiResponseDTO<T>
{ {
public T Data { get; set; } public T Data { get; set; }
} }
public class ApiResponseListDTO<T> : ApiResponseBaseDTO
{ public class ApiResponseListDTO<T> : ApiResponseBaseDTO
public T[] Data { get; set; } {
public int Total { get; set; } public T Data { get; set; }
} public int Total { get; set; }
} public int Filtered { get; set; }
}
}
@@ -1,15 +1,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListHeaderCloseDTO public class CheckListHeaderCloseDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public string CloseReason { get; set; } = null!; public string CloseReason { get; set; } = null!;
public int UserId { get; set; } public int UserId { get; set; }
} }
} }
@@ -1,59 +1,59 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.Common.Enums; using WorkFlowCheck.Common.Enums;
using WorkFlowCheck.Common.Helper; using WorkFlowCheck.Common.Helper;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListHeaderDTO public class CheckListHeaderDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public int CheckListTemplateHeaderId { get; set; } public int CheckListTemplateHeaderId { get; set; }
public CheckListTemplateHeaderDTO? CheckListTemplateHeaderDTO { get; set; } public CheckListTemplateHeaderDTO? CheckListTemplateHeaderDTO { get; set; }
[DisplayName("Státusz")] [DisplayName("Státusz")]
public CheckStatus CheckStatus { get; set; } public CheckStatus CheckStatus { get; set; }
public string StatusName => DisplayNameHelper.GetEnumDisplayName(CheckStatus); public string StatusName => DisplayNameHelper.GetEnumDisplayName(CheckStatus);
[DisplayName("Dátum")] [DisplayName("Dátum")]
public DateTime DateExecution { get; set; } public DateTime DateExecution { get; set; }
[DisplayName("Ellenőrző")] [DisplayName("Ellenőrző")]
public int UserId { get; set; } public int UserId { get; set; }
public UserDTO? UserDTO { get; set; } public UserDTO? UserDTO { get; set; }
[DisplayName("Jóváhagyó")] [DisplayName("Jóváhagyó")]
public int? AcceptUserId { get; set; } public int? AcceptUserId { get; set; }
public UserDTO? AcceptUserDTO { get; set; } public UserDTO? AcceptUserDTO { get; set; }
[DisplayName("Megnevezés")] [DisplayName("Megnevezés")]
public string ShortName { get; set; } = null!; public string ShortName { get; set; } = null!;
[DisplayName("Leírás")] [DisplayName("Leírás")]
public string Description { get; set; } = null!; public string Description { get; set; } = null!;
[DisplayName("Sorszám")] [DisplayName("Sorszám")]
public string DocumentNumber { get; set; } = null!; public string DocumentNumber { get; set; } = null!;
[DisplayName("Azonosító")] [DisplayName("Azonosító")]
public Guid GuidNumber { get; set; } public Guid GuidNumber { get; set; }
[DisplayName("Stornózva")] [DisplayName("Stornózva")]
public bool IsStorno { get; set; } public bool IsStorno { get; set; }
[DisplayName("Szerkeszthető")] [DisplayName("Szerkeszthető")]
public bool IsEditable { get; set; } public bool IsEditable { get; set; }
public ICollection<CheckListRowDTO>? CheckListRowDTO { get; set; } = new List<CheckListRowDTO>(); public ICollection<CheckListRowDTO>? CheckListRowDTO { get; set; } = new List<CheckListRowDTO>();
public CheckListHeaderDTO() public CheckListHeaderDTO()
{ {
CheckListRowDTO = new List<CheckListRowDTO>(); CheckListRowDTO = new List<CheckListRowDTO>();
} }
} }
} }
@@ -1,28 +1,28 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListHeaderInfoDTO public class CheckListHeaderInfoDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Összes ellenőrzési szám")] [DisplayName("Összes ellenőrzési szám")]
public int TotalRowCount { get; set; } public int TotalRowCount { get; set; }
[DisplayName("Még ellenőrizendő száma")] [DisplayName("Még ellenőrizendő száma")]
public int EmptyAnswerCount { get; set; } public int EmptyAnswerCount { get; set; }
[DisplayName("Készültség %")] [DisplayName("Készültség %")]
public string ReadyPercent { get; set; } public string ReadyPercent { get; set; }
[DisplayName("Ellenőrzési pontok száma")] [DisplayName("Ellenőrzési pontok száma")]
public int CheckPointCount { get; set; } public int CheckPointCount { get; set; }
} }
} }
@@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListHeaderNewDTO public class CheckListHeaderNewDTO
{ {
public int CheckListTemplateHeaderId { get; set; } public int CheckListTemplateHeaderId { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
} }
} }
+29 -29
View File
@@ -1,29 +1,29 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListRowDTO public class CheckListRowDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public int CheckListHeaderId { get; set; } public int CheckListHeaderId { get; set; }
public int CheckListTemplateRowId { get; set; } public int CheckListTemplateRowId { get; set; }
public CheckListTemplateRowDTO? CheckListTemplateRowDTO { get; set; } public CheckListTemplateRowDTO? CheckListTemplateRowDTO { get; set; }
public string GroupName => $"AnswerGroup_{CheckListTemplateRowDTO?.Id ?? 0}"; public string GroupName => $"AnswerGroup_{CheckListTemplateRowDTO?.Id ?? 0}";
[DisplayName("Eredmény")] [DisplayName("Eredmény")]
public string Answer { get; set; } = null!; public string Answer { get; set; } = null!;
public bool? AnswerYes { get; set; } = null!; public bool? AnswerYes { get; set; } = null!;
public bool? AnswerNo { get; set; } = null!; public bool? AnswerNo { get; set; } = null!;
[DisplayName("Kép")] [DisplayName("Kép")]
public byte[]? Photo { get; set; } = null!; public byte[]? Photo { get; set; } = null!;
public Guid GuidNumber { get; set; } public Guid GuidNumber { get; set; }
} }
} }
@@ -1,22 +1,22 @@
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListTemplateHeaderDTO public class CheckListTemplateHeaderDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Megnevezés")] [DisplayName("Megnevezés")]
public string ShortName { get; set; } = null!; public string ShortName { get; set; } = null!;
[DisplayName("Leírás")] [DisplayName("Leírás")]
public string Description { get; set; } = null!; public string Description { get; set; } = null!;
[DisplayName("Sorszám (munkalap)")] [DisplayName("Sorszám (munkalap)")]
public int? NumberGenerator1Id { get; set; } public int? NumberGenerator1Id { get; set; }
[DisplayName("Sorszám (dokumentum)")] [DisplayName("Sorszám (dokumentum)")]
public int? NumberGenerator2Id { get; set; } public int? NumberGenerator2Id { get; set; }
public NumberGeneratorTemplateDTO? NumberGenerator1 { get; set; } public NumberGeneratorTemplateDTO? NumberGenerator1 { get; set; }
public NumberGeneratorTemplateDTO? NumberGenerator2 { get; set; } public NumberGeneratorTemplateDTO? NumberGenerator2 { get; set; }
public ICollection<CheckListTemplateRowDTO>? CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>(); public ICollection<CheckListTemplateRowDTO>? CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>();
} }
} }
@@ -1,43 +1,43 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckListTemplateRowDTO public class CheckListTemplateRowDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A sorrend megadása kötelező.")] [Required(ErrorMessage = "A sorrend megadása kötelező.")]
[DisplayName("Sorrend")] [DisplayName("Sorrend")]
public int RowIndex { get; set; } public int RowIndex { get; set; }
public int CheckListTemplateHeaderId { get; set; } public int CheckListTemplateHeaderId { get; set; }
[DisplayName("Berendezés")] [DisplayName("Berendezés")]
public int EquipmentId { get; set; } public int EquipmentId { get; set; }
public EquipmentDTO? EquipmentDTO { get; set; } = null!; public EquipmentDTO? EquipmentDTO { get; set; } = null!;
public int CheckPointId { get; set; } public int CheckPointId { get; set; }
public CheckPointDTO? CheckPointDTO { get; set; } = null!; public CheckPointDTO? CheckPointDTO { get; set; } = null!;
[DisplayName("Tevékenység leírása")] [DisplayName("Tevékenység leírása")]
public string OperationDescription { get; set; } = null!; public string OperationDescription { get; set; } = null!;
/// <summary> /// <summary>
/// ///
/// I-N (Igen, nem) /// I-N (Igen, nem)
/// P (Fénykép készítése) /// P (Fénykép készítése)
/// PN (Fénykép nem kötelező készítése) /// PN (Fénykép nem kötelező készítése)
/// SI-N (Sárga igen,fehér nem) /// SI-N (Sárga igen,fehér nem)
/// I-SN (Fehér igen, sárga nem) /// I-SN (Fehér igen, sárga nem)
/// PI-N (Piros igen,fehér nem) /// PI-N (Piros igen,fehér nem)
/// I-PN (Fehér igen, piros nem) /// I-PN (Fehér igen, piros nem)
/// V (Érték megadása) /// V (Érték megadása)
/// ///
/// </summary> /// </summary>
[DisplayName("Válasz tipus")] [DisplayName("Válasz tipus")]
public string AnswerType { get; set; } = null!; public string AnswerType { get; set; } = null!;
} }
} }
+31 -31
View File
@@ -1,31 +1,31 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel; using System.ComponentModel;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class CheckPointDTO public class CheckPointDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A megnevezés megadása kötelező.")] [Required(ErrorMessage = "A megnevezés megadása kötelező.")]
[DisplayName("Megnevezés")] [DisplayName("Megnevezés")]
public string ShortName { get; set; } public string ShortName { get; set; }
[Required(ErrorMessage = "A kód megadása kötelező.")] [Required(ErrorMessage = "A kód megadása kötelező.")]
[DisplayName("Kód")] [DisplayName("Kód")]
public string Code { get; set; } public string Code { get; set; }
[DisplayName("Használatban")] [DisplayName("Használatban")]
public bool IsEnabled { get; set; } public bool IsEnabled { get; set; }
[DisplayName("Szabály")] [DisplayName("Szabály")]
public int? RoleId { get; set; } public int? RoleId { get; set; }
[DisplayName("Szabály neve")] [DisplayName("Szabály neve")]
public string? RoleName { get; set; } public string? RoleName { get; set; }
public List<CheckListTemplateRowDTO>? CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>(); public List<CheckListTemplateRowDTO>? CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>();
} }
} }
@@ -0,0 +1,63 @@
using WorkFlowCheck.Common.Enums;
namespace WorkFlowCheck.Common.DTO
{
public class DashboardDTO
{
public DateTime GeneratedAt { get; set; }
public int TotalCheckLists { get; set; }
public int CheckListsThisMonth { get; set; }
public decimal MonthlyChangePercent { get; set; }
public int OpenAndInProgressCount { get; set; }
public int AwaitingApprovalCount { get; set; }
public int BlockedCount { get; set; }
public int ApprovedThisMonthCount { get; set; }
public decimal ApprovalRate { get; set; }
public int ActiveUserCount { get; set; }
public int TemplateCount { get; set; }
public List<DashboardMonthlyItemDTO> MonthlyItems { get; set; } = new();
public List<DashboardStatusItemDTO> StatusItems { get; set; } = new();
public List<DashboardUserItemDTO> TopUsers { get; set; } = new();
public List<DashboardAttentionItemDTO> AttentionItems { get; set; } = new();
public List<DashboardRecentCheckListDTO> RecentCheckLists { get; set; } = new();
}
public class DashboardMonthlyItemDTO
{
public string Month { get; set; } = string.Empty;
public int Total { get; set; }
public int Approved { get; set; }
}
public class DashboardStatusItemDTO
{
public CheckStatus Status { get; set; }
public string Name { get; set; } = string.Empty;
public int Count { get; set; }
public string Color { get; set; } = string.Empty;
}
public class DashboardUserItemDTO
{
public string Name { get; set; } = string.Empty;
public int Count { get; set; }
}
public class DashboardAttentionItemDTO
{
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public bool IsCritical { get; set; }
}
public class DashboardRecentCheckListDTO
{
public int Id { get; set; }
public string DocumentNumber { get; set; } = string.Empty;
public string ShortName { get; set; } = string.Empty;
public string Responsible { get; set; } = string.Empty;
public DateTime ModifiedAt { get; set; }
public CheckStatus Status { get; set; }
public string StatusName { get; set; } = string.Empty;
}
}
@@ -1,22 +1,22 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class DeviceMessageDTO public class DeviceMessageDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public DateTime? SendDate { get; set; } public DateTime? SendDate { get; set; }
public DateTime? ReceiveDate { get; set; } public DateTime? ReceiveDate { get; set; }
public string DeviceIdFrom { get; set; } = null!; public string DeviceIdFrom { get; set; } = null!;
public string DeviceIdTo { get; set; } = null!; public string DeviceIdTo { get; set; } = null!;
public string Message { get; set; } = null!; public string Message { get; set; } = null!;
public string ExtraDataJSON { get; set; } = null!; public string ExtraDataJSON { get; set; } = null!;
public bool IsReaded { get; set; } public bool IsReaded { get; set; }
public int? RoleId { get; set; } public int? RoleId { get; set; }
public RoleDTO? RoleDTO { get; set; } public RoleDTO? RoleDTO { get; set; }
} }
} }
+23 -23
View File
@@ -1,23 +1,23 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class EquipmentDTO public class EquipmentDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A megnevezést megadása kötelező.")] [Required(ErrorMessage = "A megnevezést megadása kötelező.")]
[DisplayName("Megnevezés")] [DisplayName("Megnevezés")]
public string ShortName { get; set; } = null!; public string ShortName { get; set; } = null!;
[Required(ErrorMessage = "Az azonosító megadása kötelező.")] [Required(ErrorMessage = "Az azonosító megadása kötelező.")]
[DisplayName("Azonosító")] [DisplayName("Azonosító")]
public string EquipmentNumber { get; set; } = null!; public string EquipmentNumber { get; set; } = null!;
} }
} }
+17 -17
View File
@@ -1,17 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class FCMMessageDTO public class FCMMessageDTO
{ {
public string? Token { get; set; } public string? Token { get; set; }
public string? Body { get; set; } public string? Body { get; set; }
public string? Title { get; set; } public string? Title { get; set; }
public int? UserId { get; set; } public int? UserId { get; set; }
} }
} }
+16 -16
View File
@@ -1,16 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class ImageFileDTO public class ImageFileDTO
{ {
public string Id { get; set; } public string Id { get; set; }
public string FileName { get; set; } public string FileName { get; set; }
public string FileSize { get; set; } public string FileSize { get; set; }
public string CreateDate { get; set; } public string CreateDate { get; set; }
} }
} }
+19 -19
View File
@@ -1,19 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class LocationDTO public class LocationDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A megnevezést megadása kötelező.")] [Required(ErrorMessage = "A megnevezést megadása kötelező.")]
[DisplayName("Megnevezés")] [DisplayName("Megnevezés")]
public string FullName { get; set; } = null!; public string FullName { get; set; } = null!;
} }
} }
+16 -16
View File
@@ -1,16 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class LogFileDTO public class LogFileDTO
{ {
public string Id { get; set; } public string Id { get; set; }
public string FileName { get; set; } public string FileName { get; set; }
public string FileSize { get; set; } public string FileSize { get; set; }
public string CreateDate { get; set; } public string CreateDate { get; set; }
} }
} }
+20 -20
View File
@@ -1,20 +1,20 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class MobileUserDTO public class MobileUserDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public string? UserName { get; set; } public string? UserName { get; set; }
public string? FirstName { get; set; } public string? FirstName { get; set; }
public string? LastName { get; set; } public string? LastName { get; set; }
public string? FullName => $"{LastName} {FirstName}"; public string? FullName => $"{LastName} {FirstName}";
public string? Email { get; set; } public string? Email { get; set; }
public bool NFCActive { get; set; } public bool NFCActive { get; set; }
public string NFCCode { get; set; } = null!; public string NFCCode { get; set; } = null!;
} }
} }
@@ -1,15 +1,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class NumberGeneratorTemplateDTO public class NumberGeneratorTemplateDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public string ShortName { get; set; } public string ShortName { get; set; }
public string Sample { get; set; } public string Sample { get; set; }
} }
} }
+16 -16
View File
@@ -1,16 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class PDFFileDTO public class PDFFileDTO
{ {
public string Id { get; set; } public string Id { get; set; }
public string FileName { get; set; } public string FileName { get; set; }
public string FileSize { get; set; } public string FileSize { get; set; }
public string CreateDate { get; set; } public string CreateDate { get; set; }
} }
} }
@@ -1,30 +1,30 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class RoleCheckListTemplateHeaderDTO public class RoleCheckListTemplateHeaderDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A szabály megnevezésének megadása kötelező.")] [Required(ErrorMessage = "A szabály megnevezésének megadása kötelező.")]
[DisplayName("Szabály")] [DisplayName("Szabály")]
public int RoleId { get; set; } public int RoleId { get; set; }
public RoleDTO? RoleDTO { get; set; } = null!; public RoleDTO? RoleDTO { get; set; } = null!;
[Required(ErrorMessage = "Az ellenőrzési sablon megadása kötelező.")] [Required(ErrorMessage = "Az ellenőrzési sablon megadása kötelező.")]
[DisplayName("Ellenőrzési sablon")] [DisplayName("Ellenőrzési sablon")]
public int CheckListTemplateHeaderId { get; set; } public int CheckListTemplateHeaderId { get; set; }
public CheckListTemplateHeaderDTO? CheckListTemplateHeaderDTO { get; set; } = null!; public CheckListTemplateHeaderDTO? CheckListTemplateHeaderDTO { get; set; } = null!;
[DisplayName("Engedélyezve?")] [DisplayName("Engedélyezve?")]
public bool Enabled { get; set; } = false; public bool Enabled { get; set; } = false;
} }
} }
@@ -1,29 +1,29 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class RoleCheckPointDTO public class RoleCheckPointDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A szabály megadása kötelező.")] [Required(ErrorMessage = "A szabály megadása kötelező.")]
[DisplayName("Szabály")] [DisplayName("Szabály")]
public int RoleId { get; set; } public int RoleId { get; set; }
public RoleDTO? RoleDTO { get; set; } = null!; public RoleDTO? RoleDTO { get; set; } = null!;
[Required(ErrorMessage = "Az ellenőrzési pont megadása kötelező.")] [Required(ErrorMessage = "Az ellenőrzési pont megadása kötelező.")]
[DisplayName("Ellenőrzési pont")] [DisplayName("Ellenőrzési pont")]
public int CheckPointId { get; set; } public int CheckPointId { get; set; }
public CheckPointDTO? CheckPointDTO { get; set; } = null!; public CheckPointDTO? CheckPointDTO { get; set; } = null!;
[DisplayName("Engedélyezve?")] [DisplayName("Engedélyezve?")]
public bool Enabled { get; set; } = false; public bool Enabled { get; set; } = false;
} }
} }
+35 -35
View File
@@ -1,35 +1,35 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel; using System.ComponentModel;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class RoleDTO public class RoleDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "A szabály megnevezésének megadása kötelező.")] [Required(ErrorMessage = "A szabály megnevezésének megadása kötelező.")]
[DisplayName("Megnevezés")] [DisplayName("Megnevezés")]
public string RoleName { get; set; } = null!; public string RoleName { get; set; } = null!;
public int? ParentId { get; set; } public int? ParentId { get; set; }
[DisplayName("Szülő szerepkör neve")] [DisplayName("Szülő szerepkör neve")]
public string? ParentRoleName { get; set; } public string? ParentRoleName { get; set; }
[DisplayName("Adminisztrátor?")] [DisplayName("Adminisztrátor?")]
public bool IsAdmin { get; set; } public bool IsAdmin { get; set; }
[DisplayName("Új program letöltés?")] [DisplayName("Új program letöltés?")]
public bool CanDownloadAPK { get; set; } public bool CanDownloadAPK { get; set; }
[DisplayName("Folyamat blokk/engedélyez?")] [DisplayName("Folyamat blokk/engedélyez?")]
public bool CanEnableBlocked { get; set; } public bool CanEnableBlocked { get; set; }
[DisplayName("WEB felület?")] [DisplayName("WEB felület?")]
public bool CanUseWebAdmin { get; set; } public bool CanUseWebAdmin { get; set; }
[DisplayName("Mobil App?")] [DisplayName("Mobil App?")]
public bool CanUseMobilApp { get; set; } public bool CanUseMobilApp { get; set; }
} }
} }
+17 -17
View File
@@ -1,17 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class User2FADTO public class User2FADTO
{ {
public string UserName { get; set; } = null!; public string UserName { get; set; } = null!;
public string Password { get; set; } = null!; public string Password { get; set; } = null!;
public string Code { get; set; } = null!; public string Code { get; set; } = null!;
public string Token2FA { get; set; } = null!; public string Token2FA { get; set; } = null!;
} }
} }
@@ -1,34 +1,34 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class UserChangePassword2FADTO public class UserChangePassword2FADTO
{ {
public int UserId { get; set; } public int UserId { get; set; }
[DisplayName("Felhasználó")] [DisplayName("Felhasználó")]
public string UserName { get; set; } = null!; public string UserName { get; set; } = null!;
[DisplayName("Régi jelszó")] [DisplayName("Régi jelszó")]
public string OldPassword { get; set; } = null!; public string OldPassword { get; set; } = null!;
[Required(ErrorMessage = "A jelszó kötelező.")] [Required(ErrorMessage = "A jelszó kötelező.")]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,}$", ErrorMessage = "Az új jelszónak legalább 6 karakter hosszúnak kell lennie, és tartalmaznia kell kis- és nagybetűt, számot és speciális karaktert.")] [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,}$", ErrorMessage = "Az új jelszónak legalább 6 karakter hosszúnak kell lennie, és tartalmaznia kell kis- és nagybetűt, számot és speciális karaktert.")]
[DisplayName("Új jelszó")] [DisplayName("Új jelszó")]
public string NewPassword1 { get; set; } = null!; public string NewPassword1 { get; set; } = null!;
[Required(ErrorMessage = "A jelszó kötelező.")] [Required(ErrorMessage = "A jelszó kötelező.")]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,}$", ErrorMessage = "Az új jelszónak legalább 6 karakter hosszúnak kell lennie, és tartalmaznia kell kis- és nagybetűt, számot és speciális karaktert.")] [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,}$", ErrorMessage = "Az új jelszónak legalább 6 karakter hosszúnak kell lennie, és tartalmaznia kell kis- és nagybetűt, számot és speciális karaktert.")]
[DisplayName("Jelszó megerősítése")] [DisplayName("Jelszó megerősítése")]
public string NewPassword2 { get; set; } = null!; public string NewPassword2 { get; set; } = null!;
[DisplayName("Ellenőrző kód")] [DisplayName("Ellenőrző kód")]
public string Code { get; set; } = null!; public string Code { get; set; } = null!;
public string Token2FA { get; set; } = null!; public string Token2FA { get; set; } = null!;
} }
} }
+47 -47
View File
@@ -1,47 +1,47 @@
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class UserDTO public class UserDTO
{ {
public int Id { get; set; } public int Id { get; set; }
[Required(ErrorMessage = "Az utónév kötelező.")] [Required(ErrorMessage = "Az utónév kötelező.")]
[EmailAddress(ErrorMessage = "Érvénytelen email cím.")] [EmailAddress(ErrorMessage = "Érvénytelen email cím.")]
[RegularExpression(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", ErrorMessage = "Az email formátum nem megfelelő.")] [RegularExpression(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", ErrorMessage = "Az email formátum nem megfelelő.")]
[DisplayName("E-mail")] [DisplayName("E-mail")]
public string Email { get; set; } = null!; public string Email { get; set; } = null!;
[Required(ErrorMessage = "Az utónév kötelező.")] [Required(ErrorMessage = "Az utónév kötelező.")]
[DisplayName("Utónév")] [DisplayName("Utónév")]
public string FirstName { get; set; } = null!; public string FirstName { get; set; } = null!;
[Required(ErrorMessage = "Az vezetéknév kötelező.")] [Required(ErrorMessage = "Az vezetéknév kötelező.")]
[DisplayName("Vezetéknév")] [DisplayName("Vezetéknév")]
public string LastName { get; set; } = null!; public string LastName { get; set; } = null!;
[Required(ErrorMessage = "A felhasználónév kötelező.")] [Required(ErrorMessage = "A felhasználónév kötelező.")]
[DisplayName("Felhasználó neve")] [DisplayName("Felhasználó neve")]
public string UserName { get;set; } = null!; public string UserName { get;set; } = null!;
[Required(ErrorMessage = "A jelszó kötelező.")] [Required(ErrorMessage = "A jelszó kötelező.")]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,}$", ErrorMessage = "A jelszónak legalább 6 karakter hosszúnak kell lennie, és tartalmaznia kell kis- és nagybetűt, számot és speciális karaktert.")] [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,}$", ErrorMessage = "A jelszónak legalább 6 karakter hosszúnak kell lennie, és tartalmaznia kell kis- és nagybetűt, számot és speciális karaktert.")]
[DisplayName("Jelszó")] [DisplayName("Jelszó")]
public string Password { get; set; } = null!; public string Password { get; set; } = null!;
public string JwtToken { get; set; } = null!; public string JwtToken { get; set; } = null!;
[DisplayName("Aktív")] [DisplayName("Aktív")]
public bool Active { get; set; } public bool Active { get; set; }
[DisplayName("NFC belépés")] [DisplayName("NFC belépés")]
public bool NFCActive { get; set; } public bool NFCActive { get; set; }
[DisplayName("NFC kód")] [DisplayName("NFC kód")]
public string NFCCode { get; set; } = null!; public string NFCCode { get; set; } = null!;
public ICollection<RoleDTO>? RoleDTO { get; set; } = new List<RoleDTO>(); public ICollection<RoleDTO>? RoleDTO { get; set; } = new List<RoleDTO>();
} }
} }
+19 -19
View File
@@ -1,19 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class UserRoleDTO public class UserRoleDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public int? RoleId { get; set; } = 0; public int? RoleId { get; set; } = 0;
public RoleDTO? RoleDTO { get; set; } public RoleDTO? RoleDTO { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public UserDTO? UserDTO { get; set; } public UserDTO? UserDTO { get; set; }
} }
} }
+17 -17
View File
@@ -1,17 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO namespace WorkFlowCheck.Common.DTO
{ {
public class UserSimpleDTO public class UserSimpleDTO
{ {
[Required(ErrorMessage = "A felhasználónév kötelező.")] [Required(ErrorMessage = "A felhasználónév kötelező.")]
public string UserName { get; set; } = null!; public string UserName { get; set; } = null!;
[Required(ErrorMessage = "A jelszó megadása kötelező.")] [Required(ErrorMessage = "A jelszó megadása kötelező.")]
public string Password { get; set; } public string Password { get; set; }
} }
} }
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DataTables
{
public class DataTablesRequest
{
public int Mode { get; set; }
public int Draw { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public DataTablesSearch Search { get; set; } = new();
public List<DataTablesOrder> Order { get; set; } = new();
public List<DataTablesColumn> Columns { get; set; } = new();
}
public class DataTablesSearch { public string? Value { get; set; } }
public class DataTablesOrder { public int Column { get; set; } public string? Dir { get; set; } }
public class DataTablesColumn { public string? Data { get; set; } public bool Searchable { get; set; } public bool Orderable { get; set; } }
}
+35 -35
View File
@@ -1,35 +1,35 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace WorkFlowCheck.Common.Enums namespace WorkFlowCheck.Common.Enums
{ {
public enum CheckStatus public enum CheckStatus
{ {
[Display(Name = "Nyitott")] [Display(Name = "Nyitott")]
Open = 0, Open = 0,
[Display(Name = "Folyamatban")] [Display(Name = "Folyamatban")]
InProgress = 1, InProgress = 1,
[Display(Name = "Blokkolt")] [Display(Name = "Blokkolt")]
Blocked = 2, Blocked = 2,
[Display(Name = "Sztornózva")] [Display(Name = "Sztornózva")]
Storno = 3, Storno = 3,
[Display(Name = "Beküldött")] [Display(Name = "Beküldött")]
Sent = 4, Sent = 4,
[Display(Name = "Jóváhagyva")] [Display(Name = "Jóváhagyva")]
Signed = 5, Signed = 5,
[Display(Name = "Lezárva")] [Display(Name = "Lezárva")]
Closed = 6 Closed = 6
} }
} }
@@ -1,33 +1,33 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.Helper namespace WorkFlowCheck.Common.Helper
{ {
public static class DisplayNameHelper public static class DisplayNameHelper
{ {
public static string GetDisplayName(string propertyName, Type modelType) public static string GetDisplayName(string propertyName, Type modelType)
{ {
var property = modelType.GetProperty(propertyName); var property = modelType.GetProperty(propertyName);
var displayNameAttribute = property?.GetCustomAttributes(typeof(DisplayNameAttribute), false) var displayNameAttribute = property?.GetCustomAttributes(typeof(DisplayNameAttribute), false)
.FirstOrDefault() as DisplayNameAttribute; .FirstOrDefault() as DisplayNameAttribute;
return displayNameAttribute?.DisplayName ?? propertyName; return displayNameAttribute?.DisplayName ?? propertyName;
} }
public static string GetEnumDisplayName(this Enum enumValue) public static string GetEnumDisplayName(this Enum enumValue)
{ {
return enumValue return enumValue
.GetType() .GetType()
.GetMember(enumValue.ToString()) .GetMember(enumValue.ToString())
.First() .First()
.GetCustomAttribute<DisplayAttribute>()? .GetCustomAttribute<DisplayAttribute>()?
.Name ?? enumValue.ToString(); .Name ?? enumValue.ToString();
} }
} }
} }
@@ -1,18 +1,18 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.RequestContext namespace WorkFlowCheck.Common.RequestContext
{ {
public interface IRequestContext public interface IRequestContext
{ {
string TraceId { get; } string TraceId { get; }
string CurrentUsername { get; } string CurrentUsername { get; }
string CurrentUserEmail { get; } string CurrentUserEmail { get; }
int? CurrentUserId { get; } int? CurrentUserId { get; }
CancellationToken RequestAborted { get; } CancellationToken RequestAborted { get; }
} }
} }
@@ -1,55 +1,57 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.SqlTypes; using System.Data.SqlTypes;
using System.Linq; using System.Linq;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.Common.Security namespace WorkFlowCheck.Common.Security
{ {
public static class PasswordHasher public static class PasswordHasher
{ {
// Jelszó hashelése // Jelszó hashelése
private const string _saltstring = "xc45DDfrt!!ED210:"; private const string _saltstring = "xc45DDfrt!!ED210:";
public static string HashPassword(string password) public static string HashPassword(string password)
{ {
// Generate a random salt // Generate a random salt
byte[] salt = Encoding.UTF8.GetBytes(_saltstring); byte[] salt = Encoding.UTF8.GetBytes(_saltstring);
// Hash the password with the salt // Hash the password with the salt
using (var rfc2898 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256)) using (var rfc2898 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256))
{ {
byte[] hash = rfc2898.GetBytes(32); // 256-bit hash byte[] hash = rfc2898.GetBytes(32); // 256-bit hash
byte[] hashBytes = new byte[48]; // Salt (16 bytes) + Hash (32 bytes) byte[] hashBytes = new byte[48]; // Salt (16 bytes) + Hash (32 bytes)
Array.Copy(salt, 0, hashBytes, 0, 16); Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 32); Array.Copy(hash, 0, hashBytes, 16, 32);
return Convert.ToBase64String(hashBytes); return Convert.ToBase64String(hashBytes);
} }
} }
// Jelszó ellenőrzése // Jelszó ellenőrzése
public static bool VerifyPassword(string storedPasswordHash, string inputPassword) public static bool VerifyPassword(string storedPasswordHash, string inputPassword)
{ {
byte[] hashBytes = Convert.FromBase64String(storedPasswordHash); var inputPasswordHash = HashPassword(inputPassword);
// Extract salt (first 16 bytes) and stored hash (next 32 bytes) byte[] hashBytes = Convert.FromBase64String(storedPasswordHash);
byte[] salt = Encoding.UTF8.GetBytes(_saltstring);
byte[] storedHash = new byte[32]; // Extract salt (first 16 bytes) and stored hash (next 32 bytes)
Array.Copy(hashBytes, 0, salt, 0, 16); byte[] salt = Encoding.UTF8.GetBytes(_saltstring);
Array.Copy(hashBytes, 16, storedHash, 0, 32); byte[] storedHash = new byte[32];
Array.Copy(hashBytes, 0, salt, 0, 16);
// Hash the input password with the same salt Array.Copy(hashBytes, 16, storedHash, 0, 32);
using (var rfc2898 = new Rfc2898DeriveBytes(inputPassword, salt, 10000, HashAlgorithmName.SHA256))
{ // Hash the input password with the same salt
byte[] inputHash = rfc2898.GetBytes(32); using (var rfc2898 = new Rfc2898DeriveBytes(inputPassword, salt, 10000, HashAlgorithmName.SHA256))
{
// Compare the stored hash and the calculated hash byte[] inputHash = rfc2898.GetBytes(32);
return CryptographicOperations.FixedTimeEquals(storedHash, inputHash);
} // Compare the stored hash and the calculated hash
} return CryptographicOperations.FixedTimeEquals(storedHash, inputHash);
} }
} }
}
}
@@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
+191 -191
View File
@@ -1,191 +1,191 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.ChangeTracking;
using System; using System;
using WorkFlowCheck.Common.RequestContext; using WorkFlowCheck.Common.RequestContext;
using WorkFlowCheck.Common.Security; using WorkFlowCheck.Common.Security;
using WorkFlowCheck.DL.Configurations; using WorkFlowCheck.DL.Configurations;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.DL.Entities;
using WorkFlowCheck.DL.Extensions; using WorkFlowCheck.DL.Extensions;
using WorkFlowCheck.DL.Interfaces; using WorkFlowCheck.DL.Interfaces;
namespace WorkFlowCheck.DL namespace WorkFlowCheck.DL
{ {
public class AppDbContext : DbContext public class AppDbContext : DbContext
{ {
private readonly IRequestContext _requestContext; private readonly IRequestContext _requestContext;
public AppDbContext(DbContextOptions<AppDbContext> options, IRequestContext requestContext) public AppDbContext(DbContextOptions<AppDbContext> options, IRequestContext requestContext)
: base(options) : base(options)
{ {
_requestContext = requestContext; _requestContext = requestContext;
} }
#region Entities DbSet #region Entities DbSet
public DbSet<Entities.CheckListHeader> CheckListHeaders { get; set; } = null!; public DbSet<Entities.CheckListHeader> CheckListHeaders { get; set; } = null!;
public DbSet<Entities.CheckListRow> CheckListRows { get; set; } = null!; public DbSet<Entities.CheckListRow> CheckListRows { get; set; } = null!;
public DbSet<Entities.CheckListTemplateHeader> CheckListTemplateHeaders { get; set; } = null!; public DbSet<Entities.CheckListTemplateHeader> CheckListTemplateHeaders { get; set; } = null!;
public DbSet<Entities.CheckListTemplateRow> CheckListTemplateRows { get; set; } = null!; public DbSet<Entities.CheckListTemplateRow> CheckListTemplateRows { get; set; } = null!;
public DbSet<Entities.CheckPoint> CheckPoints { get; set; } = null!; public DbSet<Entities.CheckPoint> CheckPoints { get; set; } = null!;
public DbSet<DeviceMessage> DeviceMessages { get; set; } = null!; public DbSet<DeviceMessage> DeviceMessages { get; set; } = null!;
public DbSet<Entities.Equipment> Equipments { get; set; } = null!; public DbSet<Entities.Equipment> Equipments { get; set; } = null!;
public DbSet<Entities.FCMToken> FCMTokens { get; set; } = null!; public DbSet<Entities.FCMToken> FCMTokens { get; set; } = null!;
public DbSet<Entities.Location> Locations { get; set; } = null!; public DbSet<Entities.Location> Locations { get; set; } = null!;
public DbSet<Entities.NumberGeneratorTemplate> NumberGeneratorTemplates { get; set; } = null!; public DbSet<Entities.NumberGeneratorTemplate> NumberGeneratorTemplates { get; set; } = null!;
public DbSet<Entities.NumberGeneratorTemplateDate> NumberGeneratorTemplateDates { get; set; } = null!; public DbSet<Entities.NumberGeneratorTemplateDate> NumberGeneratorTemplateDates { get; set; } = null!;
public DbSet<Entities.Role> Roles { get; set; } = null!; public DbSet<Entities.Role> Roles { get; set; } = null!;
public DbSet<Entities.User> Users { get; set; } = null!; public DbSet<Entities.User> Users { get; set; } = null!;
public DbSet<Entities.UserRole> UserRoles { get; set; } = null!; public DbSet<Entities.UserRole> UserRoles { get; set; } = null!;
public DbSet<Entities.RoleCheckListTemplateHeader> RoleCheckListTemplateHeaders { get; set; } = null!; public DbSet<Entities.RoleCheckListTemplateHeader> RoleCheckListTemplateHeaders { get; set; } = null!;
public DbSet<Entities.RoleCheckPoint> RoleCheckPoints { get; set; } = null!; public DbSet<Entities.RoleCheckPoint> RoleCheckPoints { get; set; } = null!;
#endregion #endregion
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.ApplyConfiguration(new CheckListHeaderTypeConfiguration()); modelBuilder.ApplyConfiguration(new CheckListHeaderTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListRowTypeConfiguration()); modelBuilder.ApplyConfiguration(new CheckListRowTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListTemplateHeaderTypeConfiguration()); modelBuilder.ApplyConfiguration(new CheckListTemplateHeaderTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListTemplateRowTypeConfiguration()); modelBuilder.ApplyConfiguration(new CheckListTemplateRowTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckPointTypeConfiguration()); modelBuilder.ApplyConfiguration(new CheckPointTypeConfiguration());
modelBuilder.ApplyConfiguration(new DeviceMessageTypeConfiguration()); modelBuilder.ApplyConfiguration(new DeviceMessageTypeConfiguration());
modelBuilder.ApplyConfiguration(new EquipmentTypeConfiguration()); modelBuilder.ApplyConfiguration(new EquipmentTypeConfiguration());
modelBuilder.ApplyConfiguration(new FCMTokenTypeConfiguration()); modelBuilder.ApplyConfiguration(new FCMTokenTypeConfiguration());
modelBuilder.ApplyConfiguration(new LocationTypeConfiguration()); modelBuilder.ApplyConfiguration(new LocationTypeConfiguration());
modelBuilder.ApplyConfiguration(new NumberGeneratorTypeConfiguration()); modelBuilder.ApplyConfiguration(new NumberGeneratorTypeConfiguration());
modelBuilder.ApplyConfiguration(new NumberGeneratorDateTypeConfiguration()); modelBuilder.ApplyConfiguration(new NumberGeneratorDateTypeConfiguration());
modelBuilder.ApplyConfiguration(new RoleTypeConfiguration()); modelBuilder.ApplyConfiguration(new RoleTypeConfiguration());
modelBuilder.ApplyConfiguration(new RoleCheckListTemplateHeaderTypeConfiguration()); modelBuilder.ApplyConfiguration(new RoleCheckListTemplateHeaderTypeConfiguration());
modelBuilder.ApplyConfiguration(new RoleCheckPointTypeConfiguration()); modelBuilder.ApplyConfiguration(new RoleCheckPointTypeConfiguration());
modelBuilder.ApplyConfiguration(new UserTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserTypeConfiguration());
modelBuilder.ApplyConfiguration(new UserRoleTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserRoleTypeConfiguration());
modelBuilder.RegisterSoftDeleteQueryFilters(); modelBuilder.RegisterSoftDeleteQueryFilters();
SeedInit(modelBuilder); SeedInit(modelBuilder);
} }
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{ {
SaveChangesCore(); SaveChangesCore();
return await base.SaveChangesAsync(cancellationToken); return await base.SaveChangesAsync(cancellationToken);
} }
protected virtual void SaveChangesCore() protected virtual void SaveChangesCore()
{ {
var utcNow = DateTime.UtcNow; var utcNow = DateTime.UtcNow;
var deletedEntries = ChangeTracker var deletedEntries = ChangeTracker
.Entries() .Entries()
.Where(e => e.Entity is ISoftDeletableEntity && e.State == EntityState.Deleted); .Where(e => e.Entity is ISoftDeletableEntity && e.State == EntityState.Deleted);
UpdateDeletedEntries(deletedEntries); UpdateDeletedEntries(deletedEntries);
var modifiedEntries = ChangeTracker var modifiedEntries = ChangeTracker
.Entries() .Entries()
.Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Modified); .Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Modified);
UpdateModifiedEntires(modifiedEntries, utcNow); UpdateModifiedEntires(modifiedEntries, utcNow);
var addedEntries = ChangeTracker var addedEntries = ChangeTracker
.Entries() .Entries()
.Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Added); .Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Added);
UpdateAddedEntries(addedEntries, utcNow); UpdateAddedEntries(addedEntries, utcNow);
} }
private void UpdateAddedEntries(IEnumerable<EntityEntry> addedEntries, DateTime utcNow) private void UpdateAddedEntries(IEnumerable<EntityEntry> addedEntries, DateTime utcNow)
{ {
foreach (var entry in addedEntries) foreach (var entry in addedEntries)
{ {
((IAuditableEntity)entry.Entity).CreatedAt = utcNow; ((IAuditableEntity)entry.Entity).CreatedAt = utcNow;
((IAuditableEntity)entry.Entity).LastModAt = utcNow; ((IAuditableEntity)entry.Entity).LastModAt = utcNow;
((IAuditableEntity)entry.Entity).CreatedBy = _requestContext.CurrentUsername ?? "Admin"; ((IAuditableEntity)entry.Entity).CreatedBy = _requestContext.CurrentUsername ?? "Admin";
((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin"; ((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin";
} }
} }
private void UpdateModifiedEntires(IEnumerable<EntityEntry> modifiedEntries, DateTime utcNow) private void UpdateModifiedEntires(IEnumerable<EntityEntry> modifiedEntries, DateTime utcNow)
{ {
foreach (var entry in modifiedEntries) foreach (var entry in modifiedEntries)
{ {
((IAuditableEntity)entry.Entity).LastModAt = utcNow; ((IAuditableEntity)entry.Entity).LastModAt = utcNow;
((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin"; ((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin";
} }
} }
private void UpdateDeletedEntries(IEnumerable<EntityEntry> deletedEntries) private void UpdateDeletedEntries(IEnumerable<EntityEntry> deletedEntries)
{ {
foreach (var entry in deletedEntries) foreach (var entry in deletedEntries)
{ {
((ISoftDeletableEntity)entry.Entity).IsDeleted = true; ((ISoftDeletableEntity)entry.Entity).IsDeleted = true;
entry.State = EntityState.Modified; entry.State = EntityState.Modified;
} }
} }
private void SeedInit(ModelBuilder modelBuilder) private void SeedInit(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<User>().HasData( modelBuilder.Entity<User>().HasData(
new User new User
{ {
Id = 1, Id = 1,
Email = "admin@nuvolar.hu", Email = "admin@nuvolar.hu",
FirstName = "Administrator", FirstName = "Administrator",
LastName = "System", LastName = "System",
IsDeleted = false, IsDeleted = false,
UserName = "admin", UserName = "admin",
PasswordHash = PasswordHasher.HashPassword("111111"), PasswordHash = PasswordHasher.HashPassword("111111"),
CreatedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow,
CreatedBy = "System", CreatedBy = "System",
LastModAt = DateTime.UtcNow, LastModAt = DateTime.UtcNow,
LastModBy = "System", LastModBy = "System",
JwtToken = "", JwtToken = "",
Active = true, Active = true,
Token2FA = "", Token2FA = "",
NFCActive = true, NFCActive = true,
NFCCode = "00000000" NFCCode = "00000000"
}, },
new User new User
{ {
Id = 2, Id = 2,
Email = "user@nuvolar.hu", Email = "user@nuvolar.hu",
FirstName = "User", FirstName = "User",
LastName = "System", LastName = "System",
IsDeleted = false, IsDeleted = false,
UserName = "user", UserName = "user",
PasswordHash = PasswordHasher.HashPassword("222222"), PasswordHash = PasswordHasher.HashPassword("222222"),
CreatedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow,
CreatedBy = "System", CreatedBy = "System",
LastModAt = DateTime.UtcNow, LastModAt = DateTime.UtcNow,
LastModBy = "System", LastModBy = "System",
JwtToken = "", JwtToken = "",
Active = true, Active = true,
Token2FA = "", Token2FA = "",
NFCActive = true, NFCActive = true,
NFCCode = "00000000" NFCCode = "00000000"
} }
); );
modelBuilder.Entity<NumberGeneratorTemplate>().HasData( modelBuilder.Entity<NumberGeneratorTemplate>().HasData(
new NumberGeneratorTemplate new NumberGeneratorTemplate
{ {
Id = 1, Id = 1,
CurrentNumber = 0, CurrentNumber = 0,
DigitFormat = "D4", DigitFormat = "D4",
GenerateType = GenerateType.OnlyYear, GenerateType = GenerateType.OnlyYear,
LastGeneratedNumber = "", LastGeneratedNumber = "",
Prefix = "CHK", Prefix = "CHK",
PrefixSeparator = "-", PrefixSeparator = "-",
ShortName = "Ellenőrzési dokumentum sorszámozása", ShortName = "Ellenőrzési dokumentum sorszámozása",
Suffix = "", Suffix = "",
SuffixSeparator = "-", SuffixSeparator = "-",
} }
); );
modelBuilder.Entity<NumberGeneratorTemplateDate>().HasData( modelBuilder.Entity<NumberGeneratorTemplateDate>().HasData(
new NumberGeneratorTemplateDate new NumberGeneratorTemplateDate
{ {
Id = 1, Id = 1,
CurrentNumber = 0, CurrentNumber = 0,
LastGeneratedNumber = "", LastGeneratedNumber = "",
Month = 0, Month = 0,
Year = 1, Year = 1,
NumberGeneratorTemplateId = 1, NumberGeneratorTemplateId = 1,
} }
); );
} }
} }
} }
@@ -1,27 +1,27 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection.Emit; using System.Reflection.Emit;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.DL.Entities;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class CheckListHeaderTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListHeader> public class CheckListHeaderTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListHeader>
{ {
public void Configure(EntityTypeBuilder<Entities.CheckListHeader> builder) public void Configure(EntityTypeBuilder<Entities.CheckListHeader> builder)
{ {
builder.ToTable("CheckListHeader"); builder.ToTable("CheckListHeader");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
builder builder
.HasOne(ch => ch.AcceptUser) .HasOne(ch => ch.AcceptUser)
.WithMany() .WithMany()
.HasForeignKey(ch => ch.AcceptUserId) .HasForeignKey(ch => ch.AcceptUserId)
.OnDelete(DeleteBehavior.Restrict); // Elkerüljük a cascade delete-et .OnDelete(DeleteBehavior.Restrict); // Elkerüljük a cascade delete-et
} }
} }
} }
@@ -1,21 +1,21 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class CheckListRowTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListRow> public class CheckListRowTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListRow>
{ {
public void Configure(EntityTypeBuilder<Entities.CheckListRow> builder) public void Configure(EntityTypeBuilder<Entities.CheckListRow> builder)
{ {
builder.ToTable("CheckListRow"); builder.ToTable("CheckListRow");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
} }
} }
} }
@@ -1,21 +1,21 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class CheckListTemplateHeaderTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListTemplateHeader> public class CheckListTemplateHeaderTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListTemplateHeader>
{ {
public void Configure(EntityTypeBuilder<Entities.CheckListTemplateHeader> builder) public void Configure(EntityTypeBuilder<Entities.CheckListTemplateHeader> builder)
{ {
builder.ToTable("CheckListTemplateHeader"); builder.ToTable("CheckListTemplateHeader");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
} }
} }
} }
@@ -1,21 +1,21 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class CheckListTemplateRowTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListTemplateRow> public class CheckListTemplateRowTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListTemplateRow>
{ {
public void Configure(EntityTypeBuilder<Entities.CheckListTemplateRow> builder) public void Configure(EntityTypeBuilder<Entities.CheckListTemplateRow> builder)
{ {
builder.ToTable("CheckListTemplateRow"); builder.ToTable("CheckListTemplateRow");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
} }
} }
} }
@@ -1,21 +1,21 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class CheckPointTypeConfiguration : IEntityTypeConfiguration<Entities.CheckPoint> public class CheckPointTypeConfiguration : IEntityTypeConfiguration<Entities.CheckPoint>
{ {
public void Configure(EntityTypeBuilder<Entities.CheckPoint> builder) public void Configure(EntityTypeBuilder<Entities.CheckPoint> builder)
{ {
builder.ToTable("CheckPoint"); builder.ToTable("CheckPoint");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
} }
} }
} }
@@ -1,24 +1,24 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class DeviceMessageTypeConfiguration : IEntityTypeConfiguration<Entities.DeviceMessage> public class DeviceMessageTypeConfiguration : IEntityTypeConfiguration<Entities.DeviceMessage>
{ {
public void Configure(EntityTypeBuilder<Entities.DeviceMessage> builder) public void Configure(EntityTypeBuilder<Entities.DeviceMessage> builder)
{ {
builder.ToTable("DeviceMessage"); builder.ToTable("DeviceMessage");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
builder.HasIndex(e => e.DeviceIdTo) builder.HasIndex(e => e.DeviceIdTo)
.HasDatabaseName("IX_DeviceMessage_DeviceIdTo"); .HasDatabaseName("IX_DeviceMessage_DeviceIdTo");
} }
} }
} }
@@ -1,21 +1,21 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class EquipmentTypeConfiguration : IEntityTypeConfiguration<Entities.Equipment> public class EquipmentTypeConfiguration : IEntityTypeConfiguration<Entities.Equipment>
{ {
public void Configure(EntityTypeBuilder<Entities.Equipment> builder) public void Configure(EntityTypeBuilder<Entities.Equipment> builder)
{ {
builder.ToTable("Equipment"); builder.ToTable("Equipment");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
} }
} }
} }
@@ -1,21 +1,21 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations namespace WorkFlowCheck.DL.Configurations
{ {
public class FCMTokenTypeConfiguration : IEntityTypeConfiguration<Entities.FCMToken> public class FCMTokenTypeConfiguration : IEntityTypeConfiguration<Entities.FCMToken>
{ {
public void Configure(EntityTypeBuilder<Entities.FCMToken> builder) public void Configure(EntityTypeBuilder<Entities.FCMToken> builder)
{ {
builder.ToTable("FCMToken"); builder.ToTable("FCMToken");
builder.HasKey(e => e.Id); builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.Property(e => e.Id).ValueGeneratedOnAdd();
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More