182 Commits
Author SHA1 Message Date
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
ivanszabo 7f3562fb73 MemoryStreamos a fotó ... 2025-07-02 18:30:10 +02:00
ivanszabo bc977af15c Alap BUGFIX javításhoz 2025-07-02 13:32:33 +02:00
ivanszabo 6be6bc533c Hogy az "élesre" menjen .. 2025-07-01 17:13:34 +02:00
ivanszabo 864c76f827 BUGFIX Scroll javítása 1.1.035 2025-07-01 10:47:47 +02:00
ivanszabo 8208b31d08 1.1.033 Fényképek beküldése javítása 2025-07-01 08:30:34 +02:00
ivanszabo 4f149f4eef 1.1.030 2025-06-30 07:24:55 +02:00
ivanszabo 8ce7268338 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-06-29 13:30:38 +02:00
ivanszabo d42900e8f6 MOBILE BugFix 2025-06-29 13:30:34 +02:00
ivanszabo 25cd092a08 Backend BUGFIX 2025-06-29 13:30:08 +02:00
ivanszabo e5dd9aad27 A PDF generálásának javítása 2025-06-17 11:35:36 +02:00
ivanszabo d1ad7e76c3 Na most van jól beállítva a dolog. 2025-06-10 17:26:14 +02:00
ivanszabo 5e94586a75 Jóváhagyási BUGFIX 2025-06-10 12:14:52 +02:00
ivanszabo d775ae82a0 GIT 2025-06-10 12:14:41 +02:00
ivanszabo e6b53d193c ok 2025-06-06 08:47:53 +02:00
ivanszabo 400a459479 Itt maradt 2025-06-06 08:46:12 +02:00
Iván Szabó ac74ef9cfc v1.1.030 2025-06-05 08:56:22 +02:00
Iván Szabó 4c7d71a404 Blokkolás és frissítés is 2025-06-05 08:47:17 +02:00
ivanszabo 75d8119880 Ellenőrző lap mdosíthatósága 2025-06-05 08:12:27 +02:00
ivanszabo ff9d6ae361 Fontos kezelési javítások 2025-06-04 12:25:04 +02:00
ivanszabo 6839fc0b78 Hibajavítás hegyek 2025-06-04 11:05:29 +02:00
ivanszabo 11aea1eb5d git change 2025-06-04 09:13:52 +02:00
ivanszabo fb58bfcde0 PDF javítása 2025-05-23 21:20:05 +02:00
ivanszabo 7be3a5c58a console.log kivétele 2025-05-23 20:42:42 +02:00
ivanszabo d3e63404a2 Jóváhagyás utáni automatikus mail + CheckListHeader ShortName és Description javítása 2025-05-23 20:41:44 +02:00
ivanszabo cd0b1da85b v1.1.025 release kiadása 2025-05-23 10:51:44 +02:00
ivanszabo dc12fe8709 v1.1.025 MOBILE 2025-05-23 10:51:31 +02:00
ivanszabo 92dcb645db Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-05-23 10:50:22 +02:00
ivanszabo 0d83e30cd2 Lezárás javítása 2025-05-23 10:50:13 +02:00
ivanszabo 2318269f99 Manuális lezárás indokkal 2025-05-23 10:49:02 +02:00
ivanszabo 84f161585a Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-05-22 21:02:14 +02:00
ivanszabo 05259a09ee CheckListInfoPage implementálása 2025-05-22 21:02:09 +02:00
ivanszabo 98442dfe90 PDF javítása + %-os készültség javítása 2025-05-22 21:01:27 +02:00
ivanszabo e745f313a8 Megfelelő hang lejátszása is javítva 2025-05-16 08:40:51 +02:00
ivanszabo 254ab86d03 Egy pici javítás 2025-05-16 08:40:33 +02:00
ivanszabo 4c25dd2105 FCM kifejlesztése 2025-05-16 07:45:58 +02:00
ivanszabo da92dc45b6 Firebase FCM kliens működik 2025-05-16 07:27:02 +02:00
ivanszabo e8f7ee7e36 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-05-15 14:45:51 +02:00
ivanszabo 1f4fce1e42 X 2025-05-15 14:45:00 +02:00
ivanszabo b6ffcca996 Firebird Cloud Message API előkészítése 2025-05-15 14:41:34 +02:00
ivanszabo 73a4b9a445 Na most kaptam TOKENT!!! 2025-05-15 09:39:33 +02:00
ivanszabo 9df2854a3c Firebase teszthez 2025-05-15 09:28:08 +02:00
ivanszabo 7efd090b86 Forebird.CloudMessages implementálása 2025-05-14 21:56:33 +02:00
ivanszabo 0a36544dce Klónozás javítása 2025-05-08 11:01:55 +02:00
ivanszabo 699110af10 Privacy kialakítása 2025-05-07 13:25:27 +02:00
ivanszabo 272bd1a3fd CheckListTemplateHeader klónozása 2025-05-07 13:05:28 +02:00
ivanszabo 9ffbcd87f2 Business és Audit log hozzáadva, WEB-en letölthető 2025-04-28 11:35:30 +02:00
ivanszabo 2fae17fed4 CheckListTemplateHeader törlése WEB-ről 2025-04-25 11:38:09 +02:00
ivanszabo 4025224821 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-25 10:32:08 +02:00
ivanszabo 89c330aa0d CheckListHeader-be új infók 2025-04-25 10:31:43 +02:00
ivanszabo c028b78f1c CheckListHeader-be új infók 2025-04-25 10:31:42 +02:00
ivanszabo a324f5f852 1.1.019 verzió kiadása 2025-04-25 10:31:42 +02:00
ivanszabo 62419a2c28 MOBILE BUGFIX-ek 2025-04-25 10:29:14 +02:00
ivanszabo 1294a00219 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-22 18:38:42 +02:00
ivanszabo 0de851f7d9 Version MOBILE 2025-04-22 18:38:33 +02:00
ivanszabo f80029bd07 API URL beállítása 2025-04-22 18:12:57 +02:00
ivanszabo a8b4aa7b22 ProgramVersion - Backend 2025-04-22 18:05:31 +02:00
ivanszabo 4b674d67ab v1.1.018 Backend 2025-04-22 14:40:02 +02:00
ivanszabo f6e21418b6 v1.1.018 MOBILE 2025-04-22 14:38:43 +02:00
ivanszabo bb8d866778 Javítás a Blokkolt tételekre is. 2025-04-22 14:18:06 +02:00
ivanszabo 3c394f632d Most működik egy tesztelhető verzió. 2025-04-22 14:17:11 +02:00
ivanszabo cba9181a2d Kis kerek gombok + Egyéb nyalánkságok 2025-04-21 19:16:58 +02:00
ivanszabo dbc2f30a27 Jóváhagyás gomb MOBIL-on 2025-04-17 14:39:50 +02:00
ivanszabo 2798aeaf0d Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-17 13:30:33 +02:00
ivanszabo bce3c9e401 Feloldás mobilról 2025-04-17 08:41:56 +02:00
ivanszabo 5acf9ff954 PDF könyvtár letöltése 2025-04-16 13:29:07 +02:00
ivanszabo a1d683b955 Fényképek letöltése programból 2025-04-16 12:34:00 +02:00
ivanszabo 335f00367d DeviceMessages-hez backend fejlesztése 2025-04-16 08:42:14 +02:00
ivanszabo 8815df06b3 Figyelmeztető üzenet javítása + hangjelzés 2025-04-16 08:41:30 +02:00
ivanszabo ab86c845ab Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-15 19:42:56 +02:00
ivanszabo e151590860 Userhez is lehet már NFC kódot rendelni 2025-04-15 19:42:48 +02:00
ivanszabo 4dbda1aac3 User NFCCode is rögzítésre kerüljön 2025-04-15 19:42:39 +02:00
ivanszabo c51ee750f9 MobileUserDTO javítása 2025-04-15 18:38:16 +02:00
ivanszabo 50dcf3aff6 MobilUser lekérdezése 2025-04-15 15:13:08 +02:00
ivanszabo ae7257a3ff Auditok rendes implementálása 2025-04-15 10:17:19 +02:00
ivanszabo 9c179feeca Teljes log most jó 2025-04-15 08:50:13 +02:00
ivanszabo 380b6ac030 Különböző logok, különböző file-ba 2025-04-14 20:15:00 +02:00
ivanszabo ca71bd2194 Lezárt nem szerkeszthető már 2025-04-14 14:31:35 +02:00
ivanszabo b0a4da67d0 Lezáró az adatbázisba 2025-04-14 14:15:09 +02:00
ivanszabo 8dc902d2fb Lezárás oka a logba 2025-04-14 14:14:18 +02:00
ivanszabo 0811111865 Ellenőrzés lezárása 2025-04-14 14:11:57 +02:00
ivanszabo 29200ae418 Jelszó módosítása 2025-04-14 12:31:50 +02:00
ivanszabo 44e6719c3d Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-11 16:19:05 +02:00
ivanszabo 5c5a852ead Release +Version Backend 2025-04-11 16:18:58 +02:00
ivanszabo 70dd745889 Release + version 2025-04-11 16:18:23 +02:00
ivanszabo fad1398668 Csak a Web beállított léphet be 2025-04-11 10:56:51 +02:00
ivanszabo 7a757e84b2 Login továbbfejlesztése 2025-04-11 10:56:51 +02:00
ivanszabo 6d276e73b8 UI rendberakása 2025-04-11 10:55:40 +02:00
ivanszabo 9d107e8c0b Na most van kész a 2 faktoros authentikáció ! :) 2025-04-10 23:32:36 +02:00
ivanszabo aca0a86a6a Két faktor másik lába is kész. 2025-04-10 21:20:55 +02:00
ivanszabo d5a7895efa Kétfaktoros első része ok 2025-04-10 20:49:01 +02:00
ivanszabo 623a3c49b1 MailKit-tel
email küldése
2025-04-10 19:04:59 +02:00
ivanszabo 5356ef7424 Na most már jó lesz. 2025-04-10 16:29:36 +02:00
ivanszabo 1ea8e4fbe7 Verzió a láblécbe 2025-04-10 16:20:07 +02:00
ivanszabo 13b9d943b9 Na most menti a képet is a PDF-be 2025-04-10 16:18:33 +02:00
ivanszabo 06f5a5dd62 UserService Delete metódusai + controller 2025-04-10 14:07:20 +02:00
ivanszabo cd57fc46bc Felhasználó és szabály törlésének befejezése 2025-04-10 13:37:39 +02:00
ivanszabo 7109da0d95 Logger imolemetálása 2025-04-10 10:58:47 +02:00
ivanszabo 6137baff72 publishoz MOBILE 2025-04-10 08:51:04 +02:00
ivanszabo 621d61e08e Publishoz 2025-04-10 08:46:41 +02:00
ivanszabo 02cef1bf23 BUGFIX 2025-04-09 15:38:53 +02:00
ivanszabo e3ee93c74c UI BUGFIX 2025-04-09 15:37:30 +02:00
ivanszabo d383ccccbd Photo beküldésekor 2025-04-09 13:56:36 +02:00
ivanszabo 4eaffbcc4f DeviceMessage 2025-04-08 21:06:03 +02:00
ivanszabo a201e2028e JsonSerialize javítása 2025-04-08 21:05:12 +02:00
ivanszabo 7720f4944a Beküldés javítása 2025-04-08 17:50:47 +02:00
ivanszabo a394c643a2 Javítás 2025-04-08 17:46:22 +02:00
ivanszabo ac48e676df Na most jó a blokkolós cucc 2025-04-08 15:14:19 +02:00
ivanszabo d21ff69cc8 UI blokkolás, feloldás 2025-04-08 15:04:21 +02:00
ivanszabo b5d4a163fd Blokkolás, feloldás 2025-04-08 14:59:35 +02:00
ivanszabo cdaceb1961 Blokkolás, jóváhagyás, ilyesmi. 2025-04-08 14:59:05 +02:00
ivanszabo 2dbcbd1ed8 Mentés fölé csík 2025-04-08 07:42:25 +02:00
ivanszabo c8b8f6ae92 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-07 17:05:44 +02:00
ivanszabo b02fb58f2e Üzenetküldés frontenden 2025-04-07 17:05:40 +02:00
ivanszabo 85976547f6 Most működik az üzenetküldés Backenden 2025-04-07 17:05:27 +02:00
ivanszabo a3be387ee1 Még egy kis UI rendezés 2025-04-07 08:24:04 +02:00
ivanszabo e306139aec Egy kis UI rendezés 2025-04-07 07:57:10 +02:00
ivanszabo 2513765e51 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-06 19:34:29 +02:00
ivanszabo 3366884965 Program letöltés backend zsír!!! 2025-04-06 19:34:12 +02:00
ivanszabo a64304a05f Megy a program letöltése is... 2025-04-06 19:33:47 +02:00
ivanszabo 66744e0526 NFC azonosítás is kész 2025-04-06 14:42:34 +02:00
ivanszabo dc3e6e2f7b NFC azonosítás is beállítva 2025-04-06 14:41:36 +02:00
ivanszabo 71a5850d65 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-05 18:11:57 +02:00
ivanszabo 33232bae75 FÉLKÉSZ 2025-04-05 18:11:42 +02:00
ivanszabo 8dc13c702c DeviceMessages endpoint 2025-04-05 14:53:14 +02:00
ivanszabo 4951fc0c7a Kis tisztogatás, de fordul. 2025-04-05 12:50:57 +02:00
ivanszabo 429ccd2d70 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-05 11:31:16 +02:00
ivanszabo abc90dcec1 com.nuvolar.wfcapp beállítása 2025-04-05 11:31:09 +02:00
ivanszabo 476c9ead4c DisplayNameHelper kifejlesztése 2025-04-04 13:38:07 +02:00
ivanszabo 5b1f7fb642 Továbbfejlesztés 2025-04-04 12:42:47 +02:00
ivanszabo de8b95eda1 Alap töréls Web Locations működik. 2025-04-04 11:30:06 +02:00
ivanszabo fa48365d98 Egy kis lapozás ... 2025-04-03 17:07:12 +02:00
ivanszabo d5e11bc2e4 BaseService BL projektbe 2025-04-03 12:06:40 +02:00
ivanszabo a97c944f12 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-04-02 16:52:30 +02:00
ivanszabo 92c15072b8 Beküldés és mentés javítása 2025-04-02 16:52:25 +02:00
ivanszabo 001c59a669 LibreOffice-val dokumentum konvertálása PDF-re most jó 2025-04-02 16:51:11 +02:00
ivanszabo 90637b3848 PDF készítés DevExpressel. 2025-04-02 13:01:49 +02:00
ivanszabo 12bf69aadd Photo rendberakása + EF migráció 2025-04-02 10:32:27 +02:00
ivanszabo fe7b52efde Photo rendberakása 2025-04-02 10:32:27 +02:00
ivanszabo c7a3a608ba UI javítás + beküldés, képméretezés 2025-04-02 09:04:28 +02:00
ivanszabo c3fda85182 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-03-31 22:13:33 +02:00
ivanszabo ea305ebbf4 BUGFIXEK UI oldalon 2025-03-31 22:13:28 +02:00
ivanszabo 5207f32712 BUGFIX-ek 2025-03-31 22:13:17 +02:00
ivanszabo 61dd5bc9a1 Jó kis javítás, fejlesztés TESZT-hez 2025-03-31 19:31:22 +02:00
ivanszabo a7e913b3ee CheckStatus + UI fejlesztése 2025-03-31 15:20:16 +02:00
ivanszabo 7996f887ba IsEnabled a CheckPoint-hoz 2025-03-31 13:39:02 +02:00
ivanszabo 56f17681be RoleCheckPoint 2025-03-31 11:55:24 +02:00
ivanszabo d7c198acfa UI fejlesztés 2025-03-30 22:48:57 +02:00
ivanszabo 8566889cf9 swagger javítása 2025-03-29 09:12:55 +01:00
ivanszabo ce432e1ab0 Merge branch 'master' of https://tfs.nuvolar.hu:8443/tfs/AtomERP/_git/WorkFlowCheck 2025-03-28 20:51:04 +01:00
ivanszabo 146402a96a Snackbar meg ilyesmik 2025-03-28 20:51:00 +01:00
ivanszabo 66cf378556 SyncControl 2025-03-28 20:47:13 +01:00
ivanszabo d3bfeadc50 CheckListService extending 2025-03-28 19:25:35 +01:00
ivanszabo 77796f3247 CheckListRow edit 2025-03-28 17:35:29 +01:00
ivanszabo 728b6a8a9e Merge branch 'NFCTEST' 2025-03-28 15:37:49 +01:00
ivanszabo 148ea094ce UserRole javítása 2025-03-28 13:56:56 +01:00
ivanszabo ddc898cc2e RoleCheckListHeaderTemplate befejezése új/módosítás 2025-03-28 12:55:10 +01:00
ivanszabo f119b196ea RoleCheckListTemplateHeader lista nézet 2025-03-27 12:11:34 +01:00
ivanszabo 04cca012f4 WORD -> PDF 2025-03-27 11:13:42 +01:00
ivanszabo cb38e869a1 CheckListHeader TAB-osítva ... 2025-03-26 10:23:39 +01:00
ivanszabo 83980667d7 CheckListRow megjelenítése 2025-03-26 09:14:27 +01:00
ivanszabo ace4130f31 Entity javítás 2025-03-24 23:29:29 +01:00
459 changed files with 126772 additions and 99925 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 -341
View File
@@ -1,341 +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
*.pdf
/src/WorkFlowCheck.API/Pdf/c86f3a6a-c646-4627-823c-7e24134b7725.docx
/src/WorkFlowCheck.API/Downloads/APK/com.nuvolar.wfcapp-Signed.apk
/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,225 +1,463 @@
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("GetCheckListHeader/{id}")]
{ public async Task<ApiResponseDTO<CheckListHeaderDTO>> GetCheckListHeader(int id)
var retVal = new ApiResponseDTO<CheckListHeaderDTO>() {
{ var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
IsSuccess = true, {
}; IsSuccess = true,
var checkListHeaderDTO = await _checkListService.GetCheckListHeaderAsync(id); };
var checkListHeaderDTO = await _checkListService.GetCheckListHeaderAsync(id);
if (checkListHeaderDTO != null)
{ if (checkListHeaderDTO != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListHeaderDTO; retVal.IsSuccess = true;
} retVal.Data = checkListHeaderDTO;
else }
{ else
retVal.IsSuccess = false; {
retVal.Errors.Add("No data!"); retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
}
return retVal;
} return retVal;
[HttpGet("GetAllCheckListHeaders")] }
public async Task<ApiResponseDTO<List<CheckListHeaderDTO>>> GetAllCheckListHeadersAsync() [HttpPost("GetFilteredCheckListHeader")]
{ public async Task<ApiResponseListDTO<List<CheckListHeaderDTO>>> GetFilteredCheckListHeader([FromBody] DataTablesRequest dataTablesRequest)
var retVal = new ApiResponseDTO<List<CheckListHeaderDTO>>() {
{ var retVal = new ApiResponseListDTO<List<CheckListHeaderDTO>>()
IsSuccess = true, {
}; IsSuccess = true
var checkPointListDTO = await _checkListService.GetAllCheckListHeaderAsync(); };
if (checkPointListDTO != null) try
{ {
var result = await _checkListService.GetFilteredCheckListHeaderAsync(dataTablesRequest);
retVal.IsSuccess = true; retVal.Data = result.Data;
retVal.Data = checkPointListDTO; retVal.Total = result.Total;
} retVal.Filtered = result.Filtered;
else }
{ catch (Exception ex)
retVal.IsSuccess = false; {
retVal.Errors.Add("No data!"); retVal.IsSuccess = false;
} Log.Error(ex.Message);
}
return retVal; return retVal;
} }
[HttpPost("UpdateCheckListHeader")] [HttpGet("CreatePDF/{id}")]
public async Task<ApiResponseDTO<CheckListHeaderDTO>> UpdateCheckListHeader([FromBody] CheckListHeaderDTO checkListHeaderDTO) public async Task<ApiResponseDTO<byte[]>> CreatePDF(int id)
{ {
var retVal = new ApiResponseDTO<CheckListHeaderDTO>() var retVal = new ApiResponseDTO<byte[]>()
{ {
IsSuccess = true IsSuccess = true,
}; };
var checkListHeader = await _checkListService.GetCheckListHeaderAsync(id);
try var response = await _checkListService.CreateCheckListHeaderPDFAsync(id);
{
var result = await _checkListService.UpdateCheckListHeaderAsync(checkListHeaderDTO); if (response != null)
retVal.Data = result; {
} retVal.IsSuccess = true;
catch (Exception ex) retVal.Data = response;
{ }
retVal.IsSuccess = false; else
Log.Error(ex.Message); {
} retVal.IsSuccess = false;
return retVal; retVal.Errors.Add("No data!");
} }
[HttpPost("StartNewCheckList")]
public async Task<ApiResponseDTO<CheckListHeaderDTO>> StartNew([FromBody] CheckListHeaderNewDTO checkListHeaderNewDTO) return retVal;
{ }
var retVal = new ApiResponseDTO<CheckListHeaderDTO>() [HttpGet("GetAllCheckListHeaders/{mode}")]
{ public async Task<ApiResponseDTO<List<CheckListHeaderDTO>>> GetAllCheckListHeadersAsync(int mode = 0)
IsSuccess = true {
}; var retVal = new ApiResponseDTO<List<CheckListHeaderDTO>>()
{
try IsSuccess = true,
{ };
var response = await _checkListService.StartNewCheckListAsync(checkListHeaderNewDTO); var checkPointListDTO = await _checkListService.GetAllCheckListHeaderAsync(mode);
if (response != null)
{ if (checkPointListDTO != null)
retVal.Data = response; {
}
} retVal.IsSuccess = true;
catch (Exception ex) retVal.Data = checkPointListDTO;
{ }
else
Log.Error(ex.Message); {
} retVal.IsSuccess = false;
return retVal; retVal.Errors.Add("No data!");
} }
return retVal;
[HttpGet("GetCheckListTemplateHeader/{id}")] }
public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> GetCheckListTemplateHeader(int id) [HttpPost("UpdateCheckListHeader")]
{ public async Task<ApiResponseDTO<CheckListHeaderDTO>> UpdateCheckListHeader([FromBody] CheckListHeaderDTO checkListHeaderDTO)
var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>() {
{ var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
IsSuccess = true, {
}; IsSuccess = true
var CheckListTemplateHeaderDTO = await _checkListService.GetCheckListTemplateHeaderAsync(id); };
if (CheckListTemplateHeaderDTO != null) try
{ {
var result = await _checkListService.UpdateCheckListHeaderAsync(checkListHeaderDTO);
retVal.IsSuccess = true; retVal.Data = result;
retVal.Data = CheckListTemplateHeaderDTO;
} }
else catch (Exception ex)
{ {
retVal.IsSuccess = false; retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); Log.Error(ex.Message);
} }
return retVal;
return retVal; }
} [HttpPost("StartNewCheckList")]
[HttpGet("GetAllCheckListTemplateHeaders")] public async Task<ApiResponseDTO<CheckListHeaderDTO>> StartNew([FromBody] CheckListHeaderNewDTO checkListHeaderNewDTO)
public async Task<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>> GetAllCheckListTemplateHeadersAsync() {
{ var retVal = new ApiResponseDTO<CheckListHeaderDTO>()
var retVal = new ApiResponseDTO<List<CheckListTemplateHeaderDTO>>() {
{ IsSuccess = true
IsSuccess = true, };
};
var checkPointListDTO = await _checkListService.GetAllCheckListTemplateHeaderAsync(); try
{
if (checkPointListDTO != null) var response = await _checkListService.StartNewCheckListAsync(checkListHeaderNewDTO);
{ if (response != null)
{
retVal.IsSuccess = true; retVal.Data = response;
retVal.Data = checkPointListDTO; }
} }
else catch (Exception ex)
{ {
retVal.IsSuccess = false;
retVal.Errors.Add("No data!"); Log.Error(ex.Message);
} }
return retVal;
return retVal; }
} [HttpPost("CloseCheckListHeader")]
[HttpPost("UpdateCheckListTemplateHeader")] public async Task<ApiResponseDTO<bool>> CloseCheckListHeader([FromBody] CheckListHeaderCloseDTO checkListHeaderCloseDTO)
public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> UpdateCheckListTemplateHeader([FromBody] CheckListTemplateHeaderDTO CheckListTemplateHeaderDTO) {
{ var retVal = new ApiResponseDTO<bool>() { IsSuccess = false };
var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
{ try
IsSuccess = true {
}; var result = await _checkListService.CloseCheckListHeader(checkListHeaderCloseDTO);
retVal.Data = result;
try retVal.IsSuccess = result;
{
var result = await _checkListService.UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO); }
retVal.Data = result; catch (Exception ex)
{
} retVal.IsSuccess = false;
catch (Exception ex) Log.Error(ex.Message);
{ }
retVal.IsSuccess = false; return retVal;
Log.Error(ex.Message); }
}
return retVal; [HttpGet("AcceptCheckListHeader/{id}/{userId}")]
} public async Task<ApiResponseDTO<bool>> AcceptCheckListHeader(int id, int userId)
{
var retVal = new ApiResponseDTO<bool> { IsSuccess = false };
[HttpGet("GetCheckListTemplateRow/{id}")]
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> GetCheckListTemplateRow(int id) var response = await _checkListService.AcceptCheckListHeaderAsync(id, userId);
{
var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>() if (response)
{ {
IsSuccess = true, retVal.IsSuccess = true;
}; retVal.Data = response;
var checkListTemplateRowDTO = await _checkListService.GetCheckListTemplateRowAsync(id); }
else
if (checkListTemplateRowDTO != null) {
{ retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
retVal.IsSuccess = true; }
retVal.Data = checkListTemplateRowDTO;
} return retVal;
else }
{ [HttpGet("BlockCheckListHeader/{id}/{userId}")]
retVal.IsSuccess = false; public async Task<ApiResponseDTO<bool>> BlockCheckListHeader(int id, int userId)
retVal.Errors.Add("No data!"); {
} var retVal = new ApiResponseDTO<bool> { IsSuccess = false };
return retVal; var response = await _checkListService.BlockCheckListHeaderAsync(id, userId);
}
[HttpPost("UpdateCheckListTemplateRow")] if (response)
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> UpdateCheckListTemplateRow([FromBody] CheckListTemplateRowDTO CheckListTemplateRowDTO) {
{ retVal.IsSuccess = true;
var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>() retVal.Data = response;
{ }
IsSuccess = true else
}; {
retVal.IsSuccess = false;
try retVal.Errors.Add("No data!");
{ }
var result = await _checkListService.UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO);
retVal.Data = result; return retVal;
}
} [HttpGet("UnBlockCheckListHeader/{id}/{userId}")]
catch (Exception ex) public async Task<ApiResponseDTO<bool>> UnBlockCheckListHeader(int id, int userId)
{ {
retVal.IsSuccess = false; var retVal = new ApiResponseDTO<bool> { IsSuccess = false };
Log.Error(ex.Message);
} var response = await _checkListService.UnBlockCheckListHeaderAsync(id, userId);
return retVal;
} if (response)
} {
} retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("GetCheckListTemplateHeader/{id}")]
public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> GetCheckListTemplateHeader(int id)
{
var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
{
IsSuccess = true,
};
var CheckListTemplateHeaderDTO = await _checkListService.GetCheckListTemplateHeaderAsync(id);
if (CheckListTemplateHeaderDTO != null)
{
retVal.IsSuccess = true;
retVal.Data = CheckListTemplateHeaderDTO;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("GetAllCheckListTemplateHeaders")]
public async Task<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>> GetAllCheckListTemplateHeadersAsync()
{
var retVal = new ApiResponseDTO<List<CheckListTemplateHeaderDTO>>()
{
IsSuccess = true,
};
var checkPointListDTO = await _checkListService.GetAllCheckListTemplateHeaderAsync();
if (checkPointListDTO != null)
{
retVal.IsSuccess = true;
retVal.Data = checkPointListDTO;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpPost("UpdateCheckListTemplateHeader")]
public async Task<ApiResponseDTO<CheckListTemplateHeaderDTO>> UpdateCheckListTemplateHeader([FromBody] CheckListTemplateHeaderDTO CheckListTemplateHeaderDTO)
{
var retVal = new ApiResponseDTO<CheckListTemplateHeaderDTO>()
{
IsSuccess = true
};
try
{
var result = await _checkListService.UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO);
retVal.Data = result;
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("DeleteCheckListTemplateHeader/{id}")]
public async Task<ApiResponseDTO<bool>> DeleteCheckListTemplateHeader(int id)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true,
};
var result = await _checkListService.DeleteCheckListTemplateHeaderAsync(id);
if (result != null)
{
retVal.IsSuccess = true;
retVal.Data = result;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("CloneCheckListTemplateHeader/{id}")]
public async Task<ApiResponseDTO<bool>> CloneCheckListTemplateHeader(int id)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true,
};
var result = await _checkListService.CloneCheckListTemplateHeaderAsync(id);
if (result != null)
{
retVal.IsSuccess = true;
retVal.Data = result;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("GetCheckListTemplateRow/{id}")]
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> GetCheckListTemplateRow(int id)
{
var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>()
{
IsSuccess = true,
};
var checkListTemplateRowDTO = await _checkListService.GetCheckListTemplateRowAsync(id);
if (checkListTemplateRowDTO != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListTemplateRowDTO;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("DeleteCheckListTemplateRow/{id}")]
public async Task<ApiResponseDTO<bool>> DeleteCheckListTemplateRow(int id)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true,
};
var result = await _checkListService.DeleteCheckListTemplateRowAsync(id);
if (result != null)
{
retVal.IsSuccess = true;
retVal.Data = result;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpPost("UpdateCheckListTemplateRow")]
public async Task<ApiResponseDTO<CheckListTemplateRowDTO>> UpdateCheckListTemplateRow([FromBody] CheckListTemplateRowDTO CheckListTemplateRowDTO)
{
var retVal = new ApiResponseDTO<CheckListTemplateRowDTO>()
{
IsSuccess = true
};
try
{
var result = await _checkListService.UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO);
retVal.Data = result;
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetCheckListRow/{id}")]
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;
}
}
}
@@ -0,0 +1,83 @@
using Google.Apis.Auth.OAuth2;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Serilog;
using System.Net.Http.Headers;
using System.Text;
using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FCMController : ControllerBase
{
private readonly IMessageService _messageService;
public FCMController(IMessageService messageService)
{
_messageService = messageService;
}
[HttpPost("SendFCMMessage")]
public async Task<ApiResponseDTO<bool>> SendFCMMessage([FromBody] FCMMessageDTO fCMMessageDTO)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true
};
try
{
retVal.IsSuccess = await _messageService.SendFCMMessage(fCMMessageDTO);
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
[HttpPost("SendFCMMessageToLastToken")]
public async Task<ApiResponseDTO<bool>> SendFCMMessageToLastToken([FromBody] FCMMessageDTO fCMMessageDTO)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true
};
try
{
retVal.IsSuccess = await _messageService.SendFCMMessageToLastToken(fCMMessageDTO);
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
[HttpPost("SendFCMToken")]
public async Task<ApiResponseDTO<bool>> SendFCMToken([FromBody] FCMMessageDTO fCMMessageDTO)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true
};
try
{
await _messageService.SendFCMTokenAsync(fCMMessageDTO.Token);
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
}
}
@@ -1,302 +1,610 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Serilog; using Microsoft.IdentityModel.Tokens;
using WorkFlowCheck.BL.Services; using Serilog;
using WorkFlowCheck.BL.Services.Interfaces; using System.Text;
using WorkFlowCheck.Common.DTO; using WorkFlowCheck.BL.Services;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.API.Controllers using WorkFlowCheck.DL.Entities;
{
[Route("api/[controller]")] namespace WorkFlowCheck.API.Controllers
[ApiController] {
public class SyncController : ControllerBase [Route("api/[controller]")]
{ [ApiController]
private ISyncService _syncService; public class SyncController : ControllerBase
public SyncController(ISyncService syncService) {
{ private ISyncService _syncService;
_syncService = syncService; private INumberGeneratorService _numberGeneratorService;
} private IMessageService _messageService;
private IUserService _userService;
[HttpGet("GetCheckPoint/{id}")] public SyncController(ISyncService syncService,
public async Task<ApiResponseDTO<CheckPointDTO>> GetCheckpointAsync(int id) INumberGeneratorService numberGeneratorService,
{ IUserService userService,
var retVal = new ApiResponseDTO<CheckPointDTO>() IMessageService messageService)
{ {
IsSuccess = true, _syncService = syncService;
}; _numberGeneratorService = numberGeneratorService;
var checkPointListDTO = await _syncService.GetCheckPointAsync(id); _messageService = messageService;
_userService = userService;
if (checkPointListDTO != null) }
{
retVal.IsSuccess = true; [HttpGet("GetCheckPoint/{id}")]
retVal.Data = checkPointListDTO; public async Task<ApiResponseDTO<CheckPointDTO>> GetCheckpointAsync(int id)
} {
else var retVal = new ApiResponseDTO<CheckPointDTO>()
{ {
retVal.IsSuccess = false; IsSuccess = true,
retVal.Errors.Add("No data!"); };
} var checkPointDTO = await _syncService.GetCheckPointAsync(id);
return retVal; if (checkPointDTO != null)
} {
[HttpGet("GetAllCheckPoints")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<List<CheckPointDTO>>> GetAllCheckpointsAsync() retVal.Data = checkPointDTO;
{ }
var retVal = new ApiResponseDTO<List<CheckPointDTO>>() else
{ {
IsSuccess = true, retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
var checkPointListDTO = await _syncService.GetAllCheckPointAsync(); }
if (checkPointListDTO != null) return retVal;
{ }
[HttpGet("DeleteCheckPoint/{id}")]
retVal.IsSuccess = true; public async Task<ApiResponseDTO<bool>> DeleteCheckpointAsync(int id)
retVal.Data = checkPointListDTO; {
} var retVal = new ApiResponseDTO<bool>()
else {
{ IsSuccess = true,
retVal.IsSuccess = false; };
retVal.Errors.Add("No data!"); var response = await _syncService.DeleteCheckPointAsync(id);
}
if (response != null)
return retVal; {
}
[HttpPost("UpdateCheckPoint")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<CheckPointDTO>> UpdateCheckPoint([FromBody] CheckPointDTO checkPointDTO) retVal.Data = response;
{ }
var retVal = new ApiResponseDTO<CheckPointDTO>() else
{ {
IsSuccess = true retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
}
try
{ return retVal;
var result = await _syncService.UpdateCheckPointAsync(checkPointDTO); }
retVal.Data = result; [HttpGet("GetAllCheckPoints")]
public async Task<ApiResponseDTO<List<CheckPointDTO>>> GetAllCheckpointsAsync()
} {
catch (Exception ex) var retVal = new ApiResponseDTO<List<CheckPointDTO>>()
{ {
retVal.IsSuccess = false; IsSuccess = true,
Log.Error(ex.Message); };
} var checkPointListDTO = await _syncService.GetAllCheckPointAsync();
return retVal;
} if (checkPointListDTO != null)
[HttpPost("UpdateAllCheckPoint")] {
public async Task<ApiResponseDTO<List<CheckPointDTO>>> UpdateAllCheckPoint([FromBody] List<CheckPointDTO> checkPointListDTO)
{ retVal.IsSuccess = true;
var retVal = new ApiResponseDTO<List<CheckPointDTO>>() retVal.Data = checkPointListDTO;
{ }
IsSuccess = true else
}; {
retVal.IsSuccess = false;
try retVal.Errors.Add("No data!");
{ }
var result = await _syncService.UpdateAllCheckPointAsync(checkPointListDTO);
retVal.Data = result; return retVal;
} }
catch (Exception ex) [HttpPost("UpdateCheckPoint")]
{ public async Task<ApiResponseDTO<CheckPointDTO>> UpdateCheckPoint([FromBody] CheckPointDTO checkPointDTO)
retVal.IsSuccess = false; {
Log.Error(ex.Message); var retVal = new ApiResponseDTO<CheckPointDTO>()
} {
return retVal; IsSuccess = true
} };
try
[HttpGet("GetEquipment/{id}")] {
public async Task<ApiResponseDTO<EquipmentDTO>> GetEquipmentAsync(int id) var result = await _syncService.UpdateCheckPointAsync(checkPointDTO);
{ retVal.Data = result;
var retVal = new ApiResponseDTO<EquipmentDTO>()
{ }
IsSuccess = true, catch (Exception ex)
}; {
var equipmentDTO = await _syncService.GetEquipmentAsync(id); retVal.IsSuccess = false;
Log.Error(ex.Message);
if (equipmentDTO != null) }
{ return retVal;
}
retVal.IsSuccess = true; [HttpPost("UpdateAllCheckPoint")]
retVal.Data = equipmentDTO; public async Task<ApiResponseDTO<List<CheckPointDTO>>> UpdateAllCheckPoint([FromBody] List<CheckPointDTO> checkPointListDTO)
} {
else var retVal = new ApiResponseDTO<List<CheckPointDTO>>()
{ {
retVal.IsSuccess = false; IsSuccess = true
retVal.Errors.Add("No data!"); };
}
try
return retVal; {
} var result = await _syncService.UpdateAllCheckPointAsync(checkPointListDTO);
[HttpGet("GetAllEquipments")] retVal.Data = result;
public async Task<ApiResponseDTO<List<EquipmentDTO>>> GetAllEquipmentsAsync() }
{ catch (Exception ex)
var retVal = new ApiResponseDTO<List<EquipmentDTO>>() {
{ retVal.IsSuccess = false;
IsSuccess = true, Log.Error(ex.Message);
}; }
var equipmentListDTO = await _syncService.GetAllEquipmentAsync(); return retVal;
}
if (equipmentListDTO != null)
{
[HttpGet("GetEquipment/{id}")]
retVal.IsSuccess = true; public async Task<ApiResponseDTO<EquipmentDTO>> GetEquipmentAsync(int id)
retVal.Data = equipmentListDTO; {
} var retVal = new ApiResponseDTO<EquipmentDTO>()
else {
{ IsSuccess = true,
retVal.IsSuccess = false; };
retVal.Errors.Add("No data!"); var equipmentDTO = await _syncService.GetEquipmentAsync(id);
}
if (equipmentDTO != null)
return retVal; {
}
[HttpPost("UpdateEquipment")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<EquipmentDTO>> UpdateEquipment([FromBody] EquipmentDTO EquipmentDTO) retVal.Data = equipmentDTO;
{ }
var retVal = new ApiResponseDTO<EquipmentDTO>() else
{ {
IsSuccess = true retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
}
try
{ return retVal;
var result = await _syncService.UpdateEquipmentAsync(EquipmentDTO); }
retVal.Data = result; [HttpGet("DeleteEquipment/{id}")]
public async Task<ApiResponseDTO<bool>> DeleteEquipmentAsync(int id)
} {
catch (Exception ex) var retVal = new ApiResponseDTO<bool>()
{ {
retVal.IsSuccess = false; IsSuccess = true,
Log.Error(ex.Message); };
} var response = await _syncService.DeleteEquipmentAsync(id);
return retVal;
} if (response != null)
{
[HttpGet("GetLocation/{id}")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<LocationDTO>> GetLocationAsync(int id) retVal.Data = response;
{ }
var retVal = new ApiResponseDTO<LocationDTO>() else
{ {
IsSuccess = true, retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
var locationDTO = await _syncService.GetLocationAsync(id); }
if (locationDTO != null) return retVal;
{ }
[HttpGet("GetAllEquipments")]
retVal.IsSuccess = true; public async Task<ApiResponseDTO<List<EquipmentDTO>>> GetAllEquipmentsAsync()
retVal.Data = locationDTO; {
} var retVal = new ApiResponseDTO<List<EquipmentDTO>>()
else {
{ IsSuccess = true,
retVal.IsSuccess = false; };
retVal.Errors.Add("No data!"); var equipmentListDTO = await _syncService.GetAllEquipmentAsync();
}
if (equipmentListDTO != null)
return retVal; {
}
[HttpGet("GetAllLocations")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<List<LocationDTO>>> GetAllLocationsAsync() retVal.Data = equipmentListDTO;
{ }
var retVal = new ApiResponseDTO<List<LocationDTO>>() else
{ {
IsSuccess = true, retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
var locationListDTO = await _syncService.GetAllLocationAsync(); }
if (locationListDTO != null) return retVal;
{ }
[HttpPost("UpdateEquipment")]
retVal.IsSuccess = true; public async Task<ApiResponseDTO<EquipmentDTO>> UpdateEquipment([FromBody] EquipmentDTO EquipmentDTO)
retVal.Data = locationListDTO; {
} var retVal = new ApiResponseDTO<EquipmentDTO>()
else {
{ IsSuccess = true
retVal.IsSuccess = false; };
retVal.Errors.Add("No data!");
} try
{
return retVal; var result = await _syncService.UpdateEquipmentAsync(EquipmentDTO);
} retVal.Data = result;
[HttpPost("UpdateLocation")]
public async Task<ApiResponseDTO<LocationDTO>> UpdateLocation([FromBody] LocationDTO LocationDTO) }
{ catch (Exception ex)
var retVal = new ApiResponseDTO<LocationDTO>() {
{ retVal.IsSuccess = false;
IsSuccess = true Log.Error(ex.Message);
}; }
return retVal;
try }
{
var result = await _syncService.UpdateLocationAsync(LocationDTO);
retVal.Data = result; [HttpGet("GetLocation/{id}")]
public async Task<ApiResponseDTO<LocationDTO>> GetLocationAsync(int id)
} {
catch (Exception ex) var retVal = new ApiResponseDTO<LocationDTO>()
{ {
retVal.IsSuccess = false; IsSuccess = true,
Log.Error(ex.Message); };
} var locationDTO = await _syncService.GetLocationAsync(id);
return retVal;
} if (locationDTO != null)
{
[HttpGet("GetAllCheckListTemplateHeader/{userId}")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>> GetAllCheckListTemplateHeaderAsync(int userId) retVal.Data = locationDTO;
{ }
var retVal = new ApiResponseDTO<List<CheckListTemplateHeaderDTO>>() else
{ {
IsSuccess = true, retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
var response = await _syncService.GetAllCheckListTemplateAsync(userId); }
if (response != null) return retVal;
{ }
[HttpGet("DeleteLocation/{id}")]
retVal.IsSuccess = true; public async Task<ApiResponseDTO<bool>> DeleteLocationAsync(int id)
retVal.Data = response; {
} var retVal = new ApiResponseDTO<bool>()
else {
{ IsSuccess = true,
retVal.IsSuccess = false; };
retVal.Errors.Add("No data!"); var response = await _syncService.DeleteLocationAsync(id);
}
if (response != null)
return retVal; {
}
[HttpGet("GetAllCheckListHeader/{userId}")] retVal.IsSuccess = true;
public async Task<ApiResponseDTO<List<CheckListHeaderDTO>>> GetAllCheckListHeaderAsync(int userId) retVal.Data = response;
{ }
var retVal = new ApiResponseDTO<List<CheckListHeaderDTO>>() else
{ {
IsSuccess = true, retVal.IsSuccess = false;
}; retVal.Errors.Add("No data!");
var response = await _syncService.GetAllCheckListAsync(userId); }
if (response != null) return retVal;
{ }
[HttpGet("GetAllLocations")]
retVal.IsSuccess = true; public async Task<ApiResponseDTO<List<LocationDTO>>> GetAllLocationsAsync()
retVal.Data = response; {
} var retVal = new ApiResponseDTO<List<LocationDTO>>()
else {
{ IsSuccess = true,
retVal.IsSuccess = false; };
retVal.Errors.Add("No data!"); var locationListDTO = await _syncService.GetAllLocationAsync();
}
if (locationListDTO != null)
return retVal; {
}
retVal.IsSuccess = true;
retVal.Data = locationListDTO;
}
else
{
retVal.IsSuccess = false;
} retVal.Errors.Add("No data!");
} }
return retVal;
}
[HttpPost("UpdateLocation")]
public async Task<ApiResponseDTO<LocationDTO>> UpdateLocation([FromBody] LocationDTO LocationDTO)
{
var retVal = new ApiResponseDTO<LocationDTO>()
{
IsSuccess = true
};
try
{
var result = await _syncService.UpdateLocationAsync(LocationDTO);
retVal.Data = result;
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetAllCheckListTemplateHeader/{userId}")]
public async Task<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>> GetAllCheckListTemplateHeaderAsync(int userId)
{
var retVal = new ApiResponseDTO<List<CheckListTemplateHeaderDTO>>()
{
IsSuccess = true,
};
var response = await _syncService.GetAllCheckListTemplateAsync(userId);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("GetAllCheckListHeader/{userId}")]
public async Task<ApiResponseDTO<List<CheckListHeaderDTO>>> GetAllCheckListHeaderAsync(int userId)
{
var retVal = new ApiResponseDTO<List<CheckListHeaderDTO>>()
{
IsSuccess = true,
};
var response = await _syncService.GetAllCheckListAsync(userId);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpPost("SendCheckListHeader")]
public async Task<ApiResponseDTO<string>> SendCheckListHeader([FromBody] CheckListHeaderDTO checkListHeaderDTO)
{
var retVal = new ApiResponseDTO<string>()
{
IsSuccess = true
};
try
{
var result = await _syncService.SendCheckListHeaderAsync(checkListHeaderDTO);
retVal.Data = "Sikeres beküldés!";
}
catch (Exception ex)
{
retVal.IsSuccess = false;
retVal.Errors.Add(ex.Message);
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetAllNumbergenerators")]
public async Task<ApiResponseDTO<List<NumberGeneratorTemplateDTO>>> GetAllNumbergeneratorsAsync()
{
var retVal = new ApiResponseDTO<List<NumberGeneratorTemplateDTO>>()
{
IsSuccess = true,
};
var locationListDTO = await _numberGeneratorService.GetAllNumbergeneratorsAsync();
if (locationListDTO != null)
{
retVal.IsSuccess = true;
retVal.Data = locationListDTO;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpPost("DeviceMessageSend")]
public async Task<ApiResponseDTO<bool>> DeviceMessageSend([FromBody] DeviceMessageDTO deviceMessageDTO)
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true
};
try
{
var result = await _syncService.DeviceMessageSend(deviceMessageDTO);
retVal.Data = true;
}
catch (Exception ex)
{
retVal.IsSuccess = false;
retVal.Errors.Add(ex.Message);
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("DeviceMessageReadUnreaded/{deviceIdBase64}")]
public async Task<ApiResponseDTO<List<DeviceMessageDTO>>> DeviceMessageReadUnreaded(string deviceIdBase64)
{
var retVal = new ApiResponseDTO<List<DeviceMessageDTO>>()
{
IsSuccess = true,
};
byte[] byteArray = Base64UrlEncoder.DecodeBytes(deviceIdBase64);
string deviceId = Encoding.UTF8.GetString(byteArray);
var response = await _syncService.DeviceMessageReadUnreaded(deviceId);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("DeviceMessageReadUnreadedRole/{roleId}")]
public async Task<ApiResponseDTO<List<DeviceMessageDTO>>> DeviceMessageReadUnreadedRole(int roleId)
{
var retVal = new ApiResponseDTO<List<DeviceMessageDTO>>()
{
IsSuccess = true,
};
var response = await _syncService.DeviceMessageReadUnreadedRole(roleId);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("Download")]
public async Task<IActionResult> DownloadAPKFileAsync()
{
try
{
string fileName = "com.nuvolar.wfcapp-Signed.apk";
string downloadFolder = Path.Combine(Directory.GetCurrentDirectory(), "Downloads", "APK");
string filePath = Path.Combine(downloadFolder, fileName);
if (!System.IO.File.Exists(filePath))
{
return NotFound("File not found.");
}
var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);
var fileType = "application/octet-stream";
Response.Headers.Add("Content-Length", fileBytes.Length.ToString());
return File(fileBytes, fileType, fileName);
}
catch (Exception ex)
{
return StatusCode(500, $"Error: {ex.Message}");
}
}
[HttpGet("SendTestMail")]
public async Task<ApiResponseDTO<bool>> SendTestMail()
{
var retVal = new ApiResponseDTO<bool>()
{
IsSuccess = true
};
try
{
var result = await _messageService.SendMailAsync(
new List<string>()
{
"ivan.szabo.sis@gmail.com",
}, "Teszt", "Ok");
retVal.Data = true;
}
catch (Exception ex)
{
retVal.IsSuccess = false;
retVal.Errors.Add(ex.Message);
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetAllMobileUsers")]
public async Task<ApiResponseDTO<List<MobileUserDTO>>> GetAllMobileUsers()
{
var retVal = new ApiResponseDTO<List<MobileUserDTO>>()
{
IsSuccess = true,
Data = new List<MobileUserDTO>()
};
var usersListDTO = await _userService.GetAllUserAsync();
retVal.Data.AddRange(usersListDTO
.Where(user => user.RoleDTO.Any(role => role.CanUseMobilApp))
.Select(user => new MobileUserDTO
{
Id = user.Id,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
NFCActive = user.NFCActive,
NFCCode = user.NFCCode,
UserName = user.UserName
})
);
if (retVal.Data == null || retVal.Data.Count <= 0) { retVal.IsSuccess = false; retVal.Errors.Add("No data!"); }
return retVal;
}
[HttpPost("UpdateAllMobileUser")]
public async Task<ApiResponseDTO<List<MobileUserDTO>>> UpdateAllMobileUser([FromBody] List<MobileUserDTO> mobileUserListDTO)
{
var retVal = new ApiResponseDTO<List<MobileUserDTO>>()
{
IsSuccess = true
};
try
{
foreach (var mobileUserDTO in mobileUserListDTO)
{
var userDTO = await _userService.GetUserAsync(mobileUserDTO.Id);
if (userDTO != null && userDTO.Id == mobileUserDTO.Id)
{
userDTO.NFCCode = mobileUserDTO.NFCCode;
var result = await _userService.UpdateUserAsync(userDTO);
}
}
}
catch (Exception ex)
{
retVal.IsSuccess = false;
Log.Error(ex.Message);
}
return retVal;
}
}
}
@@ -0,0 +1,399 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SystemController : ControllerBase
{
private readonly ISystemService _systemService;
public SystemController(ISystemService systemService)
{
_systemService = systemService;
}
[HttpGet("GetDatabaseAndVersionInfo")]
public async Task<ApiResponseDTO<string>> GetDatabaseAndVersionInfo()
{
var retVal = new ApiResponseDTO<string>()
{
IsSuccess = true,
};
var result = await _systemService.GetDatabaseAndVersionInfoAsync();
if (result != null)
{
retVal.IsSuccess = true;
retVal.Data = result;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("GetAllImageFiles")]
public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllImageFilesAsync()
{
var retVal = new ApiResponseDTO<List<ImageFileDTO>>()
{
IsSuccess = true,
};
try
{
var allowedExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".tiff" };
var imageFolder = Path.Combine(Directory.GetCurrentDirectory(), "Images");
var files = Directory.GetFiles(imageFolder)
.Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLower()))
.Select(f =>
{
var fileInfo = new FileInfo(f);
return new
{
FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
};
});
var checkListFileInfos = new List<ImageFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList())
{
var checkListFileInfoDTO = new ImageFileDTO()
{
FileName = file.FileName,
FileSize = file.FileSize,
CreateDate = file.CreatedDate,
};
checkListFileInfos.Add(checkListFileInfoDTO);
}
if (checkListFileInfos != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListFileInfos;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetAllPDFFiles")]
public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllPDFilesAsync()
{
var retVal = new ApiResponseDTO<List<ImageFileDTO>>()
{
IsSuccess = true,
};
try
{
var pdfFolder = Path.Combine(Directory.GetCurrentDirectory(), "PDF");
var files = Directory.GetFiles(pdfFolder, "*.pdf")
.Select(f =>
{
var fileInfo = new FileInfo(f);
return new
{
FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
};
});
var checkListFileInfos = new List<ImageFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList())
{
var checkListFileInfoDTO = new ImageFileDTO()
{
FileName = file.FileName,
FileSize = file.FileSize,
CreateDate = file.CreatedDate,
};
checkListFileInfos.Add(checkListFileInfoDTO);
}
if (checkListFileInfos != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListFileInfos;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetAllLogAuditFiles")]
public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogAuditFilesAsync()
{
var retVal = new ApiResponseDTO<List<LogFileDTO>>()
{
IsSuccess = true,
};
try
{
var logAuditFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow");
var files = Directory.GetFiles(logAuditFiles, "*.log")
.Select(f =>
{
var fileInfo = new FileInfo(f);
return new
{
FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
};
});
var checkListFileInfos = new List<LogFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList())
{
var checkListFileInfoDTO = new LogFileDTO()
{
FileName = file.FileName,
FileSize = file.FileSize,
CreateDate = file.CreatedDate,
};
checkListFileInfos.Add(checkListFileInfoDTO);
}
if (checkListFileInfos != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListFileInfos;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("GetAllLogBusinessFiles")]
public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogBusinessFilesAsync()
{
var retVal = new ApiResponseDTO<List<LogFileDTO>>()
{
IsSuccess = true,
};
try
{
var logBusinessFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow");
var files = Directory.GetFiles(logBusinessFiles, "*.log")
.Select(f =>
{
var fileInfo = new FileInfo(f);
return new
{
FileName = fileInfo.Name,
FileSize = FormatFileSize(fileInfo.Length),
CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
};
});
var checkListFileInfos = new List<LogFileDTO>();
foreach (var file in files.OrderBy(o => o.FileName).ToList())
{
var checkListFileInfoDTO = new LogFileDTO()
{
FileName = file.FileName,
FileSize = file.FileSize,
CreateDate = file.CreatedDate,
};
checkListFileInfos.Add(checkListFileInfoDTO);
}
if (checkListFileInfos != null)
{
retVal.IsSuccess = true;
retVal.Data = checkListFileInfos;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
[HttpGet("DownloadFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadFile(string filename)
{
var retVal = new ApiResponseDTO<byte[]>()
{
IsSuccess = false,
};
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Images", filename);
if (!System.IO.File.Exists(imageFile))
{
retVal.Errors.Add($"{filename} does not exist");
return retVal;
}
byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("DownloadPDFFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadPDFFile(string filename)
{
var retVal = new ApiResponseDTO<byte[]>()
{
IsSuccess = false,
};
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "PDF", filename);
if (!System.IO.File.Exists(imageFile))
{
retVal.Errors.Add($"{filename} does not exist");
return retVal;
}
byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("DownloadAuditLogFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadAuditLogFile(string filename)
{
var retVal = new ApiResponseDTO<byte[]>()
{
IsSuccess = false,
};
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow", filename);
if (!System.IO.File.Exists(imageFile))
{
retVal.Errors.Add($"{filename} does not exist");
return retVal;
}
byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
[HttpGet("DownloadBusinessLogFile/{filename}")]
public async Task<ApiResponseDTO<byte[]>> DownloadBusinessLogFile(string filename)
{
var retVal = new ApiResponseDTO<byte[]>()
{
IsSuccess = false,
};
var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow", filename);
if (!System.IO.File.Exists(imageFile))
{
retVal.Errors.Add($"{filename} does not exist");
return retVal;
}
byte[] response = System.IO.File.ReadAllBytes(imageFile);
if (response != null)
{
retVal.IsSuccess = true;
retVal.Data = response;
}
else
{
retVal.IsSuccess = false;
retVal.Errors.Add("No data!");
}
return retVal;
}
private string FormatFileSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len /= 1024;
}
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;
} }
} }
} }
} }
Binary file not shown.
+177 -117
View File
@@ -1,117 +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;
var builder = WebApplication.CreateBuilder(args);
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration) //------------------------------------------------------------------------------------------------------------------
.CreateLogger(); string baseLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs");
if (!Directory.Exists(baseLogPath))
builder.Services.AddAutoMapper(typeof(MapperProfile)); Directory.CreateDirectory(baseLogPath);
builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor(); string auditLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "AuditFlow");
builder.Services.AddScoped<IRequestContext, HttpRequestContext>(); if (!Directory.Exists(auditLogPath))
Directory.CreateDirectory(auditLogPath);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options => string businessLogPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs", "BusinessFlow");
options.UseSqlServer(connectionString, x => x.MigrationsAssembly("WorkFlowCheck.DL"))); if (!Directory.Exists(businessLogPath))
//DI Directory.CreateDirectory(businessLogPath);
DIConfig.DIInit(builder.Services); Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration) // Konfiguráció betöltése
// SWAGGER !!! .WriteTo.Console()
builder.Services.AddEndpointsApiExplorer(); .WriteTo.File("logs/log-.log", rollingInterval: RollingInterval.Day)
builder.Services.AddSwaggerGen(c => .WriteTo.Logger(lc => lc
{ .Filter.ByIncludingOnly(Matching.WithProperty("TAG", "AuditFlow"))
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WorkFlowCheck API", Version = "v1" }); .WriteTo.File("Logs/AuditFlow/au-.log", rollingInterval: RollingInterval.Day)
)
// API Key Auth definíció .WriteTo.Logger(lc => lc
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme .Filter.ByIncludingOnly(Matching.WithProperty("TAG", "BusinessFlow"))
{ .WriteTo.File("Logs/BusinessFlow/bs-.log", rollingInterval: RollingInterval.Day)
Description = "API Key szükséges. Használat: 'ApiKey: {kulcs}'", )
Name = "X-Api-Key", // A fejlécek között keresendõ .CreateLogger();
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "ApiKey" //------------------------------------------------------------------------------------------------------------------
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement Log.ForContext("TAG", "BusinessFlow").Information("API indítása...");
{
{ builder.Services.AddAutoMapper(typeof(MapperProfile));
new OpenApiSecurityScheme builder.Services.AddMemoryCache();
{ builder.Services.AddHttpContextAccessor();
Reference = new OpenApiReference builder.Services.AddScoped<IRequestContext, HttpRequestContext>();
{
Type = ReferenceType.SecurityScheme, var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
Id = "ApiKey" builder.Services.AddDbContext<AppDbContext>(options =>
}, options.UseSqlServer(connectionString, x => x.MigrationsAssembly("WorkFlowCheck.DL")));
Scheme = "ApiKey", //DI
Name = "ApiKey",
In = ParameterLocation.Header, DIConfig.DIInit(builder.Services);
},
Array.Empty<string>() // SWAGGER !!!
} builder.Services.AddEndpointsApiExplorer();
}); builder.Services.AddSwaggerGen(c =>
}); {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WorkFlowCheck API", Version = "v1" });
builder.Host.UseSerilog();
// API Key Auth definíció
builder.Services.AddControllers() c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
.AddNewtonsoftJson(options => {
{ Description = "API Key szükséges. Használat: 'ApiKey: {kulcs}'",
// Itt konfigurálhatod az egyedi beállításokat Name = "X-Api-Key", // A fejlécek között keresendõ
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; In = ParameterLocation.Header,
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; Type = SecuritySchemeType.ApiKey,
}); Scheme = "ApiKey"
});
builder.Services.AddCors(options =>
{ c.AddSecurityRequirement(new OpenApiSecurityRequirement
options.AddDefaultPolicy(policy => {
{ {
policy.WithOrigins("*").AllowAnyMethod().AllowAnyHeader(); new OpenApiSecurityScheme
}); {
}); Reference = new OpenApiReference
{
var app = builder.Build(); Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
},
Scheme = "ApiKey",
using (var scope = app.Services.CreateScope()) Name = "ApiKey",
{ In = ParameterLocation.Header,
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>(); },
DBInitializer.Seed(context); Array.Empty<string>()
} }
});
// Swagger middleware });
if (app.Environment.IsDevelopment())
{ builder.Host.UseSerilog();
app.UseSwagger();
app.UseSwaggerUI(c => builder.Services.AddControllers()
{ .AddNewtonsoftJson(options =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkFlowCheck API v1"); {
}); // Itt konfigurálhatod az egyedi beállításokat
} options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// Routing és endpointok });
//app.UseHttpsRedirection();
app.UseRouting(); builder.Services.AddCors(options =>
{
app.UseMiddleware<ApiKeyMiddleware>(); options.AddDefaultPolicy(policy =>
app.UseMiddleware<JwtMiddleware>(); {
policy.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
app.MapControllers(); });
app.UseAuthorization(); });
app.UseCors();
app.Run(); builder.WebHost.ConfigureKestrel(options =>
{
var kestrelConfig = builder.Configuration.GetSection("Kestrel");
options.Configure(kestrelConfig);
});
var app = builder.Build();
//----------------- Munkakönyvtárak létrehozása -----------------------------
string imageDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Images");
if (!Directory.Exists(imageDirectory))
{
Directory.CreateDirectory(imageDirectory);
}
string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf");
// Ensure the Images directory exists
if (!Directory.Exists(pdfDirectory))
{
Directory.CreateDirectory(pdfDirectory);
}
string downloadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Downloads");
if (!Directory.Exists(downloadDirectory))
{
Directory.CreateDirectory(downloadDirectory);
}
string downloadAPKDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Downloads","APK");
if (!Directory.Exists(downloadAPKDirectory))
{
Directory.CreateDirectory(downloadAPKDirectory);
}
//---------------------------------------------------------------------------
using (var scope = app.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
DBInitializer.Seed(context);
}
// Swagger middleware
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkFlowCheck API v1");
});
}
// Routing és endpointok
//app.UseHttpsRedirection();
app.UseRouting();
app.UseMiddleware<ApiKeyMiddleware>();
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
app.UseAuthorization();
app.UseCors();
Log.ForContext("TAG", "BusinessFlow").Information("API fut.");
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 -38
View File
@@ -1,38 +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="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" /> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.12"> <PackageReference Include="Google.Apis.Auth" Version="1.69.0" />
<PrivateAssets>all</PrivateAssets> <PackageReference Include="MailKit" Version="4.11.0" />
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" />
</PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.12">
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PrivateAssets>all</PrivateAssets>
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" /> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" /> </PackageReference>
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" /> <PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
</ItemGroup> <PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<ItemGroup> <PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<None Update="Certs\SwaggerCert.pfx"> <PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
</None> <PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup> </ItemGroup>
</Project> <ItemGroup>
<None Update="Certs\SwaggerCert.pfx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Pdf\CheckList_Template_V1.docx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.Development.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
</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,8 +1,20 @@
{ {
"Logging": { "ConnectionStrings": {
"LogLevel": { //"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"
"Default": "Information", //"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",
"Microsoft.AspNetCore": "Warning" "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": {
} "LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:59027"
}
}
}
}
+74 -34
View File
@@ -1,34 +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": 30 "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": "File", "Name": "Logger",
"Args": { "Args": {
"path": "logs/log-.log", "filter": "Equals(TAG, 'AuditFlow')",
"rollingInterval": "Day" "writeTo": [
} {
} "Name": "File",
] "Args": {
}, "path": "Logs/AuditFlow/log-.txt",
"AllowedHosts": "*" "rollingInterval": "Day",
} "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
},
{
"Name": "Logger",
"Args": {
"filter": "Equals(TAG, 'BusinessFlow')",
"writeTo": [
{
"Name": "File",
"Args": {
"path": "Logs/BusinessFlow/log-.txt",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
}
],
"Enrich": [ "FromLogContext" ]
},
"AllowedHosts": "*",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:8660"
}
}
},
"EmailSettings": {
"SmtpServer": "smtp.gmail.com",
"SmtpPort": 587,
"Username": "nuvolarsetup@gmail.com",
"Password": "reiq pgfr nxub pvrb",
"SenderName": "Nuvolar System"
}
}
@@ -0,0 +1,13 @@
{
"type": "service_account",
"project_id": "com-nuvolar-wfcapp",
"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",
"client_email": "firebase-adminsdk-fbsvc@com-nuvolar-wfcapp.iam.gserviceaccount.com",
"client_id": "109975038898567298706",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"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",
"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
@@ -0,0 +1,225 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics;
namespace WorkFlowCheck.BL.DocumentGenerator
{
public class DokumentumGenerator
{
public static byte[] DocxToPdfL(byte[] wordBytes, List<string> imagePaths = null)
{
string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf");
string fileName = Guid.NewGuid().ToString();
string tempWordPath = Path.Combine(pdfDirectory, fileName + ".docx");
string tempPdfPath = Path.Combine(pdfDirectory, fileName + ".pdf");
try
{
// Word fájl mentése ideiglenes fájlba
File.WriteAllBytes(tempWordPath, wordBytes);
if (imagePaths != null && imagePaths.Count > 0)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(tempWordPath, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
foreach (string imagePath in imagePaths)
{
if (File.Exists(imagePath))
{
InsertImageAsNewPage(mainPart, imagePath);
}
}
wordDoc.MainDocumentPart.Document.Save();
}
}
// LibreOffice parancssori konverzió
ProcessStartInfo startInfo = new ProcessStartInfo
{
#if !DEBUG
FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs
#else
//FileName = "c:\\Program Files\\LibreOffice\\program\\soffice", // LibreOffice parancs
FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs
#endif
Arguments = $"--headless --convert-to pdf \"{tempWordPath}\" --outdir \"{pdfDirectory}",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process process = Process.Start(startInfo))
{
process.WaitForExit();
}
// Ellenőrzés, hogy létrejött-e a PDF
if (File.Exists(tempPdfPath))
{
byte[] pdfBytes = File.ReadAllBytes(tempPdfPath);
// Ideiglenes fájlok törlése
File.Delete(tempWordPath);
File.Delete(tempPdfPath);
return pdfBytes;
}
else
{
throw new Exception("PDF konverzió sikertelen.");
}
}
catch (Exception ex)
{
Console.WriteLine("Hiba a PDF konverzió során: " + ex.Message);
return null;
}
}
private static void InsertImageAsNewPage(MainDocumentPart mainPart, string imagePath)
{
string fileName = Path.GetFileName(imagePath);
// 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);
int pixelWidth = image.Width;
int pixelHeight = image.Height;
long maxWidth = 5760000L; // kb. 16 cm
long maxHeight = 7200000L; // kb. 20 cm
double aspectRatio = (double)pixelHeight / pixelWidth;
long finalWidth = maxWidth;
long finalHeight = (long)(maxWidth * aspectRatio);
if (finalHeight > maxHeight)
{
finalHeight = maxHeight;
finalWidth = (long)(maxHeight / aspectRatio);
}
// Kép hozzáadása Word dokumentumhoz
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(imagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
string imagePartId = mainPart.GetIdOfPart(imagePart);
Drawing drawing = CreateImageDrawing(imagePartId, finalWidth, finalHeight);
// Kép beillesztése középre igazítva
Paragraph imageParagraph = new Paragraph(new Run(drawing))
{
ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Center }
)
};
TableCell imageCell = new TableCell(imageParagraph,
new TableCellProperties(
new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center },
new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" }
));
// Képes sor (magas, kitölti az oldalt)
TableRow imageRow = new TableRow(imageCell);
imageRow.AppendChild(new TableRowProperties(
new TableRowHeight() { Val = 9000, HeightType = HeightRuleValues.Exact }
));
// Fájlnév beillesztése középre
Paragraph fileNamePara = new Paragraph(new Run(new Text(fileName)))
{
ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Center }
)
};
TableCell fileNameCell = new TableCell(fileNamePara,
new TableCellProperties(
new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center },
new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" }
));
// Fájlnév sor (normál magasság)
TableRow fileNameRow = new TableRow(fileNameCell);
fileNameRow.AppendChild(new TableRowProperties(
new TableRowHeight() { Val = 400, HeightType = HeightRuleValues.Auto }
));
// Táblázat – szegély nélkül, teljes oldalszélességben
Table table = new Table(
new TableProperties(
new TableWidth { Width = "10000", Type = TableWidthUnitValues.Pct },
new TableBorders(
new TopBorder { Val = BorderValues.None },
new BottomBorder { Val = BorderValues.None },
new LeftBorder { Val = BorderValues.None },
new RightBorder { Val = BorderValues.None },
new InsideHorizontalBorder { Val = BorderValues.None },
new InsideVerticalBorder { Val = BorderValues.None }
)
),
imageRow,
fileNameRow
);
// Új oldal és a táblázat beszúrása a dokumentum végére
Body body = mainPart.Document.Body;
body.Append(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
body.Append(table);
}
private static Drawing CreateImageDrawing(string relationshipId, long width, long height)
{
return new Drawing(
new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline(
new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = width, Cy = height },
new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Inserted Image"
},
new DocumentFormat.OpenXml.Drawing.Graphic(
new DocumentFormat.OpenXml.Drawing.GraphicData(
new DocumentFormat.OpenXml.Drawing.Pictures.Picture(
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureProperties(
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "Picture"
},
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureDrawingProperties()),
new DocumentFormat.OpenXml.Drawing.Pictures.BlipFill(
new DocumentFormat.OpenXml.Drawing.Blip()
{
Embed = relationshipId
},
new DocumentFormat.OpenXml.Drawing.Stretch(
new DocumentFormat.OpenXml.Drawing.FillRectangle())),
new DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties(
new DocumentFormat.OpenXml.Drawing.Transform2D(
new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L },
new DocumentFormat.OpenXml.Drawing.Extents() { Cx = width, Cy = height }),
new DocumentFormat.OpenXml.Drawing.PresetGeometry(
new DocumentFormat.OpenXml.Drawing.AdjustValueList())
{ Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle }))
)
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{ DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U });
}
}
}
@@ -0,0 +1,576 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Text.RegularExpressions;
namespace WorkFlowCheck.BL.DocumentGenerator
{
public class SablonGenerator : IDisposable
{
private readonly List<OpenXmlElement> _currentRoot;
private MemoryStream Mem { get; }
private WordprocessingDocument Doc { get; set; }
private List<OpenXmlElement> CurrentRoot => Repeater?.SablonRoot ?? _currentRoot;
private SubSablon Repeater { get; set; }
protected class SubSablon : IDisposable
{
private List<OpenXmlElement> SablonRootBase { get; set; }
protected internal List<OpenXmlElement> SablonRoot { get; private set; }
public BookmarkStart BookmarkStart { get; }
public BookmarkEnd BookmarkEnd { get; }
protected internal SubSablon(WordprocessingDocument doc, string key)
{
var bookmark = doc.MainDocumentPart.RootElement.Descendants<BookmarkStart>()
.FirstOrDefault(x => x.Name == key);
//var parentBookmark = false;
if (bookmark != null)
{
SablonRoot = new List<OpenXmlElement>();
var nextSibling = bookmark.NextSibling();
if (nextSibling == null)
nextSibling = bookmark.Parent;
while (nextSibling != null)
{
var endBookmark = (nextSibling is BookmarkEnd end && end.Id == bookmark.Id.Value) ? end : null;
if (endBookmark == null)
{
endBookmark = nextSibling.Descendants<BookmarkEnd>().FirstOrDefault(x => x.Id == bookmark.Id.Value);
if (endBookmark != null)
SablonRoot.Add(nextSibling);
}
if (endBookmark != null)
{
bookmark.Remove();
endBookmark.Remove();
break;
}
SablonRoot.Add(nextSibling);
var tmpNextSibling = nextSibling.NextSibling();
if (tmpNextSibling == null)
{
tmpNextSibling = nextSibling.Parent;
if (tmpNextSibling != null && !(tmpNextSibling is Body) && !(tmpNextSibling is Document))
SablonRoot.Clear();
else
break;
}
nextSibling = tmpNextSibling;
}
}
if (SablonRoot != null && SablonRoot.Count > 0)
{
SablonRootBase = new List<OpenXmlElement>();
foreach (var item in SablonRoot)
{
SablonRootBase.Add(item.CloneNode(true));
}
BookmarkStart = new BookmarkStart() { Name = "repeater", Id = "1000" };
BookmarkEnd = new BookmarkEnd() { Id = "1000" };
if (SablonRoot.First().Parent != null)
{
SablonRoot.First().InsertBeforeSelf(BookmarkStart);
SablonRoot.First().InsertBeforeSelf(BookmarkEnd);
foreach (var rootItem in SablonRoot)
rootItem.Remove();
}
else
{
foreach (var rootItem in SablonRoot)
foreach (var rootItemChildElement in rootItem.ChildElements)
rootItemChildElement.Remove();
SablonRoot.First().AppendChild(BookmarkStart);
SablonRoot.First().AppendChild(BookmarkEnd);
}
Reset();
}
}
private void Insert()
{
var root = SablonRoot;
if (root.Count == 1 && root.First() is Document)
{
root = root.First().ChildElements.ToList();
}
for (var i = 0; i < root.Count; i++)
{
if (i == 0)
BookmarkStart.InsertBeforeSelf(root[i]);
else
root[i - 1].InsertAfterSelf(root[i]);
}
}
private void Reset()
{
SablonRoot.Clear();
foreach (var item in SablonRootBase)
{
SablonRoot.Add(item.CloneNode(true));
}
}
protected internal void InsertAndReset()
{
Insert();
Reset();
}
public void Dispose()
{
BookmarkStart?.Remove();
BookmarkEnd?.Remove();
SablonRootBase = null;
SablonRoot = null;
}
}
public IDisposable Repeat(string key)
{
Repeater = new SubSablon(Doc, key);
return Repeater;
}
public SablonGenerator(byte[] content)
{
Mem = new MemoryStream();
Mem.Write(content, 0, content.Length);
try
{
Doc = WordprocessingDocument.Open(Mem, true, new OpenSettings()
{
MarkupCompatibilityProcessSettings =
new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts,
FileFormatVersions.Office2010)
});
}
catch (Exception)
{
//if (!string.IsNullOrEmpty(Config.TryGetStringValue("SablonGeneratorErrorPath")))
//{
// File.WriteAllBytes(Path.Combine(Config.GetStringValue("SablonGeneratorErrorPath"), DateTime.Now.ToString("yyyyMMddHHHmmss.content")), content);
//}
throw;
}
_currentRoot = new List<OpenXmlElement>();
CurrentRoot.AddRange(Doc.MainDocumentPart.HeaderParts.Select(x => x.RootElement));
CurrentRoot.Add(Doc.MainDocumentPart.RootElement);
CurrentRoot.AddRange(Doc.MainDocumentPart.FooterParts.Select(x => x.RootElement));
}
public static void CheckOpenXmlDocument(byte[] content)
{
WordprocessingDocument doc = null;
var mem = new MemoryStream();
mem.Write(content, 0, content.Length);
try
{
doc = WordprocessingDocument.Open(mem, true, new OpenSettings()
{
MarkupCompatibilityProcessSettings =
new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts,
FileFormatVersions.Office2010)
});
}
catch (Exception ex)
{
#if DEBUG
//LoggerHelper.DiagnosticAudit.Information(DateTime.Now,
//Common.Enums.Area.BaseSystem,
//0,
//string.Format(ex.ToString()),
//new Guid().ToString());
//LoggerHelper.DiagnosticAudit.Log.Information(ex.ToString());
#else
//LoggerHelper.DiagnosticAudit.Information(DateTime.Now,
//Common.Enums.Area.BaseSystem,
//0,
//string.Format(ex.Message),
//Guid.Empty.ToString());
#endif
//throw new BusinessException("Hibás vagy nem megfelelő OpenXML állomány.");
}
finally
{
mem?.Dispose();
doc?.Dispose();
}
}
public void Generate(Dictionary<string, string> propertyDictionary)
{
ReplaceBookmarks(propertyDictionary);
if (Repeater?.SablonRoot != null) Repeater.InsertAndReset();
}
public void SimpleReplace(string key, string value)
{
value = value == null ? "" : value;
foreach (var headerPart in Doc.MainDocumentPart.HeaderParts)
SimpleReplace2(headerPart.Header, key, value);
SimpleReplace2(Doc.MainDocumentPart.Document.Body, key, value);
foreach (var footerPart in Doc.MainDocumentPart.FooterParts)
SimpleReplace2(footerPart.Footer, key, value);
}
protected void SimpleReplace(OpenXmlCompositeElement target, string key, string value)
{
var keyValue = key.Replace("#", "");
var texts = target.Descendants<Text>();
Text start = null;
Text keyValueText = null;
foreach (var text in texts)
if (text.Text == "#" && start == null)
start = text;
else if (text.Text == "#" && start != null && keyValueText != null)
{
var end = text;
keyValueText.Text = value;
start.Remove();
end.Remove();
start = null;
keyValueText = null;
}
else if (start != null && text.Text.ToUpper().Contains(keyValue.ToUpper()))
keyValueText = text;
else if (text.Text.ToUpper().Contains(key.ToUpper()))
{
start = null;
keyValueText = null;
text.Text = Regex.Replace(text.Text, key, value, RegexOptions.IgnoreCase);
}
else
{
start = null;
keyValueText = null;
}
}
protected void SimpleReplace2(OpenXmlCompositeElement target, string key, string value)
{
var texts = target.Descendants<Text>();
Text start = null;
var tokens = new List<Text>();
string tokenText = "";
foreach (var text in texts)
{
if (text.Text == "#" && start == null)
{
start = text;
tokenText += text.Text;
}
else if (text.Text == "#" && start != null)
{
var end = text;
tokenText += text.Text;
if (tokenText.ToUpper() == key.ToUpper())
{
start.Text = value;
foreach (var token in tokens)
{
token.Remove();
}
tokens.Clear();
end.Remove();
start = null;
tokenText = "";
}
else
{
start = null;
tokens.Clear();
tokenText = "";
end = null;
}
}
else if (text.Text.Contains('#') && text.Text.ToUpper() == key.ToUpper())
{
text.Text = value;
}
else if (text.Text.Contains('#'))
{
}
else if (start != null)
{
tokens.Add(text);
tokenText += text.Text;
}
}
}
public void SimpleReplaceForCV(string key, string value)
{
value = value == null ? "" : value;
SimpleReplaceForCV(Doc.MainDocumentPart.Document.Body, key, value);
}
protected void SimpleReplaceForCV(OpenXmlCompositeElement target, string key, string value)
{
var keyValue = key.Replace("#", "");
var texts = target.Descendants<Text>();
Text start = null;
Text keyValueText = null;
var keyindox = "";
foreach (var text in texts)
{
if (text.Text.Contains(key))
{
text.Text = text.Text.Replace(key, value);
break;
}
if (text.Text.Contains(keyValue + "#") && start != null)
{
start.Text = "";
text.Text = text.Text.Replace(keyValue + "#", value);
break;
}
if ((text.Text == "#" || (text.Text.Contains("#") && text.Text.Count(x => x == '#') == 1)) && start == null)
{
start = text;
keyindox = start.Text;
}
else if (start != null && (text.Text == "#" || text.Text.Contains("#")))
{
for (int i = texts.ToList().IndexOf(start) + 1; i < texts.ToList().IndexOf(text) + 1; i++)
{
if (texts.ToList()[i].Text.Contains(key))
{
texts.ToList()[i].Text = texts.ToList()[i].Text.Replace(key, value);
break;
}
keyindox = keyindox + texts.ToList()[i].Text;
}
keyindox = keyindox.Replace("#", "");
if (keyindox == keyValue || keyindox.Replace(" ", "") == keyValue)
{
for (int i = texts.ToList().IndexOf(start) + 1; i < texts.ToList().IndexOf(text); i++)
{
texts.ToList()[i].Text = "";
}
start.Text = "";
text.Text = value;
}
if (keyindox.Contains(keyValue))
{
for (int i = texts.ToList().IndexOf(start) + 1; i < texts.ToList().IndexOf(text); i++)
{
texts.ToList()[i].Text = "";
}
start.Text = "";
text.Text = keyindox.Replace(keyValue, value);
}
start = null;
keyindox = "";
}
}
}
private void ReplaceBookmarks(Dictionary<string, string> propertyDictionary)
{
var bookmarkEndList = new List<BookmarkEnd>();
foreach (var item in CurrentRoot)
{
var bookmarkEnds = item.Descendants<BookmarkEnd>();
bookmarkEndList.AddRange(bookmarkEnds.ToList());
}
foreach (var docContent in CurrentRoot)
{
var bookmarkStarts = docContent.Descendants<BookmarkStart>();
var bookmarkStartList = bookmarkStarts.ToList();
if (docContent is BookmarkStart)
bookmarkStartList.Add(docContent as BookmarkStart);
for (int k = 0; k < bookmarkStartList.Count; k++)
{
Run bookmarkRun = bookmarkStartList[k].NextSibling<Run>();
if (bookmarkRun != null)
{
var bookmarkText = bookmarkRun.GetFirstChild<Text>().InnerText;
if (propertyDictionary.ContainsKey(bookmarkText))
{
var itemValue = propertyDictionary[bookmarkText];
bookmarkRun.GetFirstChild<Text>().Text = itemValue ?? string.Empty;
var id = bookmarkStartList[k].Id.Value;
bookmarkStartList[k].Remove();
var end = bookmarkEndList.Find(x => x.Id == id);
end.Remove();
}
}
}
}
}
/// <summary>
/// Táblázat generálás (a keyinrow paramétert keresi a táblázat első sorában (nem fejléc), ezt a sort kitörli, és helyére szúrja be az új sorokat
/// amit az első paraméterben kap meg
/// </summary>
/// <param name="rowsAndCells">sorok és benne az egyes cellák tartalma</param>
/// <param name="keyInRow">első (nem fejléc) sorában lévő kulcs, ez alapján azonosítjuk be a táblázatot</param>
/// <param name="deleteEmptyRow">ha igaz, a táblázat összes meglévő sorát törli</param>
public void SetTable_Old(List<List<string>> rowsAndCells, string keyInRow, bool deleteEmptyRow = false)
{
Body bod = Doc.MainDocumentPart.Document.Body;
var table = bod.Descendants<Table>().Where(tbl => tbl.InnerText.Contains(keyInRow)).FirstOrDefault();
if (table != null)
{
if (deleteEmptyRow)
{
var firstRow = table.ChildElements.Where(x => x is TableRow).FirstOrDefault();
var deletedRows = table.ChildElements.Where(x => x is TableRow).ToList();
deletedRows.Remove(firstRow);
foreach (var item in deletedRows)
table.RemoveChild(item);
}
else
{
var deletedRow = table.ChildElements.Where(x => x is TableRow).LastOrDefault();
table.RemoveChild<TableRow>(deletedRow as TableRow);
}
foreach (var row in rowsAndCells)
{
List<OpenXmlElement> cells = new List<OpenXmlElement>();
foreach (var cell in row)
{
var tableCell = new TableCell(new Paragraph(new Run(new Text(cell))));
cells.Add(tableCell);
}
table.Append(new TableRow(cells));
}
}
}
public void SetTable(List<List<string>> rowsAndCells, string keyInRow, bool deleteEmptyRow = false)
{
Body bod = Doc.MainDocumentPart.Document.Body;
var table = bod.Descendants<Table>().Where(tbl => tbl.InnerText.Contains(keyInRow)).FirstOrDefault();
if (table != null)
{
TableRow formatRow = null;
// Megkeressük az első sort és elmentjük a formázást
if (deleteEmptyRow)
{
var firstRow = table.ChildElements.OfType<TableRow>().FirstOrDefault();
if (firstRow != null)
{
formatRow = (TableRow)firstRow.CloneNode(true); // Az első sor másolása formázással
var deletedRows = table.ChildElements.OfType<TableRow>().ToList();
foreach (var item in deletedRows)
table.RemoveChild(item);
}
}
else
{
var deletedRow = table.ChildElements.OfType<TableRow>().LastOrDefault();
if (deletedRow != null)
{
formatRow = (TableRow)deletedRow.CloneNode(true); // Az utolsó sor másolása formázással
table.RemoveChild(deletedRow);
}
}
// Új sorok beszúrása a mentett formázással
foreach (var row in rowsAndCells)
{
List<OpenXmlElement> cells = new List<OpenXmlElement>();
for (int i = 0; i < row.Count; i++)
{
var cellText = row[i].Replace("#", "");
// Ha van formázási minta, alkalmazzuk
TableCell newCell;
if (formatRow != null && i < formatRow.Elements<TableCell>().Count())
{
var formatCell = formatRow.Elements<TableCell>().ElementAt(i);
var clonedCell = (TableCell)formatCell.CloneNode(true);
var para = clonedCell.Descendants<Paragraph>().FirstOrDefault();
// Ha van beágyazott szöveg, frissítjük a tartalmát
if (para != null)
{
var run = para.Descendants<Run>().FirstOrDefault();
if (run != null)
{
run.RemoveAllChildren<Text>();
run.AppendChild(new Text(cellText));
}
}
newCell = clonedCell;
}
else
{
// Alapértelmezett cella, ha nincs formázási minta
newCell = new TableCell(new Paragraph(new Run(new Text(cellText))));
}
cells.Add(newCell);
}
table.Append(new TableRow(cells));
}
}
}
public byte[] CloseAndGetDocument()
{
Doc.Dispose();
Doc = null;
return Mem.ToArray();
}
public void Dispose()
{
Doc?.Dispose();
Mem.Dispose();
}
/// <summary>
/// Hozzáfűzi a már megnyitott fájlhoz a paraméterként kapott dokumentum tartalmát.
/// </summary>
/// <param name="document"></param>
/// <param name="addPageBreak"></param>
public void AppendDocument(byte[] document, bool addPageBreak = true)
{
var mainPart = Doc.MainDocumentPart;
string altChunkId = "AltChunk_" + Guid.NewGuid().ToString().Replace("-", "");
var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
chunk.FeedData(new MemoryStream(document));
// oldaltörés, ha kell
if (addPageBreak)
{
mainPart.Document.Body.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
}
mainPart.Document.Body.AppendChild(new AltChunk() { Id = altChunkId });
mainPart.Document.Save();
}
}
}
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="hu">
<head>
<meta charset="UTF-8">
<title>Értesítés jóváhagyásról</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;">
<p style="font-size: 18px;">
A következő munkafolyamat jóvá lett hagyva:
</p>
<p style="font-size: 28px; font-weight: bold; color: #333; margin-top: 10px;">
#DocumentNumber#
</p>
</body>
</html>
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="hu">
<head>
<meta charset="UTF-8">
<title>Megerősítő kód</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;">
<p style="font-size: 18px;">
<strong>Workflow Check Application Web</strong> megerősítő kódja:
</p>
<p style="font-size: 28px; font-weight: bold; color: #333; margin-top: 10px;">
#token2F#
</p>
</body>
</html>
+24 -22
View File
@@ -1,22 +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<ISystemService, SystemService>();
} }
}
}
+91 -54
View File
@@ -1,54 +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.Common.DTO; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.Common.DTO;
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>()
CreateMap<UserRole, UserRoleDTO>() .ForMember(dest => dest.ParentId, opt => opt.MapFrom(src => src.ParentId))
.ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role)) .ForMember(dest => dest.ParentRoleName, opt => opt.MapFrom(src => src.Parent != null ? src.Parent.RoleName : null));
.ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User));
CreateMap<UserRole, UserRoleDTO>()
CreateMap<UserDTO, User>() .ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role))
.ForMember(dest => dest.PasswordHash, opt => opt.MapFrom<PasswordHashResolver>()); .ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User));
CreateMap<UserDTO, User>()
CreateMap<CheckListTemplateHeader, CheckListTemplateHeaderDTO>() .ForMember(dest => dest.PasswordHash, opt => opt.MapFrom<PasswordHashResolver>());
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
CreateMap<CheckListTemplateRow, CheckListTemplateRowDTO>() CreateMap<CheckListTemplateHeader, CheckListTemplateHeaderDTO>()
.ForMember(dest => dest.EquipmentDTO, opt => opt.MapFrom(src => src.Equipment)) .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
.ForMember(dest => dest.CheckPointDTO, opt => opt.MapFrom(src => src.CheckPoint));
CreateMap<CheckListTemplateRow, CheckListTemplateRowDTO>()
CreateMap<CheckPoint, CheckPointDTO>().ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows)); .ForMember(dest => dest.EquipmentDTO, opt => opt.MapFrom(src => src.Equipment))
.ForMember(dest => dest.CheckPointDTO, opt => opt.MapFrom(src => src.CheckPoint));
CreateMap<CheckPointDTO, CheckPoint>();
CreateMap<CheckPoint, CheckPointDTO>()
CreateMap<Location, LocationDTO>(); .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
CreateMap<LocationDTO, Location>();
CreateMap<CheckPoint, CheckPointDTO>()
CreateMap<Equipment, EquipmentDTO>(); .ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRows));
CreateMap<EquipmentDTO, Equipment>();
CreateMap<CheckListHeader, CheckListHeaderDTO>()
.ForMember(dest => dest.UserDTO, opt => opt.MapFrom(src => src.User))
.ForMember(dest => dest.CheckListRowDTO, opt => opt.MapFrom(src => src.CheckListRows)); CreateMap<CheckPointDTO, CheckPoint>();
CreateMap<CheckListRow, CheckListRowDTO>() CreateMap<Location, LocationDTO>();
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRow)); CreateMap<LocationDTO, Location>();
}
} CreateMap<Equipment, EquipmentDTO>();
} CreateMap<EquipmentDTO, Equipment>();
CreateMap<DeviceMessage, DeviceMessageDTO>();
CreateMap<DeviceMessageDTO, DeviceMessage>();
CreateMap<CheckListHeader, CheckListHeaderDTO>()
.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.AcceptUserDTO, opt => opt.MapFrom(src => src.AcceptUser))
.ForMember(dest => dest.CheckListRowDTO, opt => opt.MapFrom(src => src.CheckListRows));
CreateMap<CheckListRow, CheckListRowDTO>()
.ForMember(dest => dest.CheckListTemplateRowDTO, opt => opt.MapFrom(src => src.CheckListTemplateRow))
.ForMember(dest => dest.Photo, opt => opt.MapFrom(src => GetImageBytes(src.PhotoFileName)));
CreateMap<RoleCheckListTemplateHeader, RoleCheckListTemplateHeaderDTO>()
.ForMember(dest => dest.RoleDTO, opt => opt.MapFrom(src => src.Role))
.ForMember(dest => dest.CheckListTemplateHeaderDTO, opt => opt.MapFrom(src => src.CheckListTemplateHeader));
}
private byte[] GetImageBytes(string fileName)
{
try
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Images", fileName);
if (File.Exists(filePath))
{
return File.ReadAllBytes(filePath);
}
return Array.Empty<byte>(); // Visszaad egy üres byte[]-ot, ha a fájl nem található
}
catch (Exception)
{
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);
} }
} }
} }
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.BL.Models
{
public class EmailSettings
{
public string SmtpServer { get; set; } = string.Empty;
public int SmtpPort { get; set; }
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string SenderName { get; set; } = string.Empty;
}
}
@@ -0,0 +1,149 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCheck.DL;
namespace WorkFlowCheck.BL.Services
{
public class BaseService
{
public readonly AppDbContext _dbContext;
public readonly IMapper _mapper;
private readonly ILogger _logger;
public BaseService(AppDbContext db_dbContext, IMapper mapper)
{
_dbContext = db_dbContext;
_mapper = mapper;
_logger = Log.ForContext("Tag", "PROGSEC");
}
public async Task<bool> DeleteEntityByIdAsync<T>(int id) where T : class
{
try
{
var entity = await _dbContext.Set<T>().FindAsync(id);
if (entity == null)
return false;
_dbContext.Set<T>().Remove(entity);
await _dbContext.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
Log.Error($"Hiba történt a törlés során: {ex.Message}");
return false;
}
}
public async Task<T?> GetEntityByIdAsync<T>(int id) where T : class
{
try
{
var entity = await _dbContext.Set<T>().FindAsync(id);
return entity;
}
catch (Exception ex)
{
Log.Error($"Hiba történt a lekérdezés során: {ex.Message}");
return null;
}
}
public async Task<List<TEntity>> GetEntityByFilterAsync<TEntity, TFilter>(TFilter filter) where TEntity : class where TFilter : class
{
try
{
IQueryable<TEntity> query = _dbContext.Set<TEntity>();
foreach (var property in typeof(TFilter).GetProperties())
{
var value = property.GetValue(filter);
if (value != null)
{
var parameter = Expression.Parameter(typeof(TEntity), "x");
var member = Expression.Property(parameter, property.Name);
var constant = Expression.Constant(value);
var equal = Expression.Equal(member, constant);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
query = query.Where(lambda);
}
}
// Adatok lekérdezése
return await query.ToListAsync();
}
catch (Exception ex)
{
Log.Error($"Hiba történt a lekérdezés során: {ex.Message}");
return new List<TEntity>();
}
}
public async Task<PagedResult<TEntity>> GetPagedEntityByFilterAsync<TEntity, TFilter>(TFilter filter, int pageNumber, int pageSize) where TEntity : class where TFilter : class
{
try
{
// Az IQueryable típusú lista létrehozása
IQueryable<TEntity> query = _dbContext.Set<TEntity>();
// Dinamikus szűrés a filter tulajdonságai alapján
foreach (var property in typeof(TFilter).GetProperties())
{
var value = property.GetValue(filter);
if (value != null)
{
var parameter = Expression.Parameter(typeof(TEntity), "x");
var member = Expression.Property(parameter, property.Name);
var constant = Expression.Constant(value);
var equal = Expression.Equal(member, constant);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
query = query.Where(lambda);
}
}
// Teljes rekordok száma a szűrő után
int totalCount = await query.CountAsync();
// Lapozás alkalmazása
var items = await query
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
// Lapozási eredmény összerakása
return new PagedResult<TEntity>
{
Items = items,
TotalCount = totalCount,
PageNumber = pageNumber,
PageSize = pageSize
};
}
catch (Exception ex)
{
Console.WriteLine($"Hiba történt a lekérdezés során: {ex.Message}");
return new PagedResult<TEntity>();
}
}
}
public class PagedResult<TEntity>
{
public List<TEntity> Items { get; set; } = new List<TEntity>();
public int TotalCount { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
}
}
File diff suppressed because it is too large Load Diff
@@ -1,27 +1,37 @@
using System; using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic; using WorkFlowCheck.Common.DataTables;
using System.Linq; using WorkFlowCheck.Common.DTO;
using System.Text;
using System.Threading.Tasks; namespace WorkFlowCheck.BL.Services.Interfaces
using WorkFlowCheck.Common.DTO; {
public interface ICheckListService
namespace WorkFlowCheck.BL.Services.Interfaces {
{ Task<CheckListHeaderDTO> GetCheckListHeaderAsync(int Id);
public interface ICheckListService Task<ApiResponseListDTO<List<CheckListHeaderDTO>>> GetFilteredCheckListHeaderAsync(DataTablesRequest dataTablesRequest);
{ Task<List<CheckListHeaderDTO>> GetAllCheckListHeaderAsync(int mode = 0);
Task<CheckListHeaderDTO> GetCheckListHeaderAsync(int Id); Task<CheckListHeaderDTO> UpdateCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO);
Task<List<CheckListHeaderDTO>> GetAllCheckListHeaderAsync(); Task<bool> AcceptCheckListHeaderAsync(int id, int userid);
Task<CheckListHeaderDTO> UpdateCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO); Task<bool> BlockCheckListHeaderAsync(int id, int userid);
Task<bool> UnBlockCheckListHeaderAsync(int id, int userid);
Task<CheckListHeaderDTO> StartNewCheckListAsync(CheckListHeaderNewDTO checkListHeaderNewDTO); Task<bool> CloseCheckListHeader(CheckListHeaderCloseDTO closeCheckListHeaderCloseDTO);
Task<byte[]> CreateCheckListHeaderPDFAsync(int checkListHeaderId);
Task<CheckListHeaderDTO> StartNewCheckListAsync(CheckListHeaderNewDTO checkListHeaderNewDTO);
Task<CheckListTemplateHeaderDTO> GetCheckListTemplateHeaderAsync(int Id);
Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateHeaderAsync();
Task<CheckListTemplateHeaderDTO> UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO); Task<CheckListTemplateHeaderDTO> GetCheckListTemplateHeaderAsync(int Id);
Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateHeaderAsync();
Task<CheckListTemplateRowDTO> GetCheckListTemplateRowAsync(int id); Task<CheckListTemplateHeaderDTO> UpdateCheckListTemplateHeaderAsync(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO);
Task<CheckListTemplateRowDTO> UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO checkListTemplateRowDTO); Task<bool> DeleteCheckListTemplateHeaderAsync(int id);
Task<bool> CloneCheckListTemplateHeaderAsync(int id);
} Task<CheckListTemplateRowDTO> GetCheckListTemplateRowAsync(int id);
} Task<bool> DeleteCheckListTemplateRowAsync(int id);
Task<CheckListTemplateRowDTO> UpdateCheckListTemplateRowAsync(CheckListTemplateRowDTO checkListTemplateRowDTO);
Task<CheckListRowDTO> GetCheckListRowAsync(int id);
Task<CheckListRowDTO> UpdateCheckListRowAsync(CheckListRowDTO checkListRowDTO);
}
}
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services.Interfaces
{
public interface IMessageService
{
Task<bool> SendMailAsync(List<string> recipients, string subject, string htmlBody, string? attachmentFilePath = null);
Task<bool> SendFCMTokenAsync(string token);
Task<string> GetLastFCMTokensAsync();
Task<bool> SendFCMMessage(FCMMessageDTO fCMMessageDTO);
Task<bool> SendFCMMessageToLastToken(FCMMessageDTO fCMMessageDTO);
}
}
@@ -1,15 +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;
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> GetSampleAsync(int templateId, DateTime? baseDate = null); Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null);
} Task<string> GetSampleAsync(int templateId, DateTime? baseDate = null);
} Task<List<NumberGeneratorTemplateDTO>> GetAllNumbergeneratorsAsync();
}
}
@@ -1,27 +1,39 @@
using WorkFlowCheck.Common.DTO; using Microsoft.AspNetCore.Mvc;
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<CheckPointDTO> GetCheckPointAsync(int id); Task<List<CheckPointDTO>> GetAllCheckPointAsync();
Task<CheckPointDTO> UpdateCheckPointAsync(CheckPointDTO checkPointDTO); Task<CheckPointDTO> GetCheckPointAsync(int id);
Task<List<CheckPointDTO>> UpdateAllCheckPointAsync(List<CheckPointDTO> checkPointListDTO); Task<bool> DeleteCheckPointAsync(int id);
Task<CheckPointDTO> UpdateCheckPointAsync(CheckPointDTO checkPointDTO);
Task<List<CheckPointDTO>> UpdateAllCheckPointAsync(List<CheckPointDTO> checkPointListDTO);
Task<List<LocationDTO>> GetAllLocationAsync();
Task<LocationDTO> GetLocationAsync(int id);
Task<LocationDTO> UpdateLocationAsync(LocationDTO LocationDTO); Task<List<LocationDTO>> GetAllLocationAsync();
Task<LocationDTO> GetLocationAsync(int id);
Task<bool> DeleteLocationAsync(int id);
Task<List<EquipmentDTO>> GetAllEquipmentAsync(); Task<LocationDTO> UpdateLocationAsync(LocationDTO LocationDTO);
Task<EquipmentDTO> GetEquipmentAsync(int id);
Task<EquipmentDTO> UpdateEquipmentAsync(EquipmentDTO EquipmentDTO);
Task<List<EquipmentDTO>> GetAllEquipmentAsync();
Task<EquipmentDTO> GetEquipmentAsync(int id);
Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateAsync(int userId); Task<bool> DeleteEquipmentAsync(int id);
Task<List<CheckListHeaderDTO>> GetAllCheckListAsync(int userId); Task<EquipmentDTO> UpdateEquipmentAsync(EquipmentDTO EquipmentDTO);
}
}
Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateAsync(int userId);
Task<List<CheckListHeaderDTO>> GetAllCheckListAsync(int userId);
Task<CheckListHeaderDTO> SendCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO);
Task<bool> DeviceMessageSend(DeviceMessageDTO deviceMessageDTO);
Task<List<DeviceMessageDTO>> DeviceMessageReadUnreaded(string deviceId);
Task<List<DeviceMessageDTO>> DeviceMessageReadUnreadedRole(int roleId);
}
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.BL.Services.Interfaces
{
public interface ISystemService
{
Task<string> GetDatabaseAndVersionInfoAsync();
}
}
@@ -1,29 +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<UserDTO> UpdateUserAsync(UserDTO userDTO); Task<bool> DeleteUserAsync(int Id);
Task<UserDTO> Authenticate(string UserName, string Password); Task<UserDTO> UpdateUserAsync(UserDTO userDTO);
Task<UserDTO> Authenticate(string UserName, string Password);
Task<RoleDTO> GetRoleAsync(int Id); Task<string> Authenticate2F1(string UserName, string Password);
Task<List<RoleDTO>> GetAllRoleAsync(); Task<UserDTO> Authenticate2F2(string UserName, string Password, string Code, string token2FA);
Task<RoleDTO> UpdateRoleAsync(RoleDTO roleDTO); Task<UserDTO> Authenticate2F2ChangePassword(string UserName, string OldPassword, string NewPassword, string Code, string token2FA);
Task<UserDTO> AuthenticateNFC(string NFCCode);
Task<UserRoleDTO> GetUserRoleAsync(int Id);
Task<List<UserRoleDTO>> GetAllUserRoleAsync();
Task<UserRoleDTO> UpdateUserRoleAsync(UserRoleDTO userRoleDTO); Task<RoleDTO> GetRoleAsync(int Id);
Task<List<RoleDTO>> GetAllRoleAsync();
Task<bool> DeleteRoleAsync(int Id);
Task<RoleDTO> UpdateRoleAsync(RoleDTO roleDTO);
string GenerateJwtToken(UserDTO userDTO);
} Task<UserRoleDTO> GetUserRoleAsync(int Id);
} Task<List<UserRoleDTO>> GetAllUserRoleAsync();
Task<bool> DeleteUserRoleAsync(int Id);
Task<UserRoleDTO> UpdateUserRoleAsync(UserRoleDTO userRoleDTO);
Task<RoleCheckListTemplateHeaderDTO> GetRoleCheckListTemplateHeaderAsync(int Id);
Task<List<RoleCheckListTemplateHeaderDTO>> GetAllRoleCheckListTemplateHeadersAsync();
Task<bool> DeleteRoleCheckListTemplateHeaderAsync(int Id);
Task<RoleCheckListTemplateHeaderDTO> UpdateRoleCheckListTemplateHeaderAsync(RoleCheckListTemplateHeaderDTO roleCheckListTemplateHeaderDTO);
Task<RoleCheckPointDTO> GetRoleCheckPointAsync(int Id);
Task<List<RoleCheckPointDTO>> GetAllRoleCheckPointsAsync();
Task<bool> DeleteRoleCheckPointAsync(int Id);
Task<RoleCheckPointDTO> UpdateRoleCheckPointAsync(RoleCheckPointDTO roleCheckPointDTO);
string GenerateJwtToken(UserDTO userDTO);
}
}
@@ -0,0 +1,216 @@
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using Microsoft.Extensions.Configuration;
using WorkFlowCheck.BL.Models;
using WorkFlowCheck.BL.Services.Interfaces;
using Serilog;
using WorkFlowCheck.DL.Entities;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using WorkFlowCheck.DL;
using WorkFlowCheck.Common.DTO;
using System.Net.Http.Headers;
using System.Text;
using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;
namespace WorkFlowCheck.BL.Services
{
public class MessageService : BaseService, IMessageService
{
private readonly EmailSettings _settings;
public MessageService(AppDbContext dbContext,
IMapper mapper,
IConfiguration configuration) : base(dbContext, mapper)
{
_settings = configuration.GetSection("EmailSettings").Get<EmailSettings>()!;
}
public async Task<bool> SendMailAsync(List<string> recipients, string subject, string htmlBody, string? attachmentFilePath = null)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_settings.SenderName, _settings.Username));
foreach (var recipient in recipients)
{
message.To.Add(MailboxAddress.Parse(recipient));
}
message.Subject = subject;
var builder = new BodyBuilder
{
HtmlBody = htmlBody
};
if (!string.IsNullOrEmpty(attachmentFilePath) && File.Exists(attachmentFilePath))
{
builder.Attachments.Add(attachmentFilePath);
}
message.Body = builder.ToMessageBody();
const int maxRetries = 10;
const int delayMs = 2000;
bool authenticated = false;
Exception lastException = null;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
using var smtp = new SmtpClient();
await smtp.ConnectAsync(_settings.SmtpServer, _settings.SmtpPort, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync(_settings.Username, _settings.Password);
await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);
authenticated = true;
break; // 🎯 siker
}
catch (Exception ex)
{
lastException = ex;
Log.ForContext("TAG", "BusinessFlow").Error(lastException?.Message ?? "E-mail küldése sikertelen!");
if (attempt == maxRetries)
break;
// ⏳ várunk 1 másodpercet és újrapróbáljuk
await Task.Delay(delayMs);
}
}
if (!authenticated)
{
// 🔴 IDE ÍRHATSZ MAJD SAJÁT LOGIKÁT
Log.ForContext("TAG", "BusinessFlow").Error(lastException?.Message ?? "E-mail küldése sikertelen!");
}
return true;
}
public async Task<bool> SendFCMTokenAsync(string token)
{
var retVal = true;
try
{
if (!string.IsNullOrEmpty(token))
{
var FCMToken = await _dbContext.FCMTokens.Where(w => w.Token == token).FirstOrDefaultAsync();
if (FCMToken == null)
{
FCMToken = new FCMToken();
FCMToken.Token = token;
await _dbContext.FCMTokens.AddAsync(FCMToken);
}
else
{
FCMToken.LastModAt = DateTime.UtcNow;
}
await _dbContext.SaveChangesAsync();
}
}
catch (Exception ex)
{
retVal = false;
Log.ForContext("TAG", "BusinessFlow").Error(ex.Message);
}
return retVal;
}
public async Task<string> GetLastFCMTokensAsync()
{
var retVal = "";
try
{
var FCMToken = await _dbContext.FCMTokens
.AsNoTracking()
.OrderByDescending(x => x.LastModAt)
.Take(1)
.FirstOrDefaultAsync();
if (FCMToken != null && !string.IsNullOrEmpty(FCMToken.Token))
{
retVal += FCMToken.Token;
}
}
catch (Exception ex)
{
retVal = "";
Log.ForContext("TAG", "BusinessFlow").Error(ex.Message);
}
return retVal;
}
public async Task<bool> SendFCMMessage(FCMMessageDTO fCMMessageDTO)
{
var retVal = true;
try
{
var pathToJsonKey = "com-nuvolar-wfcapp-firebase-adminsdk-fbsvc-37642626e4.json";
var projectId = "com-nuvolar-wfcapp";
var credential = GoogleCredential
.FromFile(pathToJsonKey)
.CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var message = new
{
message = new
{
token = fCMMessageDTO.Token,
notification = new
{
title = fCMMessageDTO.Title,
body = fCMMessageDTO.Body,
},
android = new
{
notification = new
{
channel_id = "com.nuvolar.wfcapp.general"
}
}
}
};
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,144 +1,164 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage;
using System; using Serilog;
using System.Collections.Generic; using System;
using System.Linq; using System.Collections.Generic;
using System.Text; using System.Linq;
using System.Threading.Tasks; using System.Text;
using WorkFlowCheck.BL.Services.Interfaces; using System.Threading.Tasks;
using WorkFlowCheck.DL; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.DL;
namespace WorkFlowCheck.BL.Services using WorkFlowCheck.DL.Entities;
{
public class NumberGeneratorService : INumberGeneratorService namespace WorkFlowCheck.BL.Services
{ {
private readonly DbContext _dbContext; public class NumberGeneratorService : INumberGeneratorService
private static readonly Dictionary<int, SemaphoreSlim> _templateLocks = new(); {
private readonly AppDbContext _dbContext;
public NumberGeneratorService(AppDbContext dbContext) private static readonly Dictionary<int, SemaphoreSlim> _templateLocks = new();
{
_dbContext = dbContext; public NumberGeneratorService(AppDbContext dbContext)
} {
_dbContext = dbContext;
public async Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null) }
{
var semaphore = GetOrCreateSemaphore(templateId); public async Task<string> GenerateNextNumberAsync(int templateId, IDbContextTransaction transaction, DateTime? baseDate = null)
await semaphore.WaitAsync(); {
var semaphore = GetOrCreateSemaphore(templateId);
try await semaphore.WaitAsync();
{
try
var template = await _dbContext.Set<NumberGeneratorTemplate>() {
.FirstOrDefaultAsync(t => t.Id == templateId);
var template = await _dbContext.Set<NumberGeneratorTemplate>()
if (template == null) .FirstOrDefaultAsync(t => t.Id == templateId);
throw new InvalidOperationException($"Template with ID {templateId} not found.");
if (template == null)
var now = baseDate ?? DateTime.Now; throw new InvalidOperationException($"Template with ID {templateId} not found.");
var (year, month) = GetKeyDateParts(template, now);
var now = baseDate ?? DateTime.Now;
var templateDate = await _dbContext.Set<NumberGeneratorTemplateDate>() var (year, month) = GetKeyDateParts(template, now);
.FirstOrDefaultAsync(td => td.NumberGeneratorTemplateId == templateId && td.Year == year && td.Month == month);
var templateDate = await _dbContext.Set<NumberGeneratorTemplateDate>()
if (templateDate == null) .FirstOrDefaultAsync(td => td.NumberGeneratorTemplateId == templateId && td.Year == year && td.Month == month);
{
templateDate = new NumberGeneratorTemplateDate if (templateDate == null)
{ {
NumberGeneratorTemplateId = template.Id, templateDate = new NumberGeneratorTemplateDate
Year = year, {
Month = month, NumberGeneratorTemplateId = template.Id,
CurrentNumber = 0 Year = year,
}; Month = month,
_dbContext.Add(templateDate); CurrentNumber = 0
} };
_dbContext.Add(templateDate);
templateDate.CurrentNumber++; }
var formatted = templateDate.CurrentNumber.ToString(template.DigitFormat);
var dynamicSuffix = BuildDynamicSuffix(template, now); templateDate.CurrentNumber++;
var result = BuildFormattedNumber(template, formatted, dynamicSuffix); var formatted = templateDate.CurrentNumber.ToString(template.DigitFormat);
var dynamicSuffix = BuildDynamicSuffix(template, now);
templateDate.LastGeneratedNumber = result; var result = BuildFormattedNumber(template, formatted, dynamicSuffix);
await _dbContext.SaveChangesAsync();
return result; templateDate.LastGeneratedNumber = result;
} await _dbContext.SaveChangesAsync();
catch return result;
{ }
throw; catch
} {
finally throw;
{ }
semaphore.Release(); finally
} {
} 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>() {
.AsNoTracking() var template = await _dbContext.Set<NumberGeneratorTemplate>()
.FirstOrDefaultAsync(t => t.Id == templateId); .AsNoTracking()
.FirstOrDefaultAsync(t => t.Id == templateId);
if (template == null)
throw new InvalidOperationException($"Template with ID {templateId} not found."); if (template == null)
throw new InvalidOperationException($"Template with ID {templateId} not found.");
var now = baseDate ?? DateTime.Now;
var formatted = 1.ToString(template.DigitFormat); var now = baseDate ?? DateTime.Now;
var dynamicSuffix = BuildDynamicSuffix(template, now); var formatted = 1.ToString(template.DigitFormat);
var dynamicSuffix = BuildDynamicSuffix(template, now);
return BuildFormattedNumber(template, formatted, dynamicSuffix);
} return BuildFormattedNumber(template, formatted, dynamicSuffix);
}
private SemaphoreSlim GetOrCreateSemaphore(int templateId) public async Task<List<NumberGeneratorTemplateDTO>> GetAllNumbergeneratorsAsync()
{ {
lock (_templateLocks) var retVal = new List<NumberGeneratorTemplateDTO>();
{ try
if (!_templateLocks.ContainsKey(templateId)) {
_templateLocks[templateId] = new SemaphoreSlim(1, 1); var numbergenerators = await _dbContext.NumberGeneratorTemplates.ToListAsync();
foreach (var numbergenerator in numbergenerators)
return _templateLocks[templateId]; {
} var numbergeneratortemplateDTO = new NumberGeneratorTemplateDTO();
} numbergeneratortemplateDTO.Id = numbergenerator.Id;
numbergeneratortemplateDTO.ShortName = numbergenerator.ShortName;
private static (int year, int? month) GetKeyDateParts(NumberGeneratorTemplate template, DateTime date) numbergeneratortemplateDTO.Sample = await this.GetSampleAsync(numbergenerator.Id, DateTime.Now);
{ retVal.Add(numbergeneratortemplateDTO);
int year = date.Year; }
int? month = template.GenerateType == GenerateType.YearAndMonth ? date.Month : null; }
return (year, month); catch (Exception ex)
} {
Log.Error(ex.Message);
private static string BuildDynamicSuffix(NumberGeneratorTemplate template, DateTime date) }
{ return retVal;
return template.GenerateType switch }
{
GenerateType.OnlyYear => date.Year.ToString(),
GenerateType.YearAndMonth => $"{date.Year}/{date.Month:D2}", private SemaphoreSlim GetOrCreateSemaphore(int templateId)
_ => template.Suffix {
}; lock (_templateLocks)
} {
if (!_templateLocks.ContainsKey(templateId))
private static string BuildFormattedNumber(NumberGeneratorTemplate template, string formattedNumber, string dynamicSuffix) _templateLocks[templateId] = new SemaphoreSlim(1, 1);
{
var sb = new StringBuilder(); return _templateLocks[templateId];
}
if (!string.IsNullOrEmpty(template.Prefix)) }
sb.Append(template.Prefix); private static (int year, int? month) GetKeyDateParts(NumberGeneratorTemplate template, DateTime date)
{
if (!string.IsNullOrEmpty(template.PrefixSeparator) && !string.IsNullOrEmpty(template.Prefix)) int year = date.Year;
sb.Append(template.PrefixSeparator); int? month = template.GenerateType == GenerateType.YearAndMonth ? date.Month : null;
return (year, month);
sb.Append(formattedNumber); }
private static string BuildDynamicSuffix(NumberGeneratorTemplate template, DateTime date)
if (!string.IsNullOrEmpty(dynamicSuffix)) {
{ return template.GenerateType switch
if (!string.IsNullOrEmpty(template.SuffixSeparator)) {
sb.Append(template.SuffixSeparator); GenerateType.OnlyYear => date.Year.ToString(),
GenerateType.YearAndMonth => $"{date.Year}/{date.Month:D2}",
sb.Append(dynamicSuffix); _ => template.Suffix
} };
}
return sb.ToString(); private static string BuildFormattedNumber(NumberGeneratorTemplate template, string formattedNumber, string dynamicSuffix)
} {
} var sb = new StringBuilder();
if (!string.IsNullOrEmpty(template.Prefix))
} sb.Append(template.Prefix);
if (!string.IsNullOrEmpty(template.PrefixSeparator) && !string.IsNullOrEmpty(template.Prefix))
sb.Append(template.PrefixSeparator);
sb.Append(formattedNumber);
if (!string.IsNullOrEmpty(dynamicSuffix))
{
if (!string.IsNullOrEmpty(template.SuffixSeparator))
sb.Append(template.SuffixSeparator);
sb.Append(dynamicSuffix);
}
return sb.ToString();
}
}
}
+599 -343
View File
@@ -1,343 +1,599 @@
using AutoMapper; using AutoMapper;
using Microsoft.EntityFrameworkCore; using DocumentFormat.OpenXml.InkML;
using Serilog; using DocumentFormat.OpenXml.Office2010.Excel;
using System.Collections.Generic; using DocumentFormat.OpenXml.Spreadsheet;
using WorkFlowCheck.BL.Services.Interfaces; using Microsoft.EntityFrameworkCore;
using WorkFlowCheck.Common.DTO; using Serilog;
using WorkFlowCheck.DL; using System.Collections.Generic;
using WorkFlowCheck.DL.Entities; using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO;
namespace WorkFlowCheck.BL.Services using WorkFlowCheck.Common.Enums;
{ using WorkFlowCheck.Common.RequestContext;
public class SyncService : ISyncService using WorkFlowCheck.DL;
{ using WorkFlowCheck.DL.Entities;
private AppDbContext _dbContext;
private IMapper _mapper; namespace WorkFlowCheck.BL.Services
{
public SyncService(AppDbContext dbContext, IMapper mapper) public class SyncService : BaseService, ISyncService
{ {
_dbContext = dbContext; private readonly IRequestContext _requestContext;
_mapper = mapper; private readonly IUserService _userService;
} private readonly IMessageService _messageService;
public async Task<List<CheckPointDTO>> GetAllCheckPointAsync() public SyncService(AppDbContext dbContext,
{ IMapper mapper,
var retVal = new List<CheckPointDTO>(); IRequestContext requestContext,
IMessageService messageService,
try IUserService userService) : base(dbContext, mapper)
{ {
var res = await _dbContext.CheckPoints _requestContext = requestContext;
.Include(i => i.CheckListTemplateRows) _userService = userService;
.AsNoTracking() _messageService = messageService;
.ToListAsync(); }
if (res != null)
{ public async Task<List<CheckPointDTO>> GetAllCheckPointAsync()
retVal = _mapper.Map<List<CheckPointDTO>>(res); {
} var retVal = new List<CheckPointDTO>();
}
catch (Exception ex) try
{ {
Log.Error(ex.Message); var res = await _dbContext.CheckPoints
} .Include(i => i.CheckListTemplateRows)
.AsNoTracking()
return retVal; .ToListAsync();
} if (res != null)
public async Task<CheckPointDTO> GetCheckPointAsync(int id) {
{ retVal = _mapper.Map<List<CheckPointDTO>>(res);
var retVal = new CheckPointDTO(); }
}
try catch (Exception ex)
{ {
var res = await _dbContext.CheckPoints Log.Error(ex.Message);
.Include(i => i.CheckListTemplateRows) }
.Where(w => w.Id == id)
.AsNoTracking() return retVal;
.FirstOrDefaultAsync(); }
if (res != null) public async Task<CheckPointDTO> GetCheckPointAsync(int id)
{ {
retVal = _mapper.Map<CheckPointDTO>(res); var retVal = new CheckPointDTO();
}
} try
catch (Exception ex) {
{ var checkpoint = await _dbContext.CheckPoints
Log.Error(ex.Message); .Include(i => i.CheckListTemplateRows)
} .Where(w => w.Id == id)
.AsNoTracking()
return retVal; .FirstOrDefaultAsync();
} if (checkpoint != null)
public async Task<CheckPointDTO> UpdateCheckPointAsync(CheckPointDTO checkPointDTO) {
{ retVal = _mapper.Map<CheckPointDTO>(checkpoint);
var retVal = new CheckPointDTO();
var role = await _dbContext.Roles.Where(w => w.Id == retVal.RoleId).FirstOrDefaultAsync();
try
{ }
if (checkPointDTO.Id == 0) //Hozzáadás, ha Id == 0 }
{ catch (Exception ex)
var checkPoint = _mapper.Map<CheckPoint>(checkPointDTO); {
_dbContext.CheckPoints.Add(checkPoint); Log.Error(ex.Message);
await _dbContext.SaveChangesAsync(); }
retVal = _mapper.Map<CheckPointDTO>(checkPoint); return retVal;
} }
else public async Task<bool> DeleteCheckPointAsync(int id)
{ {
var res = await _dbContext.CheckPoints.Where(w => w.Id == checkPointDTO.Id).FirstOrDefaultAsync(); return await DeleteEntityByIdAsync<CheckPoint>(id);
if (res != null) }
{ public async Task<CheckPointDTO> UpdateCheckPointAsync(CheckPointDTO checkPointDTO)
res.ShortName = checkPointDTO.ShortName; {
res.Code = checkPointDTO.Code; var retVal = new CheckPointDTO();
await _dbContext.SaveChangesAsync(); try
{
retVal = _mapper.Map<CheckPointDTO>(res); if (checkPointDTO.Id == 0) //Hozzáadás, ha Id == 0
} {
} var checkPoint = _mapper.Map<CheckPoint>(checkPointDTO);
} _dbContext.CheckPoints.Add(checkPoint);
catch (Exception ex) await _dbContext.SaveChangesAsync();
{
Log.Error(ex.Message); retVal = _mapper.Map<CheckPointDTO>(checkPoint);
} }
else
return retVal; {
} var res = await _dbContext.CheckPoints.Where(w => w.Id == checkPointDTO.Id).FirstOrDefaultAsync();
public async Task<List<CheckPointDTO>> UpdateAllCheckPointAsync(List<CheckPointDTO> checkPointListDTO) if (res != null)
{ {
var retVal = new List<CheckPointDTO>(); res.ShortName = checkPointDTO.ShortName;
try res.Code = checkPointDTO.Code;
{ res.IsEnabled = checkPointDTO.IsEnabled;
var ids = checkPointListDTO.Select(dto => dto.Id).ToList();
var checkPoints = await _dbContext.CheckPoints await _dbContext.SaveChangesAsync();
.Where(cp => ids.Contains(cp.Id))
.ToListAsync(); retVal = _mapper.Map<CheckPointDTO>(res);
}
foreach (var checkPoint in checkPoints) }
{ }
var dto = checkPointListDTO.FirstOrDefault(d => d.Id == checkPoint.Id); catch (Exception ex)
if (dto != null) {
{ Log.Error(ex.Message);
checkPoint.Code = dto.Code; }
}
} return retVal;
await _dbContext.SaveChangesAsync(); }
retVal = _mapper.Map<List<CheckPointDTO>>(checkPoints); public async Task<List<CheckPointDTO>> UpdateAllCheckPointAsync(List<CheckPointDTO> checkPointListDTO)
} {
catch (Exception ex) var retVal = new List<CheckPointDTO>();
{ try
Log.Error(ex.Message); {
} var ids = checkPointListDTO.Select(dto => dto.Id).ToList();
return retVal; var checkPoints = await _dbContext.CheckPoints
} .Where(cp => ids.Contains(cp.Id))
.ToListAsync();
public async Task<List<LocationDTO>> GetAllLocationAsync()
{ foreach (var checkPoint in checkPoints)
var retVal = new List<LocationDTO>(); {
var dto = checkPointListDTO.FirstOrDefault(d => d.Id == checkPoint.Id);
try if (dto != null)
{ {
var res = await _dbContext.Locations.ToListAsync(); checkPoint.Code = dto.Code;
if (res != null) }
{ }
retVal = _mapper.Map<List<LocationDTO>>(res); await _dbContext.SaveChangesAsync();
} retVal = _mapper.Map<List<CheckPointDTO>>(checkPoints);
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal;
return retVal; }
}
public async Task<LocationDTO> GetLocationAsync(int id) public async Task<List<LocationDTO>> GetAllLocationAsync()
{ {
var retVal = new LocationDTO(); var retVal = new List<LocationDTO>();
try try
{ {
var res = await _dbContext.Locations var res = await _dbContext.Locations.ToListAsync();
.Where(w => w.Id == id) if (res != null)
.AsNoTracking() {
.FirstOrDefaultAsync(); retVal = _mapper.Map<List<LocationDTO>>(res);
if (res != null) }
{ }
retVal = _mapper.Map<LocationDTO>(res); catch (Exception ex)
} {
} Log.Error(ex.Message);
catch (Exception ex) }
{
Log.Error(ex.Message); return retVal;
} }
public async Task<LocationDTO> GetLocationAsync(int id)
return retVal; {
} var retVal = new LocationDTO();
public async Task<LocationDTO> UpdateLocationAsync(LocationDTO LocationDTO)
{ try
var retVal = new LocationDTO(); {
var res = await _dbContext.Locations
try .Where(w => w.Id == id)
{ .AsNoTracking()
if (LocationDTO.Id == 0) //Hozzáadás, ha Id == 0 .FirstOrDefaultAsync();
{ if (res != null)
var Location = _mapper.Map<Location>(LocationDTO); {
_dbContext.Locations.Add(Location); retVal = _mapper.Map<LocationDTO>(res);
await _dbContext.SaveChangesAsync(); }
}
retVal = _mapper.Map<LocationDTO>(Location); catch (Exception ex)
} {
else Log.Error(ex.Message);
{ }
var res = await _dbContext.Locations.Where(w => w.Id == LocationDTO.Id).FirstOrDefaultAsync();
if (res != null) return retVal;
{ }
res = _mapper.Map<Location>(LocationDTO); public async Task<bool> DeleteLocationAsync(int id)
{
await _dbContext.SaveChangesAsync(); return await DeleteEntityByIdAsync<DL.Entities.Location>(id);
}
retVal = _mapper.Map<LocationDTO>(res); public async Task<LocationDTO> UpdateLocationAsync(LocationDTO LocationDTO)
} {
} var retVal = new LocationDTO();
}
catch (Exception ex) try
{ {
Log.Error(ex.Message); if (LocationDTO.Id == 0) //Hozzáadás, ha Id == 0
} {
var Location = _mapper.Map<DL.Entities.Location>(LocationDTO);
return retVal; _dbContext.Locations.Add(Location);
} await _dbContext.SaveChangesAsync();
public async Task<List<EquipmentDTO>> GetAllEquipmentAsync() retVal = _mapper.Map<LocationDTO>(Location);
{ }
var retVal = new List<EquipmentDTO>(); else
{
try var res = await _dbContext.Locations.Where(w => w.Id == LocationDTO.Id).FirstOrDefaultAsync();
{ if (res != null)
var res = await _dbContext.Equipments.ToListAsync(); {
if (res != null) res.FullName = LocationDTO.FullName;
{ await _dbContext.SaveChangesAsync();
retVal = _mapper.Map<List<EquipmentDTO>>(res);
} retVal = _mapper.Map<LocationDTO>(res);
} }
catch (Exception ex) }
{ }
Log.Error(ex.Message); catch (Exception ex)
} {
Log.Error(ex.Message);
return retVal; }
}
public async Task<EquipmentDTO> GetEquipmentAsync(int id) return retVal;
{ }
var retVal = new EquipmentDTO();
public async Task<List<EquipmentDTO>> GetAllEquipmentAsync()
try {
{ var retVal = new List<EquipmentDTO>();
var res = await _dbContext.Equipments
.Where(w => w.Id == id) try
.AsNoTracking() {
.FirstOrDefaultAsync(); var res = await _dbContext.Equipments.ToListAsync();
if (res != null) if (res != null)
{ {
retVal = _mapper.Map<EquipmentDTO>(res); retVal = _mapper.Map<List<EquipmentDTO>>(res);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex.Message); Log.Error(ex.Message);
} }
return retVal; return retVal;
} }
public async Task<EquipmentDTO> UpdateEquipmentAsync(EquipmentDTO EquipmentDTO) public async Task<EquipmentDTO> GetEquipmentAsync(int id)
{ {
var retVal = new EquipmentDTO(); var retVal = new EquipmentDTO();
try try
{ {
if (EquipmentDTO.Id == 0) //Hozzáadás, ha Id == 0 var res = await _dbContext.Equipments
{ .Where(w => w.Id == id)
var Equipment = _mapper.Map<Equipment>(EquipmentDTO); .AsNoTracking()
_dbContext.Equipments.Add(Equipment); .FirstOrDefaultAsync();
await _dbContext.SaveChangesAsync(); if (res != null)
{
retVal = _mapper.Map<EquipmentDTO>(Equipment); retVal = _mapper.Map<EquipmentDTO>(res);
} }
else }
{ catch (Exception ex)
var res = await _dbContext.Equipments.Where(w => w.Id == EquipmentDTO.Id).FirstOrDefaultAsync(); {
if (res != null) Log.Error(ex.Message);
{ }
res.ShortName = EquipmentDTO.ShortName;
res.EquipmentNumber = EquipmentDTO.EquipmentNumber; return retVal;
}
await _dbContext.SaveChangesAsync(); public async Task<bool> DeleteEquipmentAsync(int id)
{
retVal = _mapper.Map<EquipmentDTO>(res); return await DeleteEntityByIdAsync<Equipment>(id);
} }
} public async Task<EquipmentDTO> UpdateEquipmentAsync(EquipmentDTO EquipmentDTO)
} {
catch (Exception ex) var retVal = new EquipmentDTO();
{
Log.Error(ex.Message); try
} {
if (EquipmentDTO.Id == 0) //Hozzáadás, ha Id == 0
return retVal; {
} var Equipment = _mapper.Map<Equipment>(EquipmentDTO);
public async Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateAsync(int userId) _dbContext.Equipments.Add(Equipment);
{ await _dbContext.SaveChangesAsync();
var retVal = new List<CheckListTemplateHeaderDTO>();
retVal = _mapper.Map<EquipmentDTO>(Equipment);
try }
{ else
var user = _dbContext.Users.Where(w => w.Id == userId).FirstOrDefault(); {
if (user != null) var res = await _dbContext.Equipments.Where(w => w.Id == EquipmentDTO.Id).FirstOrDefaultAsync();
{ if (res != null)
var res = await (from ur in _dbContext.UserRoles {
join rth in _dbContext.RoleCheckListTemplateHeaders on ur.RoleId equals rth.RoleId res.ShortName = EquipmentDTO.ShortName;
join header in _dbContext.CheckListTemplateHeaders on rth.CheckListTemplateHeaderId equals header.Id res.EquipmentNumber = EquipmentDTO.EquipmentNumber;
where ur.UserId == userId
select header) await _dbContext.SaveChangesAsync();
.Include(h => h.CheckListTemplateRows)
.Distinct() retVal = _mapper.Map<EquipmentDTO>(res);
.AsNoTracking() }
.ToListAsync(); }
}
if (res != null) catch (Exception ex)
{ {
retVal = _mapper.Map<List<CheckListTemplateHeaderDTO>>(res); Log.Error(ex.Message);
}
}
} return retVal;
} }
catch (Exception ex)
{ public async Task<List<CheckListTemplateHeaderDTO>> GetAllCheckListTemplateAsync(int userId)
Log.Error(ex.Message); {
} var retVal = new List<CheckListTemplateHeaderDTO>();
return retVal; try
} {
public async Task<List<CheckListHeaderDTO>> GetAllCheckListAsync(int userId) var user = _dbContext.Users.Where(w => w.Id == userId).FirstOrDefault();
{ if (user != null)
var retVal = new List<CheckListHeaderDTO>(); {
var res = await (from ur in _dbContext.UserRoles
try join rth in _dbContext.RoleCheckListTemplateHeaders on ur.RoleId equals rth.RoleId
{ join header in _dbContext.CheckListTemplateHeaders on rth.CheckListTemplateHeaderId equals header.Id
var res = await _dbContext.CheckListHeaders where ur.UserId == userId
.Where(w => w.IsEditable && w.UserId == userId) select header)
.Include(i => i.CheckListRows) .Include(h => h.CheckListTemplateRows)
.AsNoTracking() .Distinct()
.ToListAsync(); .AsNoTracking()
.ToListAsync();
if (res != null)
{ if (res != null)
retVal = _mapper.Map<List<CheckListHeaderDTO>>(res); {
} retVal = _mapper.Map<List<CheckListTemplateHeaderDTO>>(res);
}
catch (Exception ex) }
{ }
Log.Error(ex.Message); }
} catch (Exception ex)
{
return retVal; Log.Error(ex.Message);
} }
} return retVal;
} }
public async Task<List<CheckListHeaderDTO>> GetAllCheckListAsync(int userId)
{
var retVal = new List<CheckListHeaderDTO>();
try
{
var res = await _dbContext.CheckListHeaders
.Where(w => w.CheckStatus == CheckStatus.Open ||
w.CheckStatus == CheckStatus.InProgress ||
w.CheckStatus == CheckStatus.Blocked ||
w.CheckStatus == CheckStatus.Sent)
.Include(i => i.CheckListRows)
//.ThenInclude(i => i.CheckListTemplateRow)
.AsNoTracking()
.ToListAsync();
if (res != null)
{
retVal = _mapper.Map<List<CheckListHeaderDTO>>(res);
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
public async Task<CheckListHeaderDTO> SendCheckListHeaderAsync(CheckListHeaderDTO checkListHeaderDTO)
{
var retVal = new CheckListHeaderDTO();
try
{
if (checkListHeaderDTO.Id > 0)
{
var res = await _dbContext.CheckListHeaders
.Include(i => i.CheckListRows)
.Where(w => w.Id == checkListHeaderDTO.Id)
.FirstOrDefaultAsync();
if (res != null && (res.CheckStatus == CheckStatus.Open ||
res.CheckStatus == CheckStatus.InProgress))
{
var ids = checkListHeaderDTO.CheckListRowDTO?.Select(r => r.Id).ToList();
if (ids != null && ids.Count > 0)
{
var rowsToUpdate = await _dbContext.CheckListRows
.Where(r => ids.Contains(r.Id))
.ToListAsync();
foreach (var row in rowsToUpdate)
{
var dtoRow = checkListHeaderDTO.CheckListRowDTO?.FirstOrDefault(r => r.Id == row.Id);
if (dtoRow != null)
{
row.Answer = dtoRow.Answer;
if (dtoRow.Photo != null && dtoRow.Photo.Length > 0)
{
string imageDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Images");
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var fileName = $"PH_{timestamp}_{row.CheckListHeaderId}_{row.Id}.jpeg";
row.PhotoFileName = fileName;
var filePath = Path.Combine(imageDirectory, fileName);
await File.WriteAllBytesAsync(filePath, dtoRow.Photo);
row.Answer = fileName;
}
}
}
}
await _dbContext.SaveChangesAsync();
retVal = _mapper.Map<CheckListHeaderDTO>(res);
string Answer = "";
if (NeedBlocking(checkListHeaderDTO, out Answer))
{
/// TODO: blokkolás miatt
res.CheckStatus = CheckStatus.Blocked;
await _dbContext.SaveChangesAsync();
Log.ForContext("TAG", "BusinessFlow").Warning($"Ellenőrzési lap blokkolva: Ellenőrzés:{checkListHeaderDTO.Id}, Felhasználó:{_requestContext.CurrentUsername}");
var user = await _userService.GetUserAsync(_requestContext.CurrentUserId ?? 1);
foreach (var item in user.RoleDTO)
{
var deviceMessageDTO = new DeviceMessageDTO()
{
IsReaded = false,
Message = $"Ellenőrző lap blokkolva! [{checkListHeaderDTO.DocumentNumber}]\n({Answer})",
SendDate = DateTime.UtcNow,
ExtraDataJSON = "",
RoleId = item.ParentId,
DeviceIdFrom = "",
DeviceIdTo = "",
};
await this.DeviceMessageSend(deviceMessageDTO);
var fCMMessageDTO = new FCMMessageDTO
{
Body = deviceMessageDTO.Message,
Title = "Blokkolási értesítés",
UserId = user.Id,
};
await _messageService.SendFCMMessageToLastToken(fCMMessageDTO);
}
return retVal;
}
res.CheckStatus = CheckStatus.InProgress;
if (CheckIfLastReached(checkListHeaderDTO))
{
/// TODO: most kell a CheckStatust állítani és menjen üzenet !
res.CheckStatus = CheckStatus.Sent;
Log.ForContext("TAG", "BusinessFlow").Warning($"Ellenőrzési lap státuszváltozása: Ellenőrzés:{checkListHeaderDTO.Id}, Felhasználó:{_requestContext.CurrentUsername}");
}
await _dbContext.SaveChangesAsync();
retVal = _mapper.Map<CheckListHeaderDTO>(res);
}
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
private bool NeedBlocking(CheckListHeaderDTO checkListHeaderDTO, out string Answer)
{
var retVal = false;
Answer = "";
if (checkListHeaderDTO.CheckListRowDTO != null && checkListHeaderDTO.CheckListRowDTO.Count > 0)
{
var checkListRows = checkListHeaderDTO.CheckListRowDTO;
foreach (var row in checkListRows)
{
if (!string.IsNullOrEmpty(row.Answer))
{
if (row.CheckListTemplateRowDTO != null)
{
Answer = row.CheckListTemplateRowDTO.OperationDescription;
if (row.CheckListTemplateRowDTO.AnswerType == "PI-N" && row.Answer == "Igen")
{
retVal = true;
break;
}
if (row.CheckListTemplateRowDTO.AnswerType == "I-PN" && row.Answer == "Nem")
{
retVal = true;
break;
}
}
}
}
}
return retVal;
}
private bool CheckIfLastReached(CheckListHeaderDTO checkListHeaderDTO)
{
var retVal = false;
if (checkListHeaderDTO != null && checkListHeaderDTO.CheckListRowDTO != null && checkListHeaderDTO.CheckListRowDTO.Count > 0)
{
var totalRowCount = checkListHeaderDTO.CheckListRowDTO.Where(w => w.CheckListTemplateRowDTO.AnswerType != "PN" &&
w.CheckListTemplateRowDTO.CheckPointDTO.IsEnabled == true).Count();
var answeredCount = checkListHeaderDTO.CheckListRowDTO.Where(w => w.CheckListTemplateRowDTO.AnswerType != "PN" &&
w.CheckListTemplateRowDTO.CheckPointDTO.IsEnabled == true &&
string.IsNullOrEmpty(w.Answer) != true).Count();
if (totalRowCount == answeredCount) { retVal = true; }
}
return retVal;
}
public async Task<bool> DeviceMessageSend(DeviceMessageDTO deviceMessageDTO)
{
var retVal = false;
try
{
var deviceMessage = _mapper.Map<DeviceMessage>(deviceMessageDTO);
deviceMessage.SendDate = DateTime.UtcNow;
deviceMessage.IsReaded = false;
_dbContext.DeviceMessages.Add(deviceMessage);
await _dbContext.SaveChangesAsync(true);
retVal = true;
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
public async Task<List<DeviceMessageDTO>> DeviceMessageReadUnreaded(string deviceId)
{
var retVal = new List<DeviceMessageDTO>();
try
{
var res = await _dbContext.DeviceMessages
.Where(w => w.DeviceIdTo == deviceId && w.IsReaded != true)
.ToListAsync();
if (res != null)
{
retVal = _mapper.Map<List<DeviceMessageDTO>>(res);
foreach (var deviceMessage in res)
{
deviceMessage.IsReaded = true;
deviceMessage.ReceiveDate = DateTime.UtcNow;
}
await _dbContext.SaveChangesAsync();
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
public async Task<List<DeviceMessageDTO>> DeviceMessageReadUnreadedRole(int roleId)
{
var retVal = new List<DeviceMessageDTO>();
try
{
var res = await _dbContext.DeviceMessages
.Where(w => w.RoleId == roleId && w.IsReaded != true)
.ToListAsync();
if (res != null)
{
retVal = _mapper.Map<List<DeviceMessageDTO>>(res);
foreach (var deviceMessage in res)
{
deviceMessage.IsReaded = true;
deviceMessage.ReceiveDate = DateTime.UtcNow;
}
await _dbContext.SaveChangesAsync();
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return retVal;
}
}
}
@@ -0,0 +1,49 @@
using AutoMapper;
using DocumentFormat.OpenXml.InkML;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.DL;
namespace WorkFlowCheck.BL.Services
{
public class SystemService : ISystemService
{
public readonly AppDbContext _dbContext;
public readonly IMapper _mapper;
public readonly IConfiguration _config;
public SystemService(AppDbContext dbContext,
IMapper mapper,
IConfiguration configuration)
{
_config = configuration;
_dbContext = dbContext;
_mapper = mapper;
}
public async Task<string> GetDatabaseAndVersionInfoAsync()
{
var retVal = "";
var connection = _dbContext.Database.GetDbConnection();
var typeName = connection.GetType().Name;
//if (typeName.Contains("Npgsql"))
//{
// var builder = new NpgsqlConnectionStringBuilder(connection.ConnectionString);
// retVal= builder.Database;
//}
if (typeName.Contains("SqlConnection"))
{
var builder = new SqlConnectionStringBuilder(connection.ConnectionString);
retVal= builder.InitialCatalog;
}
return retVal;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,72 @@
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.BL.Static
{
public static class CodeGenerator2F
{
private static readonly Random _random = new Random();
private const string SecretKey = "874512WcfApplicationNuvolar.hu!%mBX210jUUKL";
private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes(SecretKey);
public static string GenerateSixDigitCode()
{
return _random.Next(100000, 1000000).ToString(); // 100000 - 999999
}
public static string GenerateToken2F(string value1, string value2, string value3)
{
var tokenHandler = new JwtSecurityTokenHandler();
var claims = new[]
{
new Claim("val1", value1),
new Claim("val2", value2),
new Claim("val3", value3)
};
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddSeconds(60 * 60 * 2),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(KeyBytes), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(descriptor);
return tokenHandler.WriteToken(token);
}
public static bool ValidateToken2F(string token, string expected1, string expected2, string expected3)
{
var tokenHandler = new JwtSecurityTokenHandler();
try
{
var parameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(KeyBytes),
ClockSkew = TimeSpan.Zero // nincs türelmi idő
};
var principal = tokenHandler.ValidateToken(token, parameters, out var validatedToken);
var val1 = principal.FindFirst("val1")?.Value;
var val2 = principal.FindFirst("val2")?.Value;
var val3 = principal.FindFirst("val3")?.Value;
return val1 == expected1 && val2 == expected2 && val3 == expected3;
}
catch
{
return false;
}
}
}
}
+35 -19
View File
@@ -1,19 +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>
<PackageReference Include="AutoMapper" Version="13.0.1" /> <None Remove="HtmlTemplates\Token2FBody.html" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" /> </ItemGroup>
</ItemGroup>
<ItemGroup>
<ItemGroup> <EmbeddedResource Include="HtmlTemplates\AcceptCheckListHeaderBody.html" />
<ProjectReference Include="..\WorkFlowCheck.Common\WorkFlowCheck.Common.csproj" /> <EmbeddedResource Include="HtmlTemplates\Token2FBody.html" />
<ProjectReference Include="..\WorkFlowCheck.DL\WorkFlowCheck.DL.csproj" /> </ItemGroup>
</ItemGroup>
<ItemGroup>
</Project> <PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Google.Apis.Auth" Version="1.69.0" />
<PackageReference Include="MailKit" Version="4.11.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WorkFlowCheck.Common\WorkFlowCheck.Common.csproj" />
<ProjectReference Include="..\WorkFlowCheck.DL\WorkFlowCheck.DL.csproj" />
</ItemGroup>
</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; }
}
}
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class CheckListHeaderCloseDTO
{
public int Id { get; set; }
public string CloseReason { get; set; } = null!;
public int UserId { get; set; }
}
}
@@ -1,30 +1,59 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.ComponentModel;
using System.Text; using System.Linq;
using System.Threading.Tasks; using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO using WorkFlowCheck.Common.Enums;
{ using WorkFlowCheck.Common.Helper;
public class CheckListHeaderDTO
{ namespace WorkFlowCheck.Common.DTO
public int Id { get; set; } {
public int CheckListTemplateHeaderId { get; set; } public class CheckListHeaderDTO
public CheckListTemplateHeaderDTO CheckListTemplateHeaderDTO { get; set; } {
public DateTime DateExecution { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int CheckListTemplateHeaderId { get; set; }
public UserDTO UserDTO { get; set; } public CheckListTemplateHeaderDTO? CheckListTemplateHeaderDTO { get; set; }
public string ShortName { get; set; } = null!;
public string Description { get; set; } = null!; [DisplayName("Státusz")]
public string DocumentNumber { get; set; } = null!; public CheckStatus CheckStatus { get; set; }
public Guid GuidNumber { get; set; }
public bool IsStorno { get; set; } public string StatusName => DisplayNameHelper.GetEnumDisplayName(CheckStatus);
public bool IsEditable { get; set; }
public required ICollection<CheckListRowDTO> CheckListRowDTO { get; set; } = new List<CheckListRowDTO>(); [DisplayName("Dátum")]
public DateTime DateExecution { get; set; }
public CheckListHeaderDTO()
{ [DisplayName("Ellenőrző")]
CheckListRowDTO = new List<CheckListRowDTO>(); public int UserId { get; set; }
} public UserDTO? UserDTO { get; set; }
}
} [DisplayName("Jóváhagyó")]
public int? AcceptUserId { get; set; }
public UserDTO? AcceptUserDTO { get; set; }
[DisplayName("Megnevezés")]
public string ShortName { get; set; } = null!;
[DisplayName("Leírás")]
public string Description { get; set; } = null!;
[DisplayName("Sorszám")]
public string DocumentNumber { get; set; } = null!;
[DisplayName("Azonosító")]
public Guid GuidNumber { get; set; }
[DisplayName("Stornózva")]
public bool IsStorno { get; set; }
[DisplayName("Szerkeszthető")]
public bool IsEditable { get; set; }
public ICollection<CheckListRowDTO>? CheckListRowDTO { get; set; } = new List<CheckListRowDTO>();
public CheckListHeaderDTO()
{
CheckListRowDTO = new List<CheckListRowDTO>();
}
}
}
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class CheckListHeaderInfoDTO
{
public int Id { get; set; }
[DisplayName("Összes ellenőrzési szám")]
public int TotalRowCount { get; set; }
[DisplayName("Még ellenőrizendő száma")]
public int EmptyAnswerCount { get; set; }
[DisplayName("Készültség %")]
public string ReadyPercent { get; set; }
[DisplayName("Ellenőrzési pontok száma")]
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 -22
View File
@@ -1,22 +1,29 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.ComponentModel;
using System.Text; using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks; using System.Linq;
using System.Text;
namespace WorkFlowCheck.Common.DTO using System.Threading.Tasks;
{
public class CheckListRowDTO namespace WorkFlowCheck.Common.DTO
{ {
public int Id { get; set; } public class CheckListRowDTO
public int CheckListHeaderId { get; set; } {
public int CheckListTemplateRowId { get; set; } public int Id { get; set; }
public CheckListTemplateRowDTO CheckListTemplateRowDTO { get; set; } public int CheckListHeaderId { get; set; }
public string GroupName => $"AnswerGroup_{CheckListTemplateRowDTO.RowIndex}"; public int CheckListTemplateRowId { get; set; }
public string Answer { get; set; } = null!; public CheckListTemplateRowDTO? CheckListTemplateRowDTO { get; set; }
public bool? AnswerYes { get; set; } = null!; public string GroupName => $"AnswerGroup_{CheckListTemplateRowDTO?.Id ?? 0}";
public bool? AnswerNo { get; set; } = null!;
public byte[] Photo { get; set; } = null!; [DisplayName("Eredmény")]
public Guid GuidNumber { get; set; } public string Answer { get; set; } = null!;
}
} public bool? AnswerYes { get; set; } = null!;
public bool? AnswerNo { get; set; } = null!;
[DisplayName("Kép")]
public byte[]? Photo { get; set; } = null!;
public Guid GuidNumber { get; set; }
}
}
@@ -1,13 +1,22 @@
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel;
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 string ShortName { get; set; } = null!; public int Id { get; set; }
public string Description { get; set; } = null!; [DisplayName("Megnevezés")]
public string ShortName { get; set; } = null!;
public required ICollection<CheckListTemplateRowDTO> CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>(); [DisplayName("Leírás")]
} public string Description { get; set; } = null!;
} [DisplayName("Sorszám (munkalap)")]
public int? NumberGenerator1Id { get; set; }
[DisplayName("Sorszám (dokumentum)")]
public int? NumberGenerator2Id { get; set; }
public NumberGeneratorTemplateDTO? NumberGenerator1 { get; set; }
public NumberGeneratorTemplateDTO? NumberGenerator2 { get; set; }
public ICollection<CheckListTemplateRowDTO>? CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>();
}
}
@@ -1,34 +1,43 @@
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace WorkFlowCheck.Common.DTO using System.ComponentModel.DataAnnotations.Schema;
{
public class CheckListTemplateRowDTO namespace WorkFlowCheck.Common.DTO
{ {
public int Id { get; set; } public class CheckListTemplateRowDTO
public int RowIndex { get; set; } {
public int CheckListTemplateHeaderId { get; set; } public int Id { get; set; }
public int EquipmentId { get; set; } [Required(ErrorMessage = "A sorrend megadása kötelező.")]
public EquipmentDTO? EquipmentDTO { get; set; } = null!; [DisplayName("Sorrend")]
public int RowIndex { get; set; }
public int CheckPointId { get; set; } public int CheckListTemplateHeaderId { get; set; }
public CheckPointDTO? CheckPointDTO { get; set; } = null!;
[DisplayName("Berendezés")]
public string OperationDescription { get; set; } = null!; public int EquipmentId { get; set; }
public EquipmentDTO? EquipmentDTO { get; set; } = null!;
/// <summary>
/// public int CheckPointId { get; set; }
/// I-N (Igen, nem) public CheckPointDTO? CheckPointDTO { get; set; } = null!;
/// P (Fénykép készítése)
/// SI-N (Sárga igen,fehér nem) [DisplayName("Tevékenység leírása")]
/// I-SN (Fehér igen, sárga nem) public string OperationDescription { get; set; } = null!;
/// PI-N (Piros igen,fehér nem)
/// I-PN (Fehér igen, piros nem) /// <summary>
/// V (Érték megadása) ///
/// /// I-N (Igen, nem)
/// </summary> /// P (Fénykép készítése)
public string AnswerType { get; set; } = null!; /// PN (Fénykép nem kötelező készítése)
/// SI-N (Sárga igen,fehér nem)
/// I-SN (Fehér igen, sárga nem)
} /// PI-N (Piros igen,fehér nem)
} /// I-PN (Fehér igen, piros nem)
/// V (Érték megadása)
///
/// </summary>
[DisplayName("Válasz tipus")]
public string AnswerType { get; set; } = null!;
}
}
+31 -11
View File
@@ -1,11 +1,31 @@
namespace WorkFlowCheck.Common.DTO using System.ComponentModel.DataAnnotations;
{ using System.ComponentModel;
public class CheckPointDTO
{ namespace WorkFlowCheck.Common.DTO
public int Id { get; set; } {
public string ShortName { get; set; } public class CheckPointDTO
public string Code { get; set; } {
public List<CheckListTemplateRowDTO> CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>(); public int Id { get; set; }
}
} [Required(ErrorMessage = "A megnevezés megadása kötelező.")]
[DisplayName("Megnevezés")]
public string ShortName { get; set; }
[Required(ErrorMessage = "A kód megadása kötelező.")]
[DisplayName("Kód")]
public string Code { get; set; }
[DisplayName("Használatban")]
public bool IsEnabled { get; set; }
[DisplayName("Szabály")]
public int? RoleId { get; set; }
[DisplayName("Szabály neve")]
public string? RoleName { get; set; }
public List<CheckListTemplateRowDTO>? CheckListTemplateRowDTO { get; set; } = new List<CheckListTemplateRowDTO>();
}
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class DeviceMessageDTO
{
public int Id { get; set; }
public DateTime? SendDate { get; set; }
public DateTime? ReceiveDate { get; set; }
public string DeviceIdFrom { get; set; } = null!;
public string DeviceIdTo { get; set; } = null!;
public string Message { get; set; } = null!;
public string ExtraDataJSON { get; set; } = null!;
public bool IsReaded { get; set; }
public int? RoleId { get; set; }
public RoleDTO? RoleDTO { get; set; }
}
}
+23 -15
View File
@@ -1,15 +1,23 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.ComponentModel;
using System.Text; using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks; using System.Linq;
using System.Text;
namespace WorkFlowCheck.Common.DTO using System.Threading.Tasks;
{
public class EquipmentDTO namespace WorkFlowCheck.Common.DTO
{ {
public int Id { get; set; } public class EquipmentDTO
public string ShortName { get; set; } = null!; {
public string EquipmentNumber { get; set; } = null!; public int Id { get; set; }
}
} [Required(ErrorMessage = "A megnevezést megadása kötelező.")]
[DisplayName("Megnevezés")]
public string ShortName { get; set; } = null!;
[Required(ErrorMessage = "Az azonosító megadása kötelező.")]
[DisplayName("Azonosító")]
public string EquipmentNumber { get; set; } = null!;
}
}
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class FCMMessageDTO
{
public string? Token { get; set; }
public string? Body { get; set; }
public string? Title { get; set; }
public int? UserId { get; set; }
}
}
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class ImageFileDTO
{
public string Id { get; set; }
public string FileName { get; set; }
public string FileSize { get; set; }
public string CreateDate { get; set; }
}
}
+19 -14
View File
@@ -1,14 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.ComponentModel;
using System.Text; using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks; using System.Linq;
using System.Text;
namespace WorkFlowCheck.Common.DTO using System.Threading.Tasks;
{
public class LocationDTO namespace WorkFlowCheck.Common.DTO
{ {
public int Id { get; set; } public class LocationDTO
public string FullName { get; set; } = null!; {
} public int Id { get; set; }
}
[Required(ErrorMessage = "A megnevezést megadása kötelező.")]
[DisplayName("Megnevezés")]
public string FullName { get; set; } = null!;
}
}
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class LogFileDTO
{
public string Id { get; set; }
public string FileName { get; set; }
public string FileSize { get; set; }
public string CreateDate { get; set; }
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class MobileUserDTO
{
public int Id { get; set; }
public string? UserName { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? FullName => $"{LastName} {FirstName}";
public string? Email { get; set; }
public bool NFCActive { get; set; }
public string NFCCode { get; set; } = null!;
}
}
@@ -1,12 +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 string ShortName { get; set; }
public string Sample { get; set; }
}
}
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class PDFFileDTO
{
public string Id { get; set; }
public string FileName { get; set; }
public string FileSize { get; set; }
public string CreateDate { get; set; }
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class RoleCheckListTemplateHeaderDTO
{
public int Id { get; set; }
[Required(ErrorMessage = "A szabály megnevezésének megadása kötelező.")]
[DisplayName("Szabály")]
public int RoleId { get; set; }
public RoleDTO? RoleDTO { get; set; } = null!;
[Required(ErrorMessage = "Az ellenőrzési sablon megadása kötelező.")]
[DisplayName("Ellenőrzési sablon")]
public int CheckListTemplateHeaderId { get; set; }
public CheckListTemplateHeaderDTO? CheckListTemplateHeaderDTO { get; set; } = null!;
[DisplayName("Engedélyezve?")]
public bool Enabled { get; set; } = false;
}
}
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class RoleCheckPointDTO
{
public int Id { get; set; }
[Required(ErrorMessage = "A szabály megadása kötelező.")]
[DisplayName("Szabály")]
public int RoleId { get; set; }
public RoleDTO? RoleDTO { get; set; } = null!;
[Required(ErrorMessage = "Az ellenőrzési pont megadása kötelező.")]
[DisplayName("Ellenőrzési pont")]
public int CheckPointId { get; set; }
public CheckPointDTO? CheckPointDTO { get; set; } = null!;
[DisplayName("Engedélyezve?")]
public bool Enabled { get; set; } = false;
}
}
+35 -8
View File
@@ -1,8 +1,35 @@
namespace WorkFlowCheck.Common.DTO using System.ComponentModel.DataAnnotations;
{ using System.ComponentModel;
public class RoleDTO
{ namespace WorkFlowCheck.Common.DTO
public int Id { get; set; } {
public string RoleName { get; set; } = null!; public class RoleDTO
} {
} public int Id { get; set; }
[Required(ErrorMessage = "A szabály megnevezésének megadása kötelező.")]
[DisplayName("Megnevezés")]
public string RoleName { get; set; } = null!;
public int? ParentId { get; set; }
[DisplayName("Szülő szerepkör neve")]
public string? ParentRoleName { get; set; }
[DisplayName("Adminisztrátor?")]
public bool IsAdmin { get; set; }
[DisplayName("Új program letöltés?")]
public bool CanDownloadAPK { get; set; }
[DisplayName("Folyamat blokk/engedélyez?")]
public bool CanEnableBlocked { get; set; }
[DisplayName("WEB felület?")]
public bool CanUseWebAdmin { get; set; }
[DisplayName("Mobil App?")]
public bool CanUseMobilApp { get; set; }
}
}
+17 -15
View File
@@ -1,15 +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 int Id { get; set; }
public string UserName { get; set; } = null!; public string UserName { get; set; } = null!;
public string Token2FA { get; set; } = null!; public string Password { get; set; } = null!;
} public string Code { get; set; } = null!;
} public string Token2FA { get; set; } = null!;
}
}
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.DTO
{
public class UserChangePassword2FADTO
{
public int UserId { get; set; }
[DisplayName("Felhasználó")]
public string UserName { get; set; } = null!;
[DisplayName("Régi jelszó")]
public string OldPassword { get; set; } = null!;
[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.")]
[DisplayName("Új jelszó")]
public string NewPassword1 { get; set; } = null!;
[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.")]
[DisplayName("Jelszó megerősítése")]
public string NewPassword2 { get; set; } = null!;
[DisplayName("Ellenőrző kód")]
public string Code { get; set; } = null!;
public string Token2FA { get; set; } = null!;
}
}
+47 -19
View File
@@ -1,19 +1,47 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace WorkFlowCheck.Common.DTO
{ namespace WorkFlowCheck.Common.DTO
public class UserDTO {
{ public class UserDTO
public int Id { get; set; } {
public string Email { get; set; } = null!; public int Id { get; set; }
[Required(ErrorMessage = "Az utónév kötelező.")]
public string FirstName { get; set; } = null!; [Required(ErrorMessage = "Az utónév kötelező.")]
[Required(ErrorMessage = "Az vezetéknév kötelező.")] [EmailAddress(ErrorMessage = "Érvénytelen email cím.")]
public string LastName { get; set; } = null!; [RegularExpression(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", ErrorMessage = "Az email formátum nem megfelelő.")]
[Required(ErrorMessage = "A felhasználónév kötelező.")] [DisplayName("E-mail")]
public string UserName { get;set; } = null!; public string Email { get; set; } = null!;
public string Password { get; set; }
public string JwtToken { get; set; } = null!; [Required(ErrorMessage = "Az utónév kötelező.")]
public required ICollection<RoleDTO> RoleDTO { get; set; } = new List<RoleDTO>(); [DisplayName("Utónév")]
} public string FirstName { get; set; } = null!;
}
[Required(ErrorMessage = "Az vezetéknév kötelező.")]
[DisplayName("Vezetéknév")]
public string LastName { get; set; } = null!;
[Required(ErrorMessage = "A felhasználónév kötelező.")]
[DisplayName("Felhasználó neve")]
public string UserName { get;set; } = null!;
[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.")]
[DisplayName("Jelszó")]
public string Password { get; set; } = null!;
public string JwtToken { get; set; } = null!;
[DisplayName("Aktív")]
public bool Active { get; set; }
[DisplayName("NFC belépés")]
public bool NFCActive { get; set; }
[DisplayName("NFC kód")]
public string NFCCode { get; set; } = null!;
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; } }
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace WorkFlowCheck.Common.Enums
{
public enum CheckStatus
{
[Display(Name = "Nyitott")]
Open = 0,
[Display(Name = "Folyamatban")]
InProgress = 1,
[Display(Name = "Blokkolt")]
Blocked = 2,
[Display(Name = "Sztornózva")]
Storno = 3,
[Display(Name = "Beküldött")]
Sent = 4,
[Display(Name = "Jóváhagyva")]
Signed = 5,
[Display(Name = "Lezárva")]
Closed = 6
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.Common.Helper
{
public static class DisplayNameHelper
{
public static string GetDisplayName(string propertyName, Type modelType)
{
var property = modelType.GetProperty(propertyName);
var displayNameAttribute = property?.GetCustomAttributes(typeof(DisplayNameAttribute), false)
.FirstOrDefault() as DisplayNameAttribute;
return displayNameAttribute?.DisplayName ?? propertyName;
}
public static string GetEnumDisplayName(this Enum enumValue)
{
return enumValue
.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()?
.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 -194
View File
@@ -1,194 +1,191 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.ChangeTracking;
using System; using System;
using System.Collections.Generic; using WorkFlowCheck.Common.RequestContext;
using System.Linq; using WorkFlowCheck.Common.Security;
using System.Text; using WorkFlowCheck.DL.Configurations;
using System.Threading.Tasks; using WorkFlowCheck.DL.Entities;
using WorkFlowCheck.Common.RequestContext; using WorkFlowCheck.DL.Extensions;
using WorkFlowCheck.Common.Security; using WorkFlowCheck.DL.Interfaces;
using WorkFlowCheck.DL.Configurations;
using WorkFlowCheck.DL.Entities; namespace WorkFlowCheck.DL
using WorkFlowCheck.DL.Extensions; {
using WorkFlowCheck.DL.Interfaces; public class AppDbContext : DbContext
{
namespace WorkFlowCheck.DL private readonly IRequestContext _requestContext;
{ public AppDbContext(DbContextOptions<AppDbContext> options, IRequestContext requestContext)
public class AppDbContext : DbContext : base(options)
{ {
private readonly IRequestContext _requestContext; _requestContext = requestContext;
public AppDbContext(DbContextOptions<AppDbContext> options, IRequestContext requestContext) }
: base(options)
{ #region Entities DbSet
_requestContext = requestContext; public DbSet<Entities.CheckListHeader> CheckListHeaders { get; set; } = null!;
} public DbSet<Entities.CheckListRow> CheckListRows { get; set; } = null!;
public DbSet<Entities.CheckListTemplateHeader> CheckListTemplateHeaders { get; set; } = null!;
#if !DEBUG public DbSet<Entities.CheckListTemplateRow> CheckListTemplateRows { get; set; } = null!;
private dynamic _requestContext; public DbSet<Entities.CheckPoint> CheckPoints { get; set; } = null!;
public AppDbContext(DbContextOptions<AppDbContext> options) public DbSet<DeviceMessage> DeviceMessages { get; set; } = null!;
: base(options) public DbSet<Entities.Equipment> Equipments { get; set; } = null!;
{ public DbSet<Entities.FCMToken> FCMTokens { get; set; } = null!;
_requestContext = new { CurrentUserEmail = "", CurrentUsername = "admin", TraceId = 0 }; public DbSet<Entities.Location> Locations { get; set; } = null!;
} public DbSet<Entities.NumberGeneratorTemplate> NumberGeneratorTemplates { get; set; } = null!;
#endif public DbSet<Entities.NumberGeneratorTemplateDate> NumberGeneratorTemplateDates { get; set; } = null!;
#region Entities DbSet public DbSet<Entities.Role> Roles { get; set; } = null!;
public DbSet<Entities.CheckListHeader> CheckListHeaders { get; set; } = null!; public DbSet<Entities.User> Users { get; set; } = null!;
public DbSet<Entities.CheckListRow> CheckListRows { get; set; } = null!; public DbSet<Entities.UserRole> UserRoles { get; set; } = null!;
public DbSet<Entities.CheckListTemplateHeader> CheckListTemplateHeaders { get; set; } = null!; public DbSet<Entities.RoleCheckListTemplateHeader> RoleCheckListTemplateHeaders { get; set; } = null!;
public DbSet<Entities.CheckListTemplateRow> CheckListTemplateRows { get; set; } = null!; public DbSet<Entities.RoleCheckPoint> RoleCheckPoints { get; set; } = null!;
public DbSet<Entities.CheckPoint> CheckPoints { get; set; } = null!; #endregion
public DbSet<Entities.Equipment> Equipments { get; set; } = null!;
public DbSet<Entities.Location> Locations { get; set; } = null!;
public DbSet<Entities.NumberGeneratorTemplate> NumberGeneratorTemplates { get; set; } = null!;
public DbSet<Entities.NumberGeneratorTemplateDate> NumberGeneratorTemplateDatess { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder)
public DbSet<Entities.Role> Roles { get; set; } = null!; {
public DbSet<Entities.User> Users { get; set; } = null!; modelBuilder.ApplyConfiguration(new CheckListHeaderTypeConfiguration());
public DbSet<Entities.UserRole> UserRoles { get; set; } = null!; modelBuilder.ApplyConfiguration(new CheckListRowTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListTemplateHeaderTypeConfiguration());
public DbSet<Entities.RoleCheckListTemplateHeader> RoleCheckListTemplateHeaders { get; set; } = null!; modelBuilder.ApplyConfiguration(new CheckListTemplateRowTypeConfiguration());
#endregion modelBuilder.ApplyConfiguration(new CheckPointTypeConfiguration());
modelBuilder.ApplyConfiguration(new DeviceMessageTypeConfiguration());
modelBuilder.ApplyConfiguration(new EquipmentTypeConfiguration());
modelBuilder.ApplyConfiguration(new FCMTokenTypeConfiguration());
protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new LocationTypeConfiguration());
{ modelBuilder.ApplyConfiguration(new NumberGeneratorTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListHeaderTypeConfiguration()); modelBuilder.ApplyConfiguration(new NumberGeneratorDateTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListRowTypeConfiguration()); modelBuilder.ApplyConfiguration(new RoleTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListTemplateHeaderTypeConfiguration()); modelBuilder.ApplyConfiguration(new RoleCheckListTemplateHeaderTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckListTemplateRowTypeConfiguration()); modelBuilder.ApplyConfiguration(new RoleCheckPointTypeConfiguration());
modelBuilder.ApplyConfiguration(new CheckPointTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserTypeConfiguration());
modelBuilder.ApplyConfiguration(new EquipmentTypeConfiguration()); modelBuilder.ApplyConfiguration(new UserRoleTypeConfiguration());
modelBuilder.ApplyConfiguration(new LocationTypeConfiguration());
modelBuilder.ApplyConfiguration(new NumberGeneratorTypeConfiguration());
modelBuilder.ApplyConfiguration(new NumberGeneratorDateTypeConfiguration()); modelBuilder.RegisterSoftDeleteQueryFilters();
modelBuilder.ApplyConfiguration(new RoleTypeConfiguration());
modelBuilder.ApplyConfiguration(new RoleCheckListTemplateHeaderTypeConfiguration()); SeedInit(modelBuilder);
modelBuilder.ApplyConfiguration(new UserTypeConfiguration()); }
modelBuilder.ApplyConfiguration(new UserRoleTypeConfiguration()); public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
SaveChangesCore();
modelBuilder.RegisterSoftDeleteQueryFilters(); return await base.SaveChangesAsync(cancellationToken);
}
SeedInit(modelBuilder); protected virtual void SaveChangesCore()
} {
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) var utcNow = DateTime.UtcNow;
{
SaveChangesCore(); var deletedEntries = ChangeTracker
return await base.SaveChangesAsync(cancellationToken); .Entries()
} .Where(e => e.Entity is ISoftDeletableEntity && e.State == EntityState.Deleted);
protected virtual void SaveChangesCore()
{ UpdateDeletedEntries(deletedEntries);
var utcNow = DateTime.UtcNow;
var modifiedEntries = ChangeTracker
var deletedEntries = ChangeTracker .Entries()
.Entries() .Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Modified);
.Where(e => e.Entity is ISoftDeletableEntity && e.State == EntityState.Deleted);
UpdateModifiedEntires(modifiedEntries, utcNow);
UpdateDeletedEntries(deletedEntries);
var addedEntries = ChangeTracker
var modifiedEntries = ChangeTracker .Entries()
.Entries() .Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Added);
.Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Modified);
UpdateAddedEntries(addedEntries, utcNow);
UpdateModifiedEntires(modifiedEntries, utcNow); }
private void UpdateAddedEntries(IEnumerable<EntityEntry> addedEntries, DateTime utcNow)
var addedEntries = ChangeTracker {
.Entries() foreach (var entry in addedEntries)
.Where(e => e.Entity is IAuditableEntity && e.State == EntityState.Added); {
((IAuditableEntity)entry.Entity).CreatedAt = utcNow;
UpdateAddedEntries(addedEntries, utcNow); ((IAuditableEntity)entry.Entity).LastModAt = utcNow;
} ((IAuditableEntity)entry.Entity).CreatedBy = _requestContext.CurrentUsername ?? "Admin";
private void UpdateAddedEntries(IEnumerable<EntityEntry> addedEntries, DateTime utcNow) ((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin";
{ }
foreach (var entry in addedEntries) }
{ private void UpdateModifiedEntires(IEnumerable<EntityEntry> modifiedEntries, DateTime utcNow)
((IAuditableEntity)entry.Entity).CreatedAt = utcNow; {
((IAuditableEntity)entry.Entity).LastModAt = utcNow; foreach (var entry in modifiedEntries)
((IAuditableEntity)entry.Entity).CreatedBy = _requestContext.CurrentUsername ?? "Admin"; {
((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin"; ((IAuditableEntity)entry.Entity).LastModAt = utcNow;
} ((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin";
} }
private void UpdateModifiedEntires(IEnumerable<EntityEntry> modifiedEntries, DateTime utcNow) }
{ private void UpdateDeletedEntries(IEnumerable<EntityEntry> deletedEntries)
foreach (var entry in modifiedEntries) {
{ foreach (var entry in deletedEntries)
((IAuditableEntity)entry.Entity).LastModAt = utcNow; {
((IAuditableEntity)entry.Entity).LastModBy = _requestContext.CurrentUsername ?? "Admin"; ((ISoftDeletableEntity)entry.Entity).IsDeleted = true;
} entry.State = EntityState.Modified;
} }
private void UpdateDeletedEntries(IEnumerable<EntityEntry> deletedEntries) }
{
foreach (var entry in deletedEntries) private void SeedInit(ModelBuilder modelBuilder)
{ {
((ISoftDeletableEntity)entry.Entity).IsDeleted = true; modelBuilder.Entity<User>().HasData(
entry.State = EntityState.Modified; new User
} {
} Id = 1,
Email = "admin@nuvolar.hu",
private void SeedInit(ModelBuilder modelBuilder) FirstName = "Administrator",
{ LastName = "System",
modelBuilder.Entity<User>().HasData( IsDeleted = false,
new User UserName = "admin",
{ PasswordHash = PasswordHasher.HashPassword("111111"),
Id = 1, CreatedAt = DateTime.UtcNow,
Email = "admin@nuvolar.hu", CreatedBy = "System",
FirstName = "Administrator", LastModAt = DateTime.UtcNow,
LastName = "System", LastModBy = "System",
IsDeleted = false, JwtToken = "",
UserName = "admin", Active = true,
PasswordHash = PasswordHasher.HashPassword("111111"), Token2FA = "",
CreatedAt = DateTime.UtcNow, NFCActive = true,
CreatedBy = "System", NFCCode = "00000000"
LastModAt = DateTime.UtcNow, },
LastModBy = "System", new User
JwtToken = "", {
Active = true, Id = 2,
Token2FA = "" Email = "user@nuvolar.hu",
}, FirstName = "User",
new User LastName = "System",
{ IsDeleted = false,
Id = 2, UserName = "user",
Email = "user@nuvolar.hu", PasswordHash = PasswordHasher.HashPassword("222222"),
FirstName = "User", CreatedAt = DateTime.UtcNow,
LastName = "System", CreatedBy = "System",
IsDeleted = false, LastModAt = DateTime.UtcNow,
UserName = "user", LastModBy = "System",
PasswordHash = PasswordHasher.HashPassword("222222"), JwtToken = "",
CreatedAt = DateTime.UtcNow, Active = true,
CreatedBy = "System", Token2FA = "",
LastModAt = DateTime.UtcNow, NFCActive = true,
LastModBy = "System", NFCCode = "00000000"
JwtToken = "", }
Active = true, );
Token2FA = "" modelBuilder.Entity<NumberGeneratorTemplate>().HasData(
} new NumberGeneratorTemplate
); {
modelBuilder.Entity<NumberGeneratorTemplate>().HasData( Id = 1,
new NumberGeneratorTemplate CurrentNumber = 0,
{ DigitFormat = "D4",
Id = 1, GenerateType = GenerateType.OnlyYear,
CurrentNumber = 0, LastGeneratedNumber = "",
DigitFormat = "D4", Prefix = "CHK",
GenerateType = GenerateType.OnlyYear, PrefixSeparator = "-",
LastGeneratedNumber = "", ShortName = "Ellenőrzési dokumentum sorszámozása",
Prefix = "CHK", Suffix = "",
PrefixSeparator = "-", SuffixSeparator = "-",
ShortName = "Ellenőrzési dokumentum sorszámozása", }
Suffix = "", );
SuffixSeparator = "-", modelBuilder.Entity<NumberGeneratorTemplateDate>().HasData(
} new NumberGeneratorTemplateDate
); {
modelBuilder.Entity<NumberGeneratorTemplateDate>().HasData( Id = 1,
new NumberGeneratorTemplateDate CurrentNumber = 0,
{ LastGeneratedNumber = "",
Id = 1, Month = 0,
CurrentNumber = 0, Year = 1,
LastGeneratedNumber = "", NumberGeneratorTemplateId = 1,
Month = 0, }
Year = 1, );
NumberGeneratorTemplateId = 1, }
} }
); }
}
}
}
@@ -1,21 +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.Text; using System.Reflection.Emit;
using System.Threading.Tasks; using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations using WorkFlowCheck.DL.Entities;
{
public class CheckListHeaderTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListHeader> namespace WorkFlowCheck.DL.Configurations
{ {
public void Configure(EntityTypeBuilder<Entities.CheckListHeader> builder) public class CheckListHeaderTypeConfiguration : IEntityTypeConfiguration<Entities.CheckListHeader>
{ {
builder.ToTable("CheckListHeader"); public void Configure(EntityTypeBuilder<Entities.CheckListHeader> builder)
builder.HasKey(e => e.Id); {
builder.Property(e => e.Id).ValueGeneratedOnAdd(); builder.ToTable("CheckListHeader");
} builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd();
} builder
} .HasOne(ch => ch.AcceptUser)
.WithMany()
.HasForeignKey(ch => ch.AcceptUserId)
.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();
} }
} }
} }
@@ -0,0 +1,24 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations
{
public class DeviceMessageTypeConfiguration : IEntityTypeConfiguration<Entities.DeviceMessage>
{
public void Configure(EntityTypeBuilder<Entities.DeviceMessage> builder)
{
builder.ToTable("DeviceMessage");
builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd();
builder.HasIndex(e => e.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();
} }
} }
} }
@@ -0,0 +1,21 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorkFlowCheck.DL.Configurations
{
public class FCMTokenTypeConfiguration : IEntityTypeConfiguration<Entities.FCMToken>
{
public void Configure(EntityTypeBuilder<Entities.FCMToken> builder)
{
builder.ToTable("FCMToken");
builder.HasKey(e => e.Id);
builder.Property(e => e.Id).ValueGeneratedOnAdd();
}
}
}

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