Compare commits

...

233 Commits

Author SHA1 Message Date
NottarJohnny 97e1ce5be4 Rectifications
continuous-integration/drone/push Build is failing Details
10 months ago
Clement CHIEU 5a4f97489d Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 656af96aca Migrations supprimées du coverage
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 2386dfd275 Merge pull request 'Controller modifié mais bug avec test unitaires en local' (#51) from modifGameController into master
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 3568fa86f7 Merge branch 'modifGameController' of codefirst.iut.uca.fr:johnny.ratton/API_SQLuedo into modifGameController
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 8965ed2dcb Modification du format de renvoi pour les tables et les colonnes
1 year ago
Johnny RATTON cbbcfa030a Merge branch 'master' into modifGameController
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 18b35ae3a5 Controller modifié mais bug avec test unitaires en local
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 203c3962b1 Merge pull request 'deploiement' (#50) from deploiement into master
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 3ba6b0c521 Merge resolved
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 6843d969e5 Suppression du authorize pour test
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU f2c3791778 Merge branch 'deploiement' of codefirst.iut.uca.fr:johnny.ratton/API_SQLuedo into deploiement
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 1aafe248cd Nouvelle migration de test
1 year ago
Clement CHIEU 2c802739b0 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU a15752d650 Ajout nouvelle migration
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 3a6693646c Ajout des bonnes routes des controller
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 037d3c5d7d Suppression de la route de test du controller
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU a4f75d948a Ajout pour migrer vers la base de données
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 0f0615c5a2 Ajout migrations
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU edc2e1055c Mise à jour de '.gitignore'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU ad41f1dd41 Ajout de la connection string pour le développement
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU b5db7d32d3 Merge branch 'deploiement' of codefirst.iut.uca.fr:johnny.ratton/API_SQLuedo into deploiement
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU c95dc22881 Ajout des bonnes variables d'environnement
1 year ago
Clement CHIEU c0763ae9a9 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 570f89b4e3 Ajout de l'utilisation de la variable d'environnement au moment de la création de l'api
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 1ec09bdedf Modification du context utilisé
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 0e1f873c9f Vérification production
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 509b0d7565 Vérification production
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 9b30ed1234 Mise à jour de 'API_SQLuedo/API/Dockerfile'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 590fa7d629 Mise à jour de 'API_SQLuedo/API/Dockerfile'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 951ba2c941 Mise à jour de 'API_SQLuedo/API/Program.cs'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 06640b6530 Mise à jour de 'API_SQLuedo/API/Properties/launchSettings.json'
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 5bcfae1b17 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 2ea38ae774 Merge branch 'QueryController'
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 1f7cba0b22 Correction d'un security review (Username et password en clean dans le code)
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 8b1f2280bc 80 %?
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS f025be2bd0 Ajout de tests et tentative de Mock une ArgumentException
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS b19801a21c Ajout de quelques test pour le coverage à cause du QueryController
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS bfa15606f7 Suppression du test c'était nul
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS a10242ce28 Test pas sur la c'est du docker (ChatGPT)
continuous-integration/drone/push Build is failing Details
1 year ago
Maxime SAPOUNTZIS 8349f43f8a Fin des TU sur le QueryController
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS fd18a3e099 Début test Controller et suppression des test service car impossible
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 6c7970fda7 Début Tests Unitaires sur le QueryService
continuous-integration/drone/push Build is failing Details
1 year ago
Johnny RATTON 18e7df02f3 Ajout des test unitaires pour les nouveaux controller et services
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 0161832d9e Ajout de getTables et getColumns pour le queryController
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 08bdb01b18 Merge branch 'master' of codefirst.iut.uca.fr:johnny.ratton/API_SQLuedo
1 year ago
Johnny RATTON f9f98e5705 Ajout des controller notepad, solution et des services associés + modification des controllers et services actuels pour se conformer au site PHP
1 year ago
Maxime SAPOUNTZIS 4e60b51384 Ajout QueryController et route ExecuteQuery qui renvoie un Json bien formaté bien mignon
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT c6819ae2f8 Merge pull request 'ModifUpdateUser' (#49) from ModifUpdateUser into master
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT d112da2e9b oublie : ajout des annotations sur les verbes POST et PUT du UserController pour indiquer quel code de retour puevent être renvoyés par les methodes concernées
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT fd42cbf104 modification pour le verbe PUT du UserController afin qu'il retour une erreur 409 conflit si le username ou l'email est déjà utilisé
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 7bda8c5181 Fusion de LinkBlazor dans Master
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 2215013554 Cover de quelques méthodes dans BlacklistService
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS b474a171e6 Ajout de test UserController
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 493719d1db Ajout de test supplémentaires pour SuccessController
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 3efa6816fe TU PromoteUser
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 05aa8d9533 Modification des citères pour les enquêtes
1 year ago
Clement CHIEU 92ea8b4686 Suppression des endpoints via kernel
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU ae50e581b1 Suppression du profil https
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU d980c972a4 Debug
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU ce8ab1cf36 Ajout de settings pour swagger
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 50b356c98a Modification Criteria pour les lessons et Users dans l'ordre
1 year ago
Clement CHIEU 488ab60b9c Tentative d'ajout de route pour les inquiries
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU dd5d0e2231 Suppression des options de swaggerui
continuous-integration/drone/push Build was killed Details
1 year ago
Clement CHIEU b5e511efd0 Ajout de swagger vers la bonne route
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU ef14986ef7 Ajout du port 8080
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU a5538bdc50 Changement de port exposé
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 0cb7df701e Fusion master dans LinkBlazor
1 year ago
Maxime SAPOUNTZIS 92a1b9e8b3 Ajout de la route pour promouvoir un user
1 year ago
Clement CHIEU 6f38993d98 Modification de la connection string
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 076deea67f Ajout debug string
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 15cd6fb57b Debug avec une autre env
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU e889bedde1 Ajout var env pour la connection string
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 6074be56d2 Ajout swagger hors developpement
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 44c858e749 Tentative d'ajout dans le appsettings
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 596fc3da4f Ajout port 8080
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 9897d78582 Ajout du port 5015 comme port exposé
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 81a387bab3 Debug
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 37547cc6da Suppression écoute port 8080 http
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 556d002f21 Suppression profil http
continuous-integration/drone/push Build was killed Details
1 year ago
Clement CHIEU af7ccc2eb4 Suppression de la variable d'envrionnement
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 3f955b9ae9 Debug pour le port de l'api
continuous-integration/drone/push Build was killed Details
1 year ago
Clement CHIEU aa8d36ab9b Ajout variable env
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 4fa79eabb2 Test de debug
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 373ddaeb49 Ajout de create
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 5a6561d9b3 Ajout du mirror
continuous-integration/drone/push Build is failing Details
1 year ago
Johnny RATTON 7730b09d3c Merge branch 'master' of codefirst.iut.uca.fr:johnny.ratton/API_SQLuedo
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 9fd24d9726 Ajout de GetNumberOfInquiries et des tests unitaires associés + modification de certaines valeurs de retour dans les controller
1 year ago
Victor GABORIT 74768a1c9e Merge pull request 'changement des codes du verbe POST de User pour traiter les erreur dans la partie client' (#48) from changeCodeRetourPOSTUser into master
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT e906584989 changement des codes du verbe POST de User pour traiter les erreur dans la partie client
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 1a2e5cd3de Ajout replace à la place de create
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 73e1aed1a0 Modification de l'image
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU d42f7acb9f Reproduction de la doc
continuous-integration/drone/push Build is failing Details
1 year ago
Maxime SAPOUNTZIS bdc1e01aa4 Ajout de l'autorisation au Blazor de se connecter
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 77f28e7e1a Ajout du create à la fin
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU b39257855e Suppression du create
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU cdc73c5716 Changement nom du container
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 30c9c158e0 Suppression espace blanc
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU bba3bdffef Refomat du code
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU b8ade38df4 Reformat du code et ajout entrypoint
continuous-integration/drone/push Build was killed Details
1 year ago
Clement CHIEU 284d380e99 Debug en supprimant la commande shell
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 3008b02f44 Ajout du bon chemin pour la commande dotnet et suppression du build
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 0c8003c4a3 Déplacement du fichier dll l'exécuter
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 2b149e3613 Ajout du bon chemin vers le secret
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU b2cf52502c Ajout du bon chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 388b6edcfb Debug du chemin de copie
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU dce7d39ca4 Debug du chemin de copie
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 5ffdb91573 Ajout dockerignore pour tout copier avant le restore
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU f00adb968e Debug du chemin vers l'api
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 1b1ff43d33 Debug du chemin vers l'api
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 8a9cd73a1f Debug du chemin vers la copie des fichiers
continuous-integration/drone/push Build was killed Details
1 year ago
Clement CHIEU f6624b4b5b Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 92d7f0556c Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU fd1826d324 Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 5ea246fb4c Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 20b94d67bb Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 156bf23d6b Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 8734e08051 Debug du chemin vers le csproj
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 7fbe9d425c Debug du chemin
continuous-integration/drone/push Build was killed Details
1 year ago
Clement CHIEU 9a834c8300 Debug du chemin
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 2352ebc5b5 Ajustement du chemin vers le fichier
continuous-integration/drone/push Build is failing Details
1 year ago
Victor GABORIT dd44cf2842 Merge pull request 'fixUserEntity' (#47) from fixUserEntity into master
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT 823701a57e ajout des pour CreateUser avec un username existant et un email existant
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 475de804eb Ajout du dockerfile et du déploiement de l'api
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 8e0c19eea8 Modification mot de passe
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT abe138e4e4 resolution d'erreur pas rapport au tests EF
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT 8e8e55542b ajout de methode pour verfier si l'email ou le username est déjà en base de données
continuous-integration/drone/push Build is failing Details
1 year ago
Victor GABORIT d03d695e68 changement de UserEntity ajout de unique sur les chanps email et username
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 4ba856e7d3 Retour à l'ancien connection string en prévision de la nouvelle avec la variable d'environnement
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU aeede41dad Passage du container en private
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 83903a96bd Ajout du déploiement pour la base de données
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON bcfb7b3e93 Ajout de tout le nécessaire pour gérer la Blacklist (controller, services, etc) accompagné de tests unitaires. Aussi ajout de méthodes manquantes sur les UserController
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 8640499d75 Ajout de la connexion string avec des variables d'environnement
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT 62ad4bf776 Merge pull request 'ajout d'un route GetByEmail pour dans UserController' (#45) from GetUserByEmail into master
continuous-integration/drone/push Build is passing Details
1 year ago
Victor GABORIT cc1903ebfd ajout d'un route GetByEmail pour dans UserController
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU d557cf4876 Rétablissement de la ci-cd
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 39e332cf4b Essai sur la ci
continuous-integration/drone/push Build is failing Details
1 year ago
Johnny RATTON 0648340c09 Changement de l'algorithme de hashage de mot de passe pour correspondre à celui utilisé en PHP
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 9ceb4bed66 Changement des mots de passe dans le contexte stubbé car ils ne correspondaient pas aux règles du site
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 96c7e7d5fb Merge pull request 'UnitTestsEF' (#44) from UnitTestsEF into master
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON b10ab98bd1 Merge branch 'UnitTestsEF' of codefirst.iut.uca.fr:johnny.ratton/API_SQLuedo into UnitTestsEF
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 80de049dc3 Augmentation du coverage pour tous les DataService de DbDataManager
1 year ago
Clement CHIEU 40e422d778 Ajout de la méthode equals dans userdto
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 0a2aa5ea92 Test de toutes les classes de Model
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 4ea53b072e Ajout des tests de UserDataService
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 0aac223ecd Début des tests unitaires sur le service ef
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 014c2665bf Merge pull request 'exclusionContextDrone' (#43) from exclusionContextDrone into master
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 32ef338221 👷 Ajout des program.cs de l'exclusion
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU ef1f7306ac 👷 Ajout de des context dans les fichiers à ignorer pour la couverture de tests, troisieme essai
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 977152026c 👷 Ajout de des context dans les fichiers à ignorer pour la couverture de tests, deuxieme essai
continuous-integration/drone/push Build is failing Details
1 year ago
Clement CHIEU 1bf6bdb3ed 👷 Ajout de des context dans les fichiers à ignorer pour la couverture de tests
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 0820badb49 Fin conflits fusion
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS c5895d2801 Fusion de UnitTestEf dans master
1 year ago
Maxime SAPOUNTZIS 75ff8a5e3a FIN TU Mapper
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS d141a22487 Ajout TU NotepasMapperUnitTest
1 year ago
Maxime SAPOUNTZIS 2cb58ed718 Ajout TU InquiryTableMapper
1 year ago
Maxime SAPOUNTZIS 616e78de47 Ajout TU BlackListMapper
1 year ago
Maxime SAPOUNTZIS 392c832317 Ajout TU Succes et User Mapper 50% done
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS fe4d22e5f9 Refactor des noms de variables pour les TU de InquityMapper et LessonMapper
1 year ago
Maxime SAPOUNTZIS 0b4b379d2f Ajout TU pour ParagraphMapper
1 year ago
Maxime SAPOUNTZIS 8c39d4a5d3 Fin TU LessonMapper
1 year ago
Maxime SAPOUNTZIS f4c2f2f3e2 Fin TU InquiryMapper
1 year ago
Johnny RATTON 9d5ee78cf4 Réglages des deux bugs signalés par Sonar
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON a2c9c0a0e8 Résolution des codeSmells critiques
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 9f2e9b8ace Résolution des codeSmells critiques
1 year ago
Johnny RATTON baf9cba856 Résolution des codeSmells critiques
continuous-integration/drone/push Build is passing Details
1 year ago
Johnny RATTON 69d344e947 Réglage de tous les problèmes conus pour les paragraphes + merge de la branche debugLesson
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS bf71b736f3 Fin des TU sur les mappers utilisés
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS cadcc2d6b8 Ajout TU SuccessMapper
1 year ago
Johnny RATTON b4a5640ede Réglage du bug lors du POST d'un paragraph qui maintenant fonctionne mais le GET sur leçon ne renvoie pas les paragraphes associés. Ajout de la création d'un utilisateur admin pour Identity.
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU d6900f66c0 Merge pull request 'Success fonctionne sur l'API' (#41) from testSuccess into master
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 04001c2ae1 Success fonctionne sur l'API
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 251febe8fb Merge pull request 'modifEntities' (#40) from modifEntities into master
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 2c94d15db7 Suppression faute de frappe au moment du push
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 4988a0ea26 Merge entre master et modifEntities et amélioration du code
continuous-integration/drone/push Build is failing Details
1 year ago
Maxime SAPOUNTZIS 2c75eb1990 Ajout TU pour LessonMapper et ParagraphMapper
1 year ago
Clement CHIEU b750dcbb71 🧑‍💻 Amélioration du code
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS ee35ba9340 Début TU Mapper (pour les méthodes utilisées) - InquiryMapper
1 year ago
Clement CHIEU 56a3fc2b49 Modification du testConsoleEF suite aux changements des constructeurs
1 year ago
Maxime SAPOUNTZIS e2d1591aea Fin fusion UnitTests -> Master
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 0790e47c0b Suppression de constructeurs restants
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU f2ed9a8dbd Suppression des constructeurs de successEntity
1 year ago
Clement CHIEU 9202afb4e6 Suppression des constructeurs de SolutionEntity
1 year ago
Clement CHIEU c4dd76334d Suppression des constructeurs pour user et notepad
1 year ago
Maxime SAPOUNTZIS d9f05fa139 Refactor des noms entre le merge de UnitTests et master
1 year ago
Maxime SAPOUNTZIS da7a13b7aa Fusion et ajout des TU Controller sur Master
1 year ago
Maxime SAPOUNTZIS ac2dfbb85b Fin TU LessonController (Update et Create)
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 99471a3705 Suppression des constructeurs pour lessonEntity
1 year ago
Clement CHIEU f4a44ea80f Suppression des constructeurs des entités
1 year ago
Maxime SAPOUNTZIS 9131895ab5 TU Delete LessonController
1 year ago
Maxime SAPOUNTZIS 98b2a4ce95 Ajout des TU GetByTitle dans LessonController
1 year ago
Clement CHIEU d0efe824ec Suppression des constructeurs de Inquiry
1 year ago
Maxime SAPOUNTZIS dc5cb856ed Ajout des TU GetID pour le LessonController
1 year ago
Maxime SAPOUNTZIS 72808c98ba Ajout des TU GetLessons pour LessonController
1 year ago
Clement CHIEU b22e31d352 Modification du constructeur de paragrapheEntity
1 year ago
Clement CHIEU 210093f565 Suppression constructeur dde blacklistentity
1 year ago
Clement CHIEU f9b325c706 Merge pull request 'code smells supprimé car non respect des conventions de nommage' (#39) from codeSmells into master
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 1d22432e0c code smells supprimé car non respect des conventions de nommage
continuous-integration/drone/push Build is passing Details
1 year ago
Clement CHIEU 62ea58dae4 Modification inutile servant à faire la code-inspection
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 957e864770 Fin des TU ParagraphController
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 4f3de6b3ab Ajout des TU Create pour ParagraphController
1 year ago
Maxime SAPOUNTZIS f1029e3e44 TU Delete ParagraphController
1 year ago
Maxime SAPOUNTZIS 38f5f386dc TU GetByTitle ParagraphController
1 year ago
Maxime SAPOUNTZIS f9f356d329 Ajout des TU GetById sur les paragraphs
1 year ago
Maxime SAPOUNTZIS e4ab7040e3 Ajout des TU GetParagraph pour le ParagrphController
1 year ago
Maxime SAPOUNTZIS 8d1791b7cf Fin TU Success Controller et refactor nom méthode TU Inquiries
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS d34c75d6bf Ajout des TU Create sur les Success
1 year ago
Maxime SAPOUNTZIS e59a452293 Ajout des TU Delete Success
1 year ago
Maxime SAPOUNTZIS f0cb5933a0 Ajout des TU pour GetSuccessesByUserId
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 4df6eac1a0 Ajout des TU Pour GetSuccesses et GetSuccessesInquiryId
1 year ago
Maxime SAPOUNTZIS a3d9f7c2b7 Fusion de Master dans UnitTests pour récupérer la nouvelle logique de Success
1 year ago
Johnny RATTON 5a8d8fe4e9 Réglage de différents bugs et incohérences liés aux succès
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 403aa3bdc4 Fin TU InquiriesController
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS df95674511 Ajout TU Create et Delete pour InquiryController
1 year ago
Johnny RATTON a86a027640 Merge pull request 'testConsoleEF' (#38) from testConsoleEF into master
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS f0c096e147 Ajout TU pour GetInquiryByTitle et ByID
1 year ago
Maxime SAPOUNTZIS 83560da671 Ajout TU Pour GetInquiries
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 3e1d716fb7 Fusion de master dans UnitTests
1 year ago
Maxime SAPOUNTZIS 61143c06b2 Correction d'un appel Moq
1 year ago
Erwan MENAGER 6c12899d8a Merge branch 'UnitTestsEF' of https://codefirst.iut.uca.fr/git/johnny.ratton/API_SQLuedo into UnitTestsEF
continuous-integration/drone/push Build is passing Details
1 year ago
Erwan MENAGER 534589dbdf Implémentation des TU pour les DTO
1 year ago
Maxime SAPOUNTZIS 6e17a7397c Ajout TU UpdateUser - FIN TU User Controller
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS ffa13b84b6 Ajout des TU pour CreateUser
1 year ago
Maxime SAPOUNTZIS 0d4ed12d9f Ajout des TU pour DeleteUser
1 year ago
Maxime SAPOUNTZIS e3b6f56204 Ajout des TU Success et Fail de 'GetUserByUsername'
1 year ago
Maxime SAPOUNTZIS 3d4bed02ec TU GetUserId réussite et échec
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS c3acddb9c5 Ajout du TU d'échec de GetUserList
1 year ago
Maxime SAPOUNTZIS cf23246666 TU GetUserList avec Moq
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS 125c6be8e1 Début des test Moq et ajout de méthodes d'extensions pour un UserDto
1 year ago
Maxime SAPOUNTZIS 37958ca428 Merge de master dans UnitTests pour être à jour et commencer les test unitaires
continuous-integration/drone/push Build is passing Details
1 year ago
Maxime SAPOUNTZIS c865bf434e Merge branch 'master' into UnitTests
continuous-integration/drone/push Build is failing Details
1 year ago
Maxime SAPOUNTZIS b90e4f6e75 Merge branch 'master' into UnitTests
1 year ago
Maxime SAPOUNTZIS 44b56dee93 Début des tests unitaires sur le service de l'API
continuous-integration/drone/push Build is failing Details
1 year ago

@ -20,17 +20,17 @@ steps:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
- dotnet test API_SQLuedo.sln -c Release --no-build --no-restore
depends_on: [ build ]
depends_on: [build]
- name: code-inspection
image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet8
secrets: [ SECRET_SONAR_LOGIN ]
secrets: [SECRET_SONAR_LOGIN]
environment:
sonar_host: https://codefirst.iut.uca.fr/sonar/
sonar_token:
from_secret: SECRET_SONAR_LOGIN
project_key: API_SQLuedo
coverage_exclusions: "Test*/**"
coverage_exclusions: "**/Test*/**,**/*Context*/**,**/Program.cs,**/Migrations/**"
commands:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
@ -40,4 +40,54 @@ steps:
- reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport"
- dotnet publish API_SQLuedo.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release
- dotnet sonarscanner end /d:sonar.login=$${sonar_token}
depends_on: [ build ]
depends_on: [build]
- name: deploy-sqluedo-db
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: postgres:16.2
CONTAINERNAME: sqluedo-db
COMMAND: create
OVERWRITE: true
PRIVATE: true
CODEFIRST_CLIENTDRONE_ENV_POSTGRES_USER:
from_secret: db_username
CODEFIRST_CLIENTDRONE_ENV_POSTGRES_PASSWORD:
from_secret: db_password
CODEFIRST_CLIENTDRONE_ENV_POSTGRES_DB:
from_secret: db_database
ADMINS: erwanmenager,maximesapountzis,johnnyratton,victorgaborit,clementchieu
depends_on: [tests]
# Build and push API image
- name: api-image-build-and-push
image: plugins/docker
settings:
dockerfile: API_SQLuedo/API/Dockerfile
context: API_SQLuedo/
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/johnny.ratton/api_sqluedo
mirror: https://proxy.iut.uca.fr:8443
username:
from_secret: secret_registry_username
password:
from_secret: secret_registry_password
# Deploy API
- name: deploy-api-from-image
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/johnny.ratton/api_sqluedo:latest
CONTAINERNAME: sqluedo-api
COMMAND: create
OVERWRITE: true
CODEFIRST_CLIENTDRONE_ENV_DB_HOST:
from_secret: db_host
CODEFIRST_CLIENTDRONE_ENV_DB_USER:
from_secret: db_username
CODEFIRST_CLIENTDRONE_ENV_DB_PASSWORD:
from_secret: db_password
CODEFIRST_CLIENTDRONE_ENV_DB_DATABASE:
from_secret: db_database
ADMINS: erwanmenager,maximesapountzis,johnnyratton,victorgaborit,clementchieu
depends_on: [ api-image-build-and-push, deploy-sqluedo-db ]

3
.gitignore vendored

@ -492,8 +492,7 @@ fabric.properties
.idea/caches/build_file_checksums.ser
# Migrations et fichiers db
**/Migrations/**
# Fichier db
*.db
/**/.idea/

@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**

@ -21,6 +21,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

@ -0,0 +1,94 @@
using Asp.Versioning;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.OrderCriteria;
using Shared;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class BlackListController(ILogger<UsersController> logger, IBlackListService<BlackListDto> blackListService)
: ControllerBase
{
[HttpGet("user/ban/{page:int}/{number:int}")]
[ProducesResponseType(typeof(IEnumerable<BlackListDto>), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria)
{
var users = blackListService.GetBannedUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
{
logger.LogError("[ERREUR] Aucun email banni trouvé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] {nb} Email(s) banni(s) trouvé(s)", users.Count);
return Ok(users);
}
[HttpGet("user/ban/number")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfBannedUsers()
{
var nb = blackListService.GetNumberOfBannedUsers();
logger.LogInformation("[INFORMATION] {nb} Email(s) banni(s) trouvé(s)", nb);
return Ok(new KeyValuePair<string,int>("number",nb));
}
[HttpPost("user/ban")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserBannedByEmail([FromBody] string email)
{
var res = blackListService.GetUserBannedByEmail(email);
if (res != null)
{
logger.LogInformation("[INFORMATION] Utilisateur banni avec l'email {email} a été trouvé.", email);
return Ok(res);
}
logger.LogError("[ERREUR] Aucun utilisateur banni trouvé avec l'email {email}.", email);
return NotFound("Utilisateur non trouvé !");
}
[HttpDelete("user/ban/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult BanUser(string username)
{
var success = blackListService.BanUser(username);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec le pseudo {username} a été banni pour 2 ans.", username);
return Ok(new KeyValuePair<string,bool>("success", true));
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec le pseudo {username}.", username);
return NotFound();
}
}
[HttpPost("user/unban")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UnbanUser([FromBody] string email)
{
var success = blackListService.UnbanUser(email);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec l'email {email} a été débanni.", email);
return Ok(new KeyValuePair<string,bool>("success", true));
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur banni trouvé avec l'email {email}.", email);
return NotFound();
}
}
}

@ -5,136 +5,145 @@ using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class InquiriesController : Controller
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class InquiriesController : Controller
{
private readonly IInquiryService<InquiryDTO> _inquiryDataService;
private readonly IInquiryService<InquiryDto> _inquiryDataService;
private readonly ILogger<InquiriesController> _logger;
private readonly ILogger<InquiriesController> _logger;
public InquiriesController(IInquiryService<InquiryDto> inquiryDataService, ILogger<InquiriesController> logger)
{
_inquiryDataService = inquiryDataService;
_logger = logger;
}
public InquiriesController(IInquiryService<InquiryDTO> inquiryDataService, ILogger<InquiriesController> logger)
[HttpGet("inquiries/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
var nbInquiry = _inquiryDataService.GetInquiries(page, number, orderCriteria).Count();
if (nbInquiry == 0)
{
_inquiryDataService = inquiryDataService;
_logger = logger;
_logger.LogError("[ERREUR] Aucune enquête trouvée.");
return StatusCode(204);
}
[HttpGet("inquiries/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(_inquiryDataService.GetInquiries(page, number, orderCriteria));
}
[HttpGet("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryById(int id)
{
try
{
var nbInquiry = _inquiryDataService.GetInquiries(page, number, orderCriteria).Count();
if (nbInquiry == 0)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(_inquiryDataService.GetInquiries(page, number, orderCriteria));
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryDataService.GetInquiryById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryById(int id)
[HttpGet("inquiry/{title:alpha}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryByTitle(string title)
{
try
{
try
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryDataService.GetInquiryById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
_logger.LogInformation("[INFORMATION] L'enquête avec le titre {title} a été trouvé.", title);
return Ok(_inquiryDataService.GetInquiryByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec le titre {title}.", title);
return NotFound();
}
}
[HttpGet("inquiry/{title:alpha}")]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryByTitle(string title)
[HttpDelete("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteInquiry(int id)
{
var success = _inquiryDataService.DeleteInquiry(id);
if (success)
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été supprimé.", id);
return Ok(_inquiryDataService.DeleteInquiry(id));
}
else
{
try
{
_logger.LogInformation("[INFORMATION] L'enquête avec le titre {title} a été trouvé.", title);
return Ok(_inquiryDataService.GetInquiryByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec le titre {title}.", title);
return NotFound();
}
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpDelete("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteInquiry(int id)
[HttpPost]
[ProducesResponseType(typeof(InquiryDto), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateInquiry([FromBody] InquiryDto dto)
{
if (dto.Title == null || dto.Description == null)
{
var success = _inquiryDataService.DeleteInquiry(id);
if (success)
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été supprimé.", id);
return Ok(_inquiryDataService.DeleteInquiry(id));
}
else
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
return BadRequest();
}
[HttpPost]
[ProducesResponseType(typeof(InquiryDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateInquiry([FromBody] InquiryDTO dto)
_logger.LogInformation(
"[INFORMATION] Une enquête a été créé : title - {title}, description - {description}, isUser - {isUser}",
dto.Title, dto.Description, dto.IsUser);
return Created(nameof(GetInquiries),
_inquiryDataService.CreateInquiry(dto.Title, dto.Description, dto.IsUser));
}
[HttpPut("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateInquiry(int id, [FromBody] InquiryDto InquiryDto)
{
if (id != InquiryDto.Id)
{
if (dto.Title == null || dto.Description == null)
{
return BadRequest();
}
_logger.LogInformation(
"[INFORMATION] Une enquête a été créé : title - {title}, description - {description}, isUser - {isUser}",
dto.Title, dto.Description, dto.IsUser);
return Created(nameof(GetInquiries),
_inquiryDataService.CreateInquiry(dto.Title, dto.Description, dto.IsUser));
_logger.LogError("[ERREUR] Problème ID - La mise à jour de l'enquête avec l'id {id} a échouée.", id);
return BadRequest();
}
[HttpPut("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateInquiry(int id, [FromBody] InquiryDTO inquiryDTO)
if (!ModelState.IsValid)
{
if (id != inquiryDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour de l'enquête avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour de l'enquête avec l'id {id} a échouée.", id);
return BadRequest();
}
if (inquiryDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de l'enquête avec l'id {id} a été effectuée", id);
return Ok(_inquiryDataService.UpdateInquiry(id, inquiryDTO));
}
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour de l'enquête avec l'id {id} a échouée.", id);
return BadRequest();
}
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
if (InquiryDto != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de l'enquête avec l'id {id} a été effectuée", id);
return Ok(_inquiryDataService.UpdateInquiry(id, InquiryDto));
}
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
[HttpGet("inquiries/number")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfInquiries()
{
var nbInquiry = _inquiryDataService.GetNumberOfInquiries();
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(new KeyValuePair<string, int>("nbInquiries", nbInquiry));
}
}

@ -0,0 +1,42 @@
using Asp.Versioning;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class InquiryTableController : Controller
{
private readonly IInquiryTableService<InquiryTableDto> _inquiryTableService;
private readonly ILogger<InquiryTableController> _logger;
public InquiryTableController(IInquiryTableService<InquiryTableDto> inquiryTableService, ILogger<InquiryTableController> logger)
{
_inquiryTableService = inquiryTableService;
_logger = logger;
}
[HttpGet("database/{id:int}")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetDatabaseNameByInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] La base de données pour l'enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryTableService.GetDatabaseNameByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune base de données trouvée pour l'enquête avec l'id {id}.", id);
return NotFound();
}
}
}

@ -5,136 +5,168 @@ using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class LessonsController : Controller
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class LessonsController : Controller
private readonly ILessonService<LessonDto> _lessonDataService;
private readonly ILogger<LessonsController> _logger;
public LessonsController(ILessonService<LessonDto> lessonDataService, ILogger<LessonsController> logger)
{
private readonly ILessonService<LessonDTO> _lessonDataService;
_lessonDataService = lessonDataService;
_logger = logger;
}
private readonly ILogger<LessonsController> _logger;
[HttpGet("lessons/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
var nbLesson = _lessonDataService.GetLessons(page, number, orderCriteria).Count();
if (nbLesson == 0)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée.");
return StatusCode(204);
}
public LessonsController(ILessonService<LessonDTO> lessonDataService, ILogger<LessonsController> logger)
_logger.LogInformation("[INFORMATION] {nb} Leçon(s) trouvée(s)", nbLesson);
return Ok(_lessonDataService.GetLessons(page, number, orderCriteria));
}
[HttpGet("lessons/number")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfLessons()
{
var nbLesson = _lessonDataService.GetNumberOfLessons();
if (nbLesson == 0)
{
_lessonDataService = lessonDataService;
_logger = logger;
_logger.LogError("[ERREUR] Aucune leçon trouvée.");
return StatusCode(204);
}
[HttpGet("lessons/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
_logger.LogInformation("[INFORMATION] {nb} Leçon(s) trouvée(s)", nbLesson);
return Ok(new KeyValuePair<string,int>("nbLessons", nbLesson));
}
[HttpGet("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonById(int id)
{
try
{
var nbLesson = _lessonDataService.GetLessons(page, number, orderCriteria).Count();
if (nbLesson == 0)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été trouvé.", id);
return Ok(_lessonDataService.GetLessonById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
_logger.LogInformation("[INFORMATION] {nb} Leçon(s) trouvée(s)", nbLesson);
return Ok(_lessonDataService.GetLessons(page, number, orderCriteria));
[HttpGet("lesson/{title:alpha}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec le titre {title} a été trouvé.", title);
return Ok(_lessonDataService.GetLessonByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec le titre {title}.", title);
return NotFound();
}
}
[HttpGet("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonById(int id)
[HttpDelete("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteLesson(int id)
{
var success = _lessonDataService.DeleteLesson(id);
if (success)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été trouvé.", id);
return Ok(_lessonDataService.GetLessonById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été supprimé.", id);
return Ok(_lessonDataService.DeleteLesson(id));
}
else
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("lesson/{title:alpha}")]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonByTitle(string title)
[HttpPost]
[ProducesResponseType(typeof(LessonDto), 201)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 500)]
public IActionResult CreateLesson([FromBody] LessonDto dto)
{
if (dto.Title == null || dto.LastPublisher == null)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec le titre {title} a été trouvé.", title);
return Ok(_lessonDataService.GetLessonByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec le titre {title}.", title);
return NotFound();
}
return BadRequest();
}
[HttpDelete("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteLesson(int id)
try
{
var success = _lessonDataService.DeleteLesson(id);
if (success)
var createdLesson = _lessonDataService.CreateLesson(dto.Id, dto.Title, dto.LastPublisher,
dto.LastEdit ?? DateOnly.FromDateTime(DateTime.Now));
if (createdLesson != null)
{
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été supprimé.", id);
return Ok(_lessonDataService.DeleteLesson(id));
_logger.LogInformation(
"[INFORMATION] Une leçon a été créé : title - {title}, lastPublisher - {publisher}, lastEdit - {lastEdit}",
dto.Title, dto.LastPublisher, dto.LastEdit);
return Created(nameof(GetLessons), createdLesson);
}
else
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
return StatusCode(500);
}
}
[HttpPost]
[ProducesResponseType(typeof(LessonDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateLesson([FromBody] LessonDTO dto)
catch (ArgumentException e)
{
if (dto.Title == null || dto.LastPublisher == null)
{
return BadRequest();
}
_logger.LogInformation(
"[INFORMATION] Une leçon a été créé : title - {title}, lastPublisher - {publisher}, lastEdit - {lastEdit}",
dto.Title, dto.LastPublisher, dto.LastEdit);
return Created(nameof(GetLessons),
_lessonDataService.CreateLesson(dto.Title, dto.LastPublisher, dto.LastEdit));
_logger.LogError("[ERREUR] " + e.Message);
return Created();
}
}
[HttpPut("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateLesson(int id, [FromBody] LessonDTO lessonDTO)
[HttpPut("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateLesson(int id, [FromBody] LessonDto LessonDto)
{
if (id != LessonDto.Id)
{
if (id != lessonDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour de la leçon avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour de la leçon avec l'id {id} a échouée.",
id);
return BadRequest();
}
_logger.LogError("[ERREUR] Problème ID - La mise à jour de la leçon avec l'id {id} a échouée.", id);
return BadRequest();
}
if (lessonDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id);
return Ok(_lessonDataService.UpdateLesson(id, lessonDTO));
}
if (!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour de la leçon avec l'id {id} a échouée.",
id);
return BadRequest();
}
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
if (LessonDto != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id);
return Ok(_lessonDataService.UpdateLesson(id, LessonDto));
}
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}

@ -0,0 +1,97 @@
using Asp.Versioning;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class NotepadController : Controller
{
private readonly INotepadService<NotepadDto> _notepadDataService;
private readonly ILogger<NotepadController> _logger;
public NotepadController(INotepadService<NotepadDto> notepadService, ILogger<NotepadController> logger)
{
_notepadDataService = notepadService;
_logger = logger;
}
[HttpGet("notepad/{userId:int}/{inquiryId:int}")]
[ProducesResponseType(typeof(NotepadDto), 200)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult GetNotepadByUserAndInquiryById(int userId, int inquiryId)
{
try
{
_logger.LogInformation(
"[INFORMATION] Le bloc-notes de l'utilisateur avec l'id {id} et l'enquête avec l'id {idInquiry} a été trouvé.",
userId, inquiryId);
return Ok(_notepadDataService.GetNotepadFromUserAndInquiryId(userId,inquiryId));
}
catch (ArgumentException)
{
_logger.LogError(
"[ERREUR] Aucun bloc-notes trouvé pour l'utilisateur avec l'id {id} et l'enquête avec l'id {inquiryId}.",
userId, inquiryId);
return NotFound();
}
}
[HttpPost("notepad")]
[ProducesResponseType(typeof(void), 200)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult SetNotepadByUserAndInquiryById([FromBody] NotepadDto notepad)
{
try
{
if (notepad.InquiryId < 0 || notepad.UserId < 0 || notepad.Notes == null)
{
return BadRequest();
}
_notepadDataService.SetNotepadFromUserAndInquiryId(notepad.UserId, notepad.InquiryId, notepad.Notes);
_logger.LogInformation(
"[INFORMATION] Le bloc-notes de l'utilisateur avec l'id {id} et l'enquête avec l'id {idInquiry} a été créé.",
notepad.UserId, notepad.InquiryId);
return Ok();
}
catch (ArgumentException)
{
_logger.LogError(
"[ERREUR] Aucun bloc-notes n'a pu être créé pour l'utilisateur avec l'id {id} et l'enquête avec l'id {inquiryId}.",
notepad.UserId, notepad.InquiryId);
return NotFound();
}
}
[HttpPut("notepad")]
[ProducesResponseType(typeof(void), 203)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult UpdateNotepadByUserAndInquiryById([FromBody] NotepadDto notepad)
{
try
{
if (notepad.InquiryId < 0 || notepad.UserId < 0 || notepad.Notes == null)
{
return BadRequest();
}
_notepadDataService.UpdateNotepadFromUserAndInquiryId(notepad.UserId, notepad.InquiryId, notepad.Notes);
_logger.LogInformation(
"[INFORMATION] Le bloc-notes de l'utilisateur avec l'id {id} et l'enquête avec l'id {idInquiry} a été mis à jour.",
notepad.UserId, notepad.InquiryId);
return Ok();
}
catch (ArgumentException)
{
_logger.LogError(
"[ERREUR] Aucun bloc-notes n'a pu être mis à jour pour l'utilisateur avec l'id {id} et l'enquête avec l'id {inquiryId}.",
notepad.UserId, notepad.InquiryId);
return NotFound();
}
}
}

@ -5,139 +5,156 @@ using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class ParagraphsController : Controller
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class ParagraphsController : Controller
private readonly IParagraphService<ParagraphDto> _paragraphDataService;
private readonly ILogger<ParagraphsController> _logger;
public ParagraphsController(IParagraphService<ParagraphDto> paragraphDataService,
ILogger<ParagraphsController> logger)
{
_paragraphDataService = paragraphDataService;
_logger = logger;
}
[HttpGet("paragraphs/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
private readonly IParagraphService<ParagraphDTO> _paragraphDataService;
var nbParagraph = _paragraphDataService.GetParagraphs(page, number, orderCriteria).ToList().Count;
if (nbParagraph == 0)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé.");
return StatusCode(204);
}
private readonly ILogger<ParagraphsController> _logger;
_logger.LogInformation("[INFORMATION] {nb} Paragraphe(s) trouvé(s)", nbParagraph);
return Ok(_paragraphDataService.GetParagraphs(page, number, orderCriteria));
}
public ParagraphsController(IParagraphService<ParagraphDTO> paragraphDataService,
ILogger<ParagraphsController> logger)
[HttpGet("paragraphs/lesson/{id:int}")]
[ProducesResponseType(typeof(IEnumerable<ParagraphDto>), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetParagraphsByLessonId(int id)
{
var paragraphs = _paragraphDataService.GetParagraphsByLessonId(id);
if (paragraphs.Count() == 0)
{
_paragraphDataService = paragraphDataService;
_logger = logger;
_logger.LogError("[ERREUR] Aucun paragraphe trouvé.");
return StatusCode(204);
}
[HttpGet("paragraphs/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
_logger.LogInformation("[INFORMATION] {nb} Paragraphe(s) trouvé(s)", paragraphs.Count());
return Ok(paragraphs);
}
[HttpGet("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphById(int id)
{
try
{
var nbParagraph = _paragraphDataService.GetParagraphs(page, number, orderCriteria).ToList().Count;
if (nbParagraph == 0)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Paragraphe(s) trouvé(s)", nbParagraph);
return Ok(_paragraphDataService.GetParagraphs(page, number, orderCriteria));
_logger.LogInformation("[INFORMATION] Le paragraphe avec l'id {id} a été trouvé.", id);
return Ok(_paragraphDataService.GetParagraphById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphById(int id)
[HttpGet("paragraph/{title:alpha}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphByTitle(string title)
{
try
{
try
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec l'id {id} a été trouvé.", id);
return Ok(_paragraphDataService.GetParagraphById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
_logger.LogInformation("[INFORMATION] Le paragraphe avec le titre {title} a été trouvé.", title);
return Ok(_paragraphDataService.GetParagraphByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec le titre {title}.", title);
return NotFound();
}
}
[HttpGet("paragraph/{title:alpha}")]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphByTitle(string title)
[HttpDelete("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteParagraph(int id)
{
var success = _paragraphDataService.DeleteParagraph(id);
if (success)
{
try
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec le titre {title} a été trouvé.", title);
return Ok(_paragraphDataService.GetParagraphByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec le titre {title}.", title);
return NotFound();
}
_logger.LogInformation("[INFORMATION] Le paragraphe avec l'id {id} a été supprimé.", id);
return Ok(_paragraphDataService.DeleteParagraph(id));
}
else
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpDelete("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteParagraph(int id)
[HttpPost]
[ProducesResponseType(typeof(ParagraphDto), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateParagraph([FromBody] ParagraphDto dto)
{
if (dto.ContentTitle == null || dto.ContentContent == null || dto.Title == null || dto.Content == null ||
dto.Info == null || dto.Query == null ||
dto.Comment == null)
{
var success = _paragraphDataService.DeleteParagraph(id);
if (success)
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec l'id {id} a été supprimé.", id);
return Ok(_paragraphDataService.DeleteParagraph(id));
}
else
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
return BadRequest();
}
[HttpPost]
[ProducesResponseType(typeof(ParagraphDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateParagraph([FromBody] ParagraphDTO dto)
_logger.LogInformation(
"[INFORMATION] Un paragraphe a été créé : title - {title}, content - {content}, info - {info}, query - {query}, comment - {comment}",
dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment);
return Created(nameof(GetParagraphs),
_paragraphDataService.CreateParagraph(dto.ContentTitle, dto.ContentContent, dto.Title, dto.Content,
dto.Info, dto.Query, dto.Comment,
dto.LessonId));
}
[HttpPut("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateParagraph(int id, [FromBody] ParagraphDto ParagraphDto)
{
if (id != ParagraphDto.Id)
{
if (dto.Title == null || dto.Content == null || dto.Info == null || dto.Query == null ||
dto.Comment == null)
{
return BadRequest();
}
_logger.LogInformation(
"[INFORMATION] Un paragraphe a été créé : title - {title}, content - {content}, info - {info}, query - {query}, comment - {comment}",
dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment);
return Created(nameof(GetParagraphs),
_paragraphDataService.CreateParagraph(dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment,
dto.LessonId));
_logger.LogError("[ERREUR] Problème ID - La mise à jour du paragraphe avec l'id {id} a échouée.", id);
return BadRequest();
}
[HttpPut("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateParagraph(int id, [FromBody] ParagraphDTO paragraphDTO)
if (!ModelState.IsValid)
{
if (id != paragraphDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour du paragraphe avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour du paragraphe avec l'id {id} a échouée.", id);
return BadRequest();
}
if (paragraphDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour du paragraphe avec l'id {id} a été effectuée", id);
return Ok(_paragraphDataService.UpdateParagraph(id, paragraphDTO));
}
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour du paragraphe avec l'id {id} a échouée.", id);
return BadRequest();
}
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
if (ParagraphDto != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour du paragraphe avec l'id {id} a été effectuée", id);
return Ok(_paragraphDataService.UpdateParagraph(id, ParagraphDto));
}
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
}

@ -0,0 +1,65 @@
using Dto;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared;
using Model.OrderCriteria;
namespace API.Controllers
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class QueryController(ILogger<QueryController> logger, IQueryService<QueryDto> queryService) : ControllerBase
{
[HttpPost("{database}/execute")]
[ProducesResponseType(typeof(QueryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult ExecuteQuery([FromBody]string query, string database)
{
var queryResult = queryService.ExecuteQuery(query, database);
if (queryResult == null)
{
logger.LogError("[ERREUR] La requête n'a rien renvoyé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] La requête a renvoyé : {result} ", queryResult);
return Content(queryResult.Result, "application/json");
}
[HttpGet("{database}/Tables")]
[ProducesResponseType(typeof(QueryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetTables(string database)
{
var queryResult = queryService.GetTables(database);
if (queryResult == null)
{
logger.LogError("[ERREUR] La requête n'a rien renvoyé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] La requête a renvoyé : {result} ", queryResult);
return Content(queryResult.Result, "application/json");
}
[HttpGet("{database}/{table}/Columns")]
[ProducesResponseType(typeof(QueryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetColumns(string database,string table)
{
var queryResult = queryService.GetColumns(database,table);
if (queryResult == null)
{
logger.LogError("[ERREUR] La requête n'a rien renvoyé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] La requête a renvoyé : {result} ", queryResult);
return Content(queryResult.Result, "application/json");
}
}
}

@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class SolutionController : Controller
{
private readonly ISolutionService<SolutionDto> _solutionDataService;
private readonly ILogger<SolutionController> _logger;
public SolutionController(ISolutionService<SolutionDto> solutionDataService, ILogger<SolutionController> logger)
{
_solutionDataService = solutionDataService;
_logger = logger;
}
[HttpGet("solution/{id:int}")]
[ProducesResponseType(typeof(SolutionDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSolutionByInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_solutionDataService.GetSolutionByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
}
}

@ -5,139 +5,202 @@ using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class SuccessesController : Controller
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class SuccessesController : Controller
private readonly ISuccessService<SuccessDto> _successDataService;
private readonly ILogger<SuccessesController> _logger;
public SuccessesController(ISuccessService<SuccessDto> successDataService, ILogger<SuccessesController> logger)
{
_successDataService = successDataService;
_logger = logger;
}
[HttpGet("successes/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 204)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
if (page < 1 || number < 1)
{
_logger.LogError("[ERREUR] La page ou le nombre de succès est inférieur à 1.");
return BadRequest("La page ou le nombre de succès est inférieur à 1.");
}
var nbUser = _successDataService.GetSuccesses(page, number, orderCriteria).ToList().Count;
if (nbUser == 0)
{
_logger.LogError("[ERREUR] Aucun Succès trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Succès(s) trouvé(s)", nbUser);
return Ok(_successDataService.GetSuccesses(page, number, orderCriteria));
}
[HttpGet("success/user/{id:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSuccessByUserId(int id)
{
if (id < 1)
{
_logger.LogError("[ERREUR] L'id de l'utilisateur est inférieur à 1.");
return BadRequest("L'id de l'utilisateur est inférieur à 1.");
}
try
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id de l'utilisateur {id} a été trouvé.", id);
return Ok(_successDataService.GetSuccessesByUserId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'utilisateur {id}.", id);
return NotFound("Aucun utilisateur trouvé avec l'id de l'utilisateur.");
}
}
[HttpGet("success/inquiry/{id:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSuccessByInquiryId(int id)
{
private readonly ISuccessService<SuccessDTO> _successDataService;
private readonly ILogger<SuccessesController> _logger;
public SuccessesController(ISuccessService<SuccessDTO> successDataService, ILogger<SuccessesController> logger)
{
_successDataService = successDataService;
_logger = logger;
}
[HttpGet("successes/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
var nbUser = _successDataService.GetSuccesses(page, number, orderCriteria).ToList().Count;
if (nbUser == 0)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_successDataService.GetSuccesses(page, number, orderCriteria));
}
[HttpGet("success/user/{id:int}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSuccessByUserId(int id)
{
try
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id de l'utilisateur {id} a été trouvé.", id);
return Ok(_successDataService.GetSuccessByUserId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'utilisateur {id}.", id);
return NotFound();
}
}
[HttpGet("success/inquiry/{id:int}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSuccessByInquiryId(int id)
{
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id de l'enquête {inquiryId} a été trouvé.",
id);
return Ok(_successDataService.GetSuccessByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'enquête {inquiryId}.", id);
return NotFound();
}
}
[HttpDelete("success/{id:int}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteSuccess(int id)
{
var success = _successDataService.DeleteSuccess(id);
if (success)
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id {id} a été supprimé.", id);
return Ok(_successDataService.DeleteSuccess(id));
}
else
{
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(SuccessDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateSuccess([FromBody] SuccessDTO dto)
{
/*if (dto.UserId == null || dto.InquiryId == null)
{
return BadRequest();
}*/
if (id < 1)
{
_logger.LogError("[ERREUR] L'id de l'enquête doit être inférieur à 1.");
return BadRequest("L'id de l'enquête doit être inférieur à 1.");
}
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id de l'enquête {inquiryId} a été trouvé.",
id);
return Ok(_successDataService.GetSuccessesByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'enquête {inquiryId}.", id);
return NotFound("Aucune enquête trouvée avec l'id de l'enquête.");
}
}
[HttpDelete("success/{idUser:int}/{idInquiry:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteSuccess(int idUser, int idInquiry)
{
if (idUser < 1 || idInquiry < 1)
{
_logger.LogInformation("[INFORMATION] L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
return BadRequest("L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
}
var success = _successDataService.DeleteSuccess(idUser, idInquiry);
if (success)
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id {id} a été supprimé.", idUser);
return Ok(success);
}
else
{
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id {id}.", idUser);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(SuccessDto), 201)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateSuccess([FromBody] SuccessDto dto)
{
if (dto.UserId < 1 || dto.InquiryId < 1)
{
_logger.LogError("[ERREUR] L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
return BadRequest("L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
}
try
{
var s = _successDataService.CreateSuccess(dto.UserId, dto.InquiryId, dto.IsFinished);
_logger.LogInformation(
"[INFORMATION] Un succès a été créé : userId - {userId}, inquiryId - {inquiryId}, isFinished - {isFinished}",
dto.UserId, dto.InquiryId, dto.IsFinished);
return Created(nameof(GetSuccesses),
_successDataService.CreateSuccess(dto.UserId, dto.InquiryId, dto.IsFinished));
}
[HttpPut("success/{id:int}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateSuccess(int id, [FromBody] SuccessDTO successDTO)
{
if (id != successDTO.UserId)
{
_logger.LogError(
"[ERREUR] Problème ID - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.",
id);
return BadRequest();
}
if (successDTO != null)
{
_logger.LogInformation(
"[INFORMATION] La mise à jour du succès avec l'id de l'utilisateur {id} a été effectuée", id);
return Ok(_successDataService.UpdateSuccess(id, successDTO));
}
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id de l'utilisateur {id}.", id);
return NotFound();
return Created(nameof(GetSuccesses), s);
}
catch (Exception e)
{
return HandleError(e);
}
}
[HttpPut("success/{idUser:int}/{idInquiry:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateSuccess(int idUser, int idInquiry, [FromBody] SuccessDto successDto)
{
if (idUser < 1 || idInquiry < 1)
{
_logger.LogError("[ERREUR] L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
return BadRequest("L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
}
if (idUser != successDto.UserId || idInquiry != successDto.InquiryId)
{
_logger.LogError(
"[ERREUR] Problème ID - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.",
idUser);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.",
idUser);
return BadRequest();
}
try
{
var s = _successDataService.UpdateSuccess(idUser, idInquiry, successDto);
_logger.LogInformation(
"[INFORMATION] La mise à jour du succès avec l'id de l'utilisateur {id} a été effectuée", idUser);
return Ok(s);
}
catch (Exception e)
{
return HandleError(e);
}
}
private IActionResult HandleError(Exception e)
{
switch (e.Message)
{
case { } msg when msg.Contains("userId"):
_logger.LogError("[ERREUR] Impossible de trouver l'utilisateur pour la manipulation du succès");
return NotFound("Impossible de trouver l'utilisateur pour la manipulation du succès");
case { } msg when msg.Contains("inquiryId"):
_logger.LogError("[ERREUR] Impossible de trouver l'enquête pour la manipulation du succès");
return NotFound("Impossible de trouver l'enquête pour la manipulation du succès");
case { } msg when msg.Contains("success"):
_logger.LogError("[ERREUR] Impossible de manipuler le succès car il n'existe pas");
return Conflict("Impossible de manipuler le succès car il n'existe pas");
default:
_logger.LogError("[ERREUR] Erreur inattendue, impossible de manipuler le succès");
return BadRequest("Erreur inattendue, impossible de manipuler le succès");
}
}
}

@ -5,128 +5,231 @@ using Microsoft.AspNetCore.Mvc;
using Shared;
using Model.OrderCriteria;
namespace API.Controllers
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class UsersController(ILogger<UsersController> logger, IUserService<UserDto> userService) : ControllerBase
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class UsersController(ILogger<UsersController> logger, IUserService<UserDTO> userService) : ControllerBase
[HttpGet("users/{page:int}/{number:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var users = userService.GetUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", users.Count);
return Ok(users);
}
[HttpGet("users/not-admin/{page:int}/{number:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var users = userService.GetNotAdminUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", users.Count);
return Ok(users);
}
[HttpGet("users/number")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfUsers()
{
[HttpGet("users/{page:int}/{number:int}")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var users = userService.GetUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", users.Count);
return Ok(users);
}
[HttpGet("user/{id:int}")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserById(int id)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
return Ok(userService.GetUserById(id));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("user/{username:alpha}")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserByUsername(string username)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
return Ok(userService.GetUserByUsername(username));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
return NotFound();
}
}
[HttpDelete("user/{id:int}")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUser(int id)
{
var success = userService.DeleteUser(id);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
return Ok();
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(UserDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateUser([FromBody] UserDTO dto)
{
if (dto.Username == null || dto.Password == null || dto.Email == null)
{
return BadRequest();
}
// return Ok(userService.CreateUser(username, password, email, isAdmin));
logger.LogInformation(
"[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}",
dto.Username, dto.Password, dto.Email, dto.IsAdmin);
return Created(nameof(GetUsers),
userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin));
}
[HttpPut("user/{id:int}")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateUser(int id, [FromBody] UserDTO userDto)
{
if (id != userDto.Id)
{
logger.LogError("[ERREUR] Problème ID - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if (userDto != null)
{
logger.LogInformation("[INFORMATION] La mise à jour de l'utilsiateur avec l'id {id} a été effectuée",
id);
return Ok(userService.UpdateUser(id, userDto));
}
var users = userService.GetNumberOfUsers();
if (users == 0)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] {users} Utilisateur(s) trouvé(s)", users);
return Ok(new KeyValuePair<string, int>("nbUsers", users));
}
[HttpGet("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserById(int id)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
return Ok(userService.GetUserById(id));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("user/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserByUsername(string username)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
return Ok(userService.GetUserByUsername(username));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
return NotFound("Utilisateur non trouvé !");
}
}
[HttpGet("user/email/{email}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetByEmail(string email)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'username {email} a été trouvé.", email);
return Ok(userService.GetUserByEmail(email));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {email}.", email);
return NotFound();
}
}
[HttpDelete("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUser(int id)
{
var success = userService.DeleteUser(id);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
return Ok();
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpDelete("user/username/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUserByUsername(string username)
{
var success = userService.DeleteUserByUsername(username);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec le pseudo {username} a été supprimé.",
username);
return Ok();
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec le pseudo {username}.", username);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(UserDto), 201)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 410)]
public IActionResult CreateUser([FromBody] UserDto dto)
{
if (dto.Username == null || dto.Password == null || dto.Email == null)
{
return BadRequest();
}
if (userService.IsEmailTaken(dto.Email))
{
return StatusCode(409, "Email déjà utilisé");
}
if (userService.IsUsernameTaken(dto.Username))
{
return StatusCode(410, "Username déjà utilisé");
}
// return Ok(userService.CreateUser(username, password, email, isAdmin));
logger.LogInformation(
"[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}",
dto.Username, dto.Password, dto.Email, dto.IsAdmin);
return Created(nameof(GetUsers),
userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin));
}
[HttpPut("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 409)]
public IActionResult UpdateUser(int id, [FromBody] UserDto userDto)
{
if (id != userDto.Id)
{
logger.LogError("[ERREUR] Problème ID - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
logger.LogError(
"[ERREUR] Problème controller - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if (userDto.Username == userService.GetUserById(id).Username && !userService.IsEmailTaken(userDto.Email)
|| (userDto.Email == userService.GetUserById(id).Email &&
!userService.IsUsernameTaken(userDto.Username))
|| (!userService.IsEmailTaken(userDto.Email) && !userService.IsUsernameTaken(userDto.Username)))
{
logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée",
id);
return Ok(userService.UpdateUser(id, userDto));
}
logger.LogError("[ERREUR] Email ou nom d'utilisateur déjà utilisé");
return StatusCode(409, "Email ou nom d'utilisateur déjà utilisé");
}
[HttpPut("user/promote/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult PromoteUser(int id)
{
var userPromoted = userService.GetUserById(id);
if (userPromoted != null)
{
userPromoted = userService.PromoteUser(id);
logger.LogInformation("[INFORMATION] La promotion de l'utilisateur avec l'id {id} a été effectuée");
return Ok(userPromoted);
}
else
{
logger.LogInformation("[INFORMATION] La promotion de l'utilisateur avec l'id {id} à échouée",
id);
return NotFound();
}
}
}

@ -0,0 +1,31 @@
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["API/API.csproj", "API/"]
COPY ["DbContextLib/DbContextLib.csproj", "DbContextLib/"]
COPY ["EntityFramework/Entities.csproj", "EntityFramework/"]
COPY ["Dto/Dto.csproj", "Dto/"]
COPY ["DbDataManager/DbDataManager.csproj", "DbDataManager/"]
COPY ["Model/Model.csproj", "Model/"]
COPY ["Shared/Shared.csproj", "Shared/"]
COPY ["StubbedContextLib/StubbedContextLib.csproj", "StubbedContextLib/"]
RUN dotnet restore "./API/./API.csproj"
COPY . .
WORKDIR "/src/API"
RUN dotnet build "./API.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENV ASPNETCORE_HTTP_PORTS=80
ENV DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE=false
ENTRYPOINT ["dotnet", "API.dll"]

@ -8,35 +8,74 @@ using Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Model;
using Shared;
using StubbedContextLib;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IQueryService<QueryDto>, QueryDataServiceApi>();
builder.Services.AddScoped<IUserService<UserEntity>, UserDataService>();
builder.Services.AddScoped<IUserService<UserDTO>, UserDataServiceApi>();
builder.Services.AddScoped<IUserService<UserDto>, UserDataServiceApi>();
builder.Services.AddScoped<IBlackListService<BlackListEntity>, BlackListDataService>();
builder.Services.AddScoped<IBlackListService<BlackListDto>, BlackListDataServiceAPI>();
builder.Services.AddScoped<IInquiryService<InquiryEntity>, InquiryDataService>();
builder.Services.AddScoped<IInquiryService<InquiryDTO>, InquiryDataServiceApi>();
builder.Services.AddScoped<IInquiryService<InquiryDto>, InquiryDataServiceApi>();
builder.Services.AddScoped<ISolutionService<SolutionEntity>, SolutionDataService>();
builder.Services.AddScoped<ISolutionService<SolutionDto>, SolutionDataServiceAPI>();
builder.Services.AddScoped<IInquiryTableService<InquiryTableEntity>, InquiryTableDataService>();
builder.Services.AddScoped<IInquiryTableService<InquiryTableDto>, InquiryTableDataServiceAPI>();
builder.Services.AddScoped<IParagraphService<ParagraphEntity>, ParagraphDataService>();
builder.Services.AddScoped<IParagraphService<ParagraphDTO>, ParagraphDataServiceApi>();
builder.Services.AddScoped<IParagraphService<ParagraphDto>, ParagraphDataServiceApi>();
builder.Services.AddScoped<ISuccessService<SuccessEntity>, SuccessDataService>();
builder.Services.AddScoped<ISuccessService<SuccessDTO>, SuccessDataServiceApi>();
builder.Services.AddScoped<ISuccessService<SuccessDto>, SuccessDataServiceApi>();
builder.Services.AddScoped<ILessonService<LessonEntity>, LessonDataService>();
builder.Services.AddScoped<ILessonService<LessonDTO>, LessonDataServiceApi>();
builder.Services.AddScoped<ILessonService<LessonDto>, LessonDataServiceApi>();
builder.Services.AddScoped<INotepadService<NotepadEntity>, NotepadDataService>();
builder.Services.AddScoped<INotepadService<NotepadDto>, NotepadDataServiceAPI>();
builder.Services.AddDbContext<DbContext,UserDbContext>((serviceProvider, options) =>
{
if (builder.Environment.IsProduction())
{
Console.WriteLine("I am in production mode");
var address = Environment.GetEnvironmentVariable("DB_HOST", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_HOST environment variable");
var database = Environment.GetEnvironmentVariable("DB_DATABASE", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_DATABASE environment variable");
var user = Environment.GetEnvironmentVariable("DB_USER", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_USER environment variable");
var password = Environment.GetEnvironmentVariable("DB_PASSWORD", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_PASSWORD environment variable");
var coString = $"Host={address};Database={database};Username={user};Password={password}";
options.UseNpgsql(coString);
}
else
{
Console.WriteLine("I am in development mode");
options.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse");
}
});
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<UserDbContext>();
builder.Services.AddDbContext<DbContext, UserDbContext>();
builder.Services.AddDbContext<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb"));
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>();
builder.Services.AddAuthorization();
builder.Services.AddApiVersioning(o =>
{
@ -78,16 +117,67 @@ builder.Services.AddSwaggerGen(option =>
}
});
});
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("https://localhost:7171")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
builder.Services.AddSingleton(configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
app.UseCors("AllowSpecificOrigin");
// Création de l'utilisateur admin pour la base de données Identity
using (var scope = app.Services.CreateScope())
{
app.UseSwagger();
app.UseSwaggerUI();
var services = scope.ServiceProvider;
// Création base de données via les migrations
await using var dbContext = services.GetRequiredService<UserDbContext>();
//await dbContext.Database.MigrateAsync();
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
try
{
var user = new IdentityUser { UserName = "admin@example.com", Email = "admin@example.com" };
var result = await userManager.CreateAsync(user, "Mdp_1234");
if (result.Succeeded)
{
Console.WriteLine("Utilisateur admin créé avec succès.");
}
else
{
foreach (var error in result.Errors)
{
Console.WriteLine($"Erreur lors de la création de l'utilisateur : {error.Description}");
}
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Une erreur s'est produite lors de la création de l'utilisateur.");
}
}
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();

@ -16,7 +16,10 @@
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5015",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"DB_HOST": "localhost",
"DB_DATABASE": "SQLuedo",
"DB_USER": "admin",
"DB_PASSWORD" : "motdepasse"
}
},
"https": {
@ -24,17 +27,23 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7259;http://localhost:5015",
"applicationUrl": "https://localhost:8081;http://localhost:5015",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"DB_HOST": "localhost",
"DB_DATABASE": "SQLuedo",
"DB_USER": "admin",
"DB_PASSWORD" : "motdepasse"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"launchUrl": "containers/johnnyratton-sqluedo-api",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"DB_HOST": "localhost",
"DB_DATABASE": "SQLuedo",
"DB_USER": "admin",
"DB_PASSWORD" : "motdepasse"
}
}
}

@ -0,0 +1,27 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class BlackListDataServiceAPI (IBlackListService<BlackListEntity> userService) : IBlackListService<BlackListDto>
{
public IEnumerable<BlackListDto> GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria) =>
userService.GetBannedUsers(page, number, orderCriteria).Select(b => b.FromEntityToDto());
public int GetNumberOfBannedUsers() => userService.GetNumberOfBannedUsers();
public BlackListDto? GetUserBannedByEmail(string email)
{
var res = userService.GetUserBannedByEmail(email);
if (res == null)
{
return null;
}
return res.FromEntityToDto();
}
public bool BanUser(string username) => userService.BanUser(username);
public bool UnbanUser(string email) => userService.UnbanUser(email);
}

@ -6,16 +6,16 @@ using Shared.Mapper;
namespace API.Service;
public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService) : IInquiryService<InquiryDTO>
public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService) : IInquiryService<InquiryDto>
{
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry)
public InquiryDto UpdateInquiry(int id, InquiryDto inquiry)
{
return inquiryService.UpdateInquiry(id, inquiry.FromDTOToEntity()).FromEntityToDTO();
return inquiryService.UpdateInquiry(id, inquiry.FromDtoToEntity()).FromEntityToDto();
}
public InquiryDTO CreateInquiry(string title, string description, bool isUser)
public InquiryDto CreateInquiry(string title, string description, bool isUser)
{
return inquiryService.CreateInquiry(title, description, isUser).FromEntityToDTO();
return inquiryService.CreateInquiry(title, description, isUser).FromEntityToDto();
}
public bool DeleteInquiry(int id)
@ -23,13 +23,18 @@ public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService
return inquiryService.DeleteInquiry(id);
}
public IEnumerable<InquiryDTO> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
public IEnumerable<InquiryDto> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
var inquiries = inquiryService.GetInquiries(page, number, orderCriteria);
return inquiries.Select(i => i.FromEntityToDTO()).ToList();
return inquiries.Select(i => i.FromEntityToDto()).ToList();
}
public InquiryDTO GetInquiryById(int id) => inquiryService.GetInquiryById(id).FromEntityToDTO();
public int GetNumberOfInquiries()
{
return inquiryService.GetNumberOfInquiries();
}
public InquiryDto GetInquiryById(int id) => inquiryService.GetInquiryById(id).FromEntityToDto();
public InquiryDTO GetInquiryByTitle(string title) => inquiryService.GetInquiryByTitle(title).FromEntityToDTO();
public InquiryDto GetInquiryByTitle(string title) => inquiryService.GetInquiryByTitle(title).FromEntityToDto();
}

@ -0,0 +1,13 @@
using Dto;
using Entities;
using Shared;
namespace API.Service;
public class InquiryTableDataServiceAPI(IInquiryTableService<InquiryTableEntity> inquiryTableService) : IInquiryTableService<InquiryTableDto>
{
public string GetDatabaseNameByInquiryId(int id)
{
return inquiryTableService.GetDatabaseNameByInquiryId(id);
}
}

@ -6,26 +6,31 @@ using Shared.Mapper;
namespace API.Service;
public class LessonDataServiceApi(ILessonService<LessonEntity> lessonService) : ILessonService<LessonDTO>
public class LessonDataServiceApi(ILessonService<LessonEntity> lessonService) : ILessonService<LessonDto>
{
public IEnumerable<LessonDTO> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
public IEnumerable<LessonDto> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
var lessonsEntities = lessonService.GetLessons(page, number, orderCriteria);
return lessonsEntities.Select(e => e.FromEntityToDTO()).ToList();
return lessonsEntities.Select(e => e.FromEntityToDto()).ToList();
}
public LessonDTO GetLessonById(int id) => lessonService.GetLessonById(id).FromEntityToDTO();
public int GetNumberOfLessons()
{
return lessonService.GetNumberOfLessons();
}
public LessonDto GetLessonById(int id) => lessonService.GetLessonById(id).FromEntityToDto();
public LessonDTO GetLessonByTitle(string title) => lessonService.GetLessonByTitle(title).FromEntityToDTO();
public LessonDto GetLessonByTitle(string title) => lessonService.GetLessonByTitle(title).FromEntityToDto();
public bool DeleteLesson(int id) => lessonService.DeleteLesson(id);
public LessonDTO UpdateLesson(int id, LessonDTO lesson) =>
lessonService.UpdateLesson(id, lesson.FromDTOToEntity()).FromEntityToDTO();
public LessonDto UpdateLesson(int id, LessonDto lesson) =>
lessonService.UpdateLesson(id, lesson.FromDtoToEntity()).FromEntityToDto();
public LessonDTO UpdateLesson(int id, LessonEntity lesson) =>
lessonService.UpdateLesson(id, lesson).FromEntityToDTO();
public LessonDto UpdateLesson(int id, LessonEntity lesson) =>
lessonService.UpdateLesson(id, lesson).FromEntityToDto();
public LessonDTO CreateLesson(string title, string lastPublisher, DateOnly? lastEdit) =>
lessonService.CreateLesson(title, lastPublisher, lastEdit).FromEntityToDTO();
public LessonDto CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit) =>
lessonService.CreateLesson(id, title, lastPublisher, lastEdit).FromEntityToDto();
}

@ -0,0 +1,24 @@
using Dto;
using Entities;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class NotepadDataServiceAPI(INotepadService<NotepadEntity> notepadService) : INotepadService<NotepadDto>
{
public NotepadDto GetNotepadFromUserAndInquiryId(int userId, int inquiryId)
{
return notepadService.GetNotepadFromUserAndInquiryId(userId, inquiryId).FromEntityToDto();
}
public void SetNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
notepadService.SetNotepadFromUserAndInquiryId(userId,inquiryId,notes);
}
public void UpdateNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
notepadService.UpdateNotepadFromUserAndInquiryId(userId,inquiryId,notes);
}
}

@ -7,25 +7,29 @@ using Shared.Mapper;
namespace API.Service;
public class ParagraphDataServiceApi(IParagraphService<ParagraphEntity> paragraphService)
: IParagraphService<ParagraphDTO>
: IParagraphService<ParagraphDto>
{
public IEnumerable<ParagraphDTO> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
public IEnumerable<ParagraphDto> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
var paragraphsEntities = paragraphService.GetParagraphs(page, number, orderCriteria);
return paragraphsEntities.Select(e => e.FromEntityToDTO()).ToList();
return paragraphsEntities.Select(e => e.FromEntityToDto()).ToList();
}
public ParagraphDTO GetParagraphById(int id) => paragraphService.GetParagraphById(id).FromEntityToDTO();
public IEnumerable<ParagraphDto> GetParagraphsByLessonId(int lessonId)
{
return paragraphService.GetParagraphsByLessonId(lessonId).Select(p => p.FromEntityToDto());
}
public ParagraphDto GetParagraphById(int id) => paragraphService.GetParagraphById(id).FromEntityToDto();
public ParagraphDTO GetParagraphByTitle(string title) =>
paragraphService.GetParagraphByTitle(title).FromEntityToDTO();
public ParagraphDto GetParagraphByTitle(string title) =>
paragraphService.GetParagraphByTitle(title).FromEntityToDto();
public bool DeleteParagraph(int id) => paragraphService.DeleteParagraph(id);
public ParagraphDTO UpdateParagraph(int id, ParagraphDTO paragraph) =>
paragraphService.UpdateParagraph(id, paragraph.FromDTOToEntity()).FromEntityToDTO();
public ParagraphDto UpdateParagraph(int id, ParagraphDto paragraph) =>
paragraphService.UpdateParagraph(id, paragraph.FromDtoToEntity()).FromEntityToDto();
public ParagraphDTO CreateParagraph(string title, string content, string info, string query, string comment,
int lessonId) =>
paragraphService.CreateParagraph(title, content, info, query, comment, lessonId).FromEntityToDTO();
public ParagraphDto CreateParagraph(string contentTitle, string contentContent,string title, string content, string info, string query, string comment,
int lessonId) => paragraphService.CreateParagraph(contentTitle, contentContent, title, content, info, query, comment, lessonId).FromEntityToDto();
}

@ -0,0 +1,176 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Npgsql;
using Shared;
using Shared.Mapper;
using Microsoft.Extensions.Configuration;
using System.Text;
using Newtonsoft.Json;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace API.Service;
public class QueryDataServiceApi : IQueryService<QueryDto>{
private readonly IConfiguration _configuration;
public QueryDataServiceApi(IConfiguration configuration)
{
_configuration = configuration;
}
public QueryDto ExecuteQuery(string query, string database)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
connectionString = connectionString.Replace("{database}", database);
if (string.IsNullOrEmpty(database))
{
return new QueryDto { Result = "Le nom de la base de données est requis." };
}
try
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
{
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<Dictionary<string, object>> resultList = new List<Dictionary<string, object>>();
List<string> columnNames = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
columnNames.Add(reader.GetName(i));
}
while (reader.Read())
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[columnNames[i]] = reader[i].ToString();
}
resultList.Add(row);
}
string resultJson = JsonConvert.SerializeObject(resultList);
QueryDto queryDto = new QueryDto { Result = resultJson };
return queryDto;
}
}
}
}
catch (Exception ex)
{
return new QueryDto { Result = ex.Message };
}
}
public QueryDto GetTables(string database)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
connectionString = connectionString.Replace("{database}", database);
try
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand())
{
command.Connection = connection;
// Donner et exclure les bonnes permissions au rôle en question
// GRANT SELECT ON TABLE information_schema.tables TO votre_utilisateur;
// GRANT SELECT ON TABLE information_schema.columns TO votre_utilisateur;
// REVOKE ALL ON SCHEMA information_schema FROM PUBLIC;
command.CommandText =
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';";
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<string> tableNames = new List<string>();
while (reader.Read())
{
tableNames.Add(reader["table_name"].ToString());
}
List<object> tablesDict = new List<object>();
foreach (string tableName in tableNames)
{
tablesDict.Add(new { TableName = tableName});
}
string tablesJson = JsonConvert.SerializeObject(tablesDict);
QueryDto queryDto = new QueryDto { Result = tablesJson };
return queryDto;
}
}
}
}
catch (Exception ex)
{
return new QueryDto { Result = ex.Message };
}
}
public QueryDto GetColumns(string database, string table)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
connectionString = connectionString.Replace("{database}", database);
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand())
{
command.Connection = connection;
// Donner et exclure les bonnes permissions au rôle en question
//GRANT SELECT ON TABLE information_schema.tables TO votre_utilisateur;
//GRANT SELECT ON TABLE information_schema.columns TO votre_utilisateur;
//REVOKE ALL ON SCHEMA information_schema FROM PUBLIC;
command.CommandText =
$"SELECT column_name FROM information_schema.columns WHERE table_name = '{table}';";
Console.WriteLine(command.CommandText);
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<string> columnsNames = new List<string>();
while (reader.Read())
{
columnsNames.Add(reader["column_name"].ToString());
}
/*List<object> columnsDict = new List<object>();
foreach (string colName in columnsNames)
{
columnsDict.Add(new { ColumnName = colName});
}*/
string tablesJson = JsonConvert.SerializeObject(columnsNames);
Console.WriteLine(tablesJson);
QueryDto queryDto = new QueryDto { Result = tablesJson };
return queryDto;
}
}
}
}
}

@ -0,0 +1,14 @@
using Dto;
using Entities;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class SolutionDataServiceAPI(ISolutionService<SolutionEntity> solutionService) : ISolutionService<SolutionDto>
{
public SolutionDto GetSolutionByInquiryId(int id)
{
return solutionService.GetSolutionByInquiryId(id).FromEntityToDto();
}
}

@ -6,23 +6,25 @@ using Shared.Mapper;
namespace API.Service;
public class SuccessDataServiceApi(ISuccessService<SuccessEntity> sucessService) : ISuccessService<SuccessDTO>
public class SuccessDataServiceApi(ISuccessService<SuccessEntity> sucessService) : ISuccessService<SuccessDto>
{
public IEnumerable<SuccessDTO> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
public IEnumerable<SuccessDto> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
var successesEntities = sucessService.GetSuccesses(page, number, orderCriteria);
return successesEntities.Select(e => e.FromEntityToDTO()).ToList();
return successesEntities.Select(e => e.FromEntityToDto()).ToList();
}
public SuccessDTO GetSuccessByUserId(int id) => sucessService.GetSuccessByUserId(id).FromEntityToDTO();
public IEnumerable<SuccessDto> GetSuccessesByUserId(int id) =>
sucessService.GetSuccessesByUserId(id).Select(s => s.FromEntityToDto());
public SuccessDTO GetSuccessByInquiryId(int id) => sucessService.GetSuccessByInquiryId(id).FromEntityToDTO();
public IEnumerable<SuccessDto> GetSuccessesByInquiryId(int id) =>
sucessService.GetSuccessesByInquiryId(id).Select(s => s.FromEntityToDto());
public bool DeleteSuccess(int id) => sucessService.DeleteSuccess(id);
public bool DeleteSuccess(int idUser, int idInquiry) => sucessService.DeleteSuccess(idUser, idInquiry);
public SuccessDTO UpdateSuccess(int id, SuccessDTO success) =>
sucessService.UpdateSuccess(id, success.FromDTOToEntity()).FromEntityToDTO();
public SuccessDto UpdateSuccess(int idUser, int idInquiry, SuccessDto success) =>
sucessService.UpdateSuccess(idUser, idInquiry, success.FromDtoToEntity()).FromEntityToDto();
public SuccessDTO CreateSuccess(int userId, int inquiryId, bool isFinished) =>
sucessService.CreateSuccess(userId, inquiryId, isFinished).FromEntityToDTO();
public SuccessDto CreateSuccess(int userId, int inquiryId, bool isFinished) =>
sucessService.CreateSuccess(userId, inquiryId, isFinished).FromEntityToDto();
}

@ -6,23 +6,43 @@ using Shared.Mapper;
namespace API.Service;
public class UserDataServiceApi(IUserService<UserEntity> userService) : IUserService<UserDTO>
public class UserDataServiceApi(IUserService<UserEntity> userService) : IUserService<UserDto>
{
public IEnumerable<UserDTO> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
public IEnumerable<UserDto> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var usersEntities = userService.GetUsers(page, number, orderCriteria);
return usersEntities.Select(e => e.FromEntityToDTO()).ToList();
return usersEntities.Select(e => e.FromEntityToDto()).ToList();
}
public IEnumerable<UserDto> GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var usersEntities = userService.GetNotAdminUsers(page, number, orderCriteria);
return usersEntities.Select(e => e.FromEntityToDto()).ToList();
}
public int GetNumberOfUsers()
{
return userService.GetNumberOfUsers();
}
public UserDto GetUserById(int id) => userService.GetUserById(id).FromEntityToDto();
public UserDTO GetUserById(int id) => userService.GetUserById(id).FromEntityToDTO();
public UserDTO GetUserByUsername(string username) => userService.GetUserByUsername(username).FromEntityToDTO();
public UserDto GetUserByUsername(string username) => userService.GetUserByUsername(username).FromEntityToDto();
public UserDto GetUserByEmail(string email) => userService.GetUserByEmail(email).FromEntityToDto();
public bool DeleteUser(int id) => userService.DeleteUser(id);
public bool DeleteUserByUsername(string username) => userService.DeleteUserByUsername(username);
public UserDto UpdateUser(int id, UserDto user) =>
userService.UpdateUser(id, user.FromDtoToEntity()).FromEntityToDto();
public UserDto CreateUser(string username, string password, string email, bool isAdmin) =>
userService.CreateUser(username, password, email, isAdmin).FromEntityToDto();
public bool IsEmailTaken(string email) => userService.IsEmailTaken(email);
public UserDTO UpdateUser(int id, UserDTO user) =>
userService.UpdateUser(id, user.FromDTOToEntity()).FromEntityToDTO();
public bool IsUsernameTaken(string username) => userService.IsUsernameTaken(username);
public UserDTO CreateUser(string username, string password, string email, bool isAdmin) =>
userService.CreateUser(username, password, email, isAdmin).FromEntityToDTO();
public UserDto PromoteUser(int id) =>
userService.PromoteUser(id).FromEntityToDto();
}

@ -5,5 +5,8 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Username=admin;Password=motdepasse;Database={database}"
}
}

@ -0,0 +1,595 @@
// <auto-generated />
using System;
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DbContextLib.Migrations
{
[DbContext(typeof(UserDbContext))]
[Migration("20240403065352_v1")]
partial class v1
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.HasSequence("ContentLessonEntitySequence");
modelBuilder.Entity("Entities.BlackListEntity", b =>
{
b.Property<string>("Email")
.HasColumnType("text");
b.Property<DateOnly>("ExpirationDate")
.HasColumnType("date");
b.HasKey("Email");
b.ToTable("BlackList");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValueSql("nextval('\"ContentLessonEntitySequence\"')");
NpgsqlPropertyBuilderExtensions.UseSequence(b.Property<int>("Id"));
b.Property<string>("ContentContent")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentTitle")
.IsRequired()
.HasColumnType("text");
b.Property<int>("LessonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("LessonId");
b.ToTable((string)null);
b.UseTpcMappingStrategy();
});
modelBuilder.Entity("Entities.InquiryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsUser")
.HasColumnType("boolean");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Inquiries");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("ConnectionInfo")
.IsRequired()
.HasColumnType("text");
b.Property<string>("DatabaseName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("InquiryTable");
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateOnly>("LastEdit")
.HasColumnType("date");
b.Property<string>("LastPublisher")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Lesson");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("InquiryId");
b.HasIndex("UserId");
b.ToTable("Notepad");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("Explaination")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderPlace")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderWeapon")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererFirstName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererLastName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("Solution");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<bool>("IsFinished")
.HasColumnType("boolean");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("InquiryId");
b.HasIndex("UserId");
b.ToTable("Success");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Entities.ParagraphEntity", b =>
{
b.HasBaseType("Entities.ContentLessonEntity");
b.Property<string>("Comment")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Query")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.ToTable("Paragraph");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.HasOne("Entities.LessonEntity", "Lesson")
.WithMany("Content")
.HasForeignKey("LessonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Lesson");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Navigation("Content");
});
#pragma warning restore 612, 618
}
}
}

@ -0,0 +1,452 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DbContextLib.Migrations
{
/// <inheritdoc />
public partial class v1 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateSequence(
name: "ContentLessonEntitySequence");
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
PasswordHash = table.Column<string>(type: "text", nullable: true),
SecurityStamp = table.Column<string>(type: "text", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
PhoneNumber = table.Column<string>(type: "text", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "BlackList",
columns: table => new
{
Email = table.Column<string>(type: "text", nullable: false),
ExpirationDate = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BlackList", x => x.Email);
});
migrationBuilder.CreateTable(
name: "Inquiries",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
IsUser = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Inquiries", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Lesson",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
LastPublisher = table.Column<string>(type: "text", nullable: false),
LastEdit = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Lesson", x => x.Id);
});
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Username = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
IsAdmin = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RoleId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "text", nullable: false),
ProviderKey = table.Column<string>(type: "text", nullable: false),
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
UserId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
LoginProvider = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "InquiryTable",
columns: table => new
{
OwnerId = table.Column<int>(type: "integer", nullable: false),
DatabaseName = table.Column<string>(type: "text", nullable: false),
ConnectionInfo = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_InquiryTable", x => x.OwnerId);
table.ForeignKey(
name: "FK_InquiryTable_Inquiries_OwnerId",
column: x => x.OwnerId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Solution",
columns: table => new
{
OwnerId = table.Column<int>(type: "integer", nullable: false),
MurdererFirstName = table.Column<string>(type: "text", nullable: false),
MurdererLastName = table.Column<string>(type: "text", nullable: false),
MurderPlace = table.Column<string>(type: "text", nullable: false),
MurderWeapon = table.Column<string>(type: "text", nullable: false),
Explaination = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Solution", x => x.OwnerId);
table.ForeignKey(
name: "FK_Solution_Inquiries_OwnerId",
column: x => x.OwnerId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Paragraph",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false, defaultValueSql: "nextval('\"ContentLessonEntitySequence\"')"),
ContentContent = table.Column<string>(type: "text", nullable: false),
ContentTitle = table.Column<string>(type: "text", nullable: false),
LessonId = table.Column<int>(type: "integer", nullable: false),
Title = table.Column<string>(type: "text", nullable: false),
Content = table.Column<string>(type: "text", nullable: false),
Info = table.Column<string>(type: "text", nullable: false),
Query = table.Column<string>(type: "text", nullable: false),
Comment = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Paragraph", x => x.Id);
table.ForeignKey(
name: "FK_Paragraph_Lesson_LessonId",
column: x => x.LessonId,
principalTable: "Lesson",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Notepad",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
InquiryId = table.Column<int>(type: "integer", nullable: false),
Notes = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Notepad", x => x.Id);
table.ForeignKey(
name: "FK_Notepad_Inquiries_InquiryId",
column: x => x.InquiryId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Notepad_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Success",
columns: table => new
{
InquiryId = table.Column<int>(type: "integer", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: false),
IsFinished = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Success", x => x.InquiryId);
table.ForeignKey(
name: "FK_Success_Inquiries_InquiryId",
column: x => x.InquiryId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Success_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Notepad_InquiryId",
table: "Notepad",
column: "InquiryId");
migrationBuilder.CreateIndex(
name: "IX_Notepad_UserId",
table: "Notepad",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Paragraph_LessonId",
table: "Paragraph",
column: "LessonId");
migrationBuilder.CreateIndex(
name: "IX_Success_UserId",
table: "Success",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "BlackList");
migrationBuilder.DropTable(
name: "InquiryTable");
migrationBuilder.DropTable(
name: "Notepad");
migrationBuilder.DropTable(
name: "Paragraph");
migrationBuilder.DropTable(
name: "Solution");
migrationBuilder.DropTable(
name: "Success");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "Lesson");
migrationBuilder.DropTable(
name: "Inquiries");
migrationBuilder.DropTable(
name: "User");
migrationBuilder.DropSequence(
name: "ContentLessonEntitySequence");
}
}
}

@ -0,0 +1,592 @@
// <auto-generated />
using System;
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DbContextLib.Migrations
{
[DbContext(typeof(UserDbContext))]
partial class UserDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.HasSequence("ContentLessonEntitySequence");
modelBuilder.Entity("Entities.BlackListEntity", b =>
{
b.Property<string>("Email")
.HasColumnType("text");
b.Property<DateOnly>("ExpirationDate")
.HasColumnType("date");
b.HasKey("Email");
b.ToTable("BlackList");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValueSql("nextval('\"ContentLessonEntitySequence\"')");
NpgsqlPropertyBuilderExtensions.UseSequence(b.Property<int>("Id"));
b.Property<string>("ContentContent")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentTitle")
.IsRequired()
.HasColumnType("text");
b.Property<int>("LessonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("LessonId");
b.ToTable((string)null);
b.UseTpcMappingStrategy();
});
modelBuilder.Entity("Entities.InquiryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsUser")
.HasColumnType("boolean");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Inquiries");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("ConnectionInfo")
.IsRequired()
.HasColumnType("text");
b.Property<string>("DatabaseName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("InquiryTable");
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateOnly>("LastEdit")
.HasColumnType("date");
b.Property<string>("LastPublisher")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Lesson");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("InquiryId");
b.HasIndex("UserId");
b.ToTable("Notepad");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("Explaination")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderPlace")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderWeapon")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererFirstName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererLastName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("Solution");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<bool>("IsFinished")
.HasColumnType("boolean");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("InquiryId");
b.HasIndex("UserId");
b.ToTable("Success");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Entities.ParagraphEntity", b =>
{
b.HasBaseType("Entities.ContentLessonEntity");
b.Property<string>("Comment")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Query")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.ToTable("Paragraph");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.HasOne("Entities.LessonEntity", "Lesson")
.WithMany("Content")
.HasForeignKey("LessonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Lesson");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Navigation("Content");
});
#pragma warning restore 612, 618
}
}
}

@ -23,23 +23,23 @@ namespace DbContextLib
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse");
optionsBuilder.UseNpgsql(Environment.GetEnvironmentVariable("CO_STRING", EnvironmentVariableTarget.Process));
//optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse");
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
protected override void OnModelCreating(ModelBuilder builder)
{
// Permet d'avoir les champs de la classe mère dans les classes filles et de ne pas avoir de table pour la classe mère
modelBuilder.Entity<ContentLessonEntity>().UseTpcMappingStrategy();
builder.Entity<ContentLessonEntity>().UseTpcMappingStrategy();
modelBuilder.Entity<SuccessEntity>().HasKey(s => s.UserId);
modelBuilder.Entity<SuccessEntity>().HasKey(s => s.InquiryId);
modelBuilder.Entity<InquiryEntity>().HasKey(s => s.Id);
base.OnModelCreating(modelBuilder);
builder.Entity<SuccessEntity>().HasKey(s => s.UserId);
builder.Entity<SuccessEntity>().HasKey(s => s.InquiryId);
builder.Entity<InquiryEntity>().HasKey(s => s.Id);
base.OnModelCreating(builder);
}
}
}

@ -0,0 +1,85 @@
using DbContextLib;
using Entities;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class BlackListDataService : IBlackListService<BlackListEntity>
{
private UserDbContext DbContext { get; set; }
public BlackListDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public int GetNumberOfBannedUsers()
{
return DbContext.BlackLists.Count();
}
public IEnumerable<BlackListEntity> GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<BlackListEntity> query = DbContext.BlackLists.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case BlackListOdrerCriteria.None:
break;
case BlackListOdrerCriteria.ByEmail:
query = query.OrderBy(s => s.Email);
break;
case BlackListOdrerCriteria.ByExpirationDate:
query = query.OrderBy(s => s.ExpirationDate);
break;
default:
break;
}
var blackList = query.ToList();
return blackList;
}
public BlackListEntity? GetUserBannedByEmail(string email)
{
var blackListEntity = DbContext.BlackLists.FirstOrDefault(b => b.Email == email);
return blackListEntity;
}
public bool BanUser(string username)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
return false;
}
DbContext.BlackLists.Add(new BlackListEntity
{ Email = userEntity.Email, ExpirationDate = DateOnly.FromDateTime(DateTime.Now.AddYears(2)) });
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
}
public bool UnbanUser(string email)
{
var blackListEntity = DbContext.BlackLists.FirstOrDefault(b => b.Email == email);
if (blackListEntity == null)
{
return false;
}
DbContext.BlackLists.Remove(blackListEntity);
DbContext.SaveChangesAsync();
return true;
}
}

@ -18,7 +18,15 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
public IEnumerable<InquiryEntity> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
IQueryable<InquiryEntity> query = DbContext.Inquiries.Skip((page - 1) * number).Take(number);
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<InquiryEntity> query = DbContext.Inquiries;
switch (orderCriteria)
{
case InquiryOrderCriteria.None:
@ -32,14 +40,23 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
case InquiryOrderCriteria.ByIsUser:
query = query.OrderBy(s => s.IsUser);
break;
case InquiryOrderCriteria.ById:
query = query.OrderBy(s => s.Id);
break;
default:
break;
}
query = query.Skip((page - 1) * number).Take(number);
var inquiries = query.ToList();
return inquiries;
}
public int GetNumberOfInquiries()
{
return DbContext.Inquiries.Count();
}
public InquiryEntity GetInquiryById(int id)
{
var inquiryEntity = DbContext.Inquiries.FirstOrDefault(i => i.Id == id);
@ -64,7 +81,12 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
public InquiryEntity CreateInquiry(string title, string description, bool isUser)
{
var newInquiryEntity = new InquiryEntity(title, description, isUser);
var newInquiryEntity = new InquiryEntity
{
Title = title,
Description = description,
IsUser = isUser
};
DbContext.Inquiries.Add(newInquiryEntity);
DbContext.SaveChangesAsync();
return newInquiryEntity;
@ -79,7 +101,7 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
}
DbContext.Inquiries.Remove(inquiryEntity);
DbContext.SaveChangesAsync();
DbContext.SaveChanges();
return true;
}

@ -0,0 +1,27 @@
using DbContextLib;
using Entities;
using Shared;
namespace DbDataManager.Service;
public class InquiryTableDataService : IInquiryTableService<InquiryTableEntity>
{
private UserDbContext DbContext { get; set; }
public InquiryTableDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public string GetDatabaseNameByInquiryId(int id)
{
var inquiryTable = DbContext.InquiryTables.FirstOrDefault(i => i.OwnerId == id);
if (inquiryTable == null)
{
throw new ArgumentException($"Erreur, impossible de trouver l'objet InquiryTable pour l'enquête d'id {id}",
nameof(id));
}
return inquiryTable.DatabaseName;
}
}

@ -1,5 +1,6 @@
using DbContextLib;
using Entities;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
@ -18,7 +19,17 @@ public class LessonDataService : ILessonService<LessonEntity>
public IEnumerable<LessonEntity> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
IQueryable<LessonEntity> query = DbContext.Lessons.Skip((page - 1) * number).Take(number);
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<LessonEntity> query = DbContext.Lessons;
switch (orderCriteria)
{
case LessonOrderCriteria.None:
@ -32,14 +43,25 @@ public class LessonDataService : ILessonService<LessonEntity>
case LessonOrderCriteria.ByLastEdit:
query = query.OrderBy(s => s.LastEdit);
break;
case LessonOrderCriteria.ById:
query = query.OrderBy(s => (int) s.Id);
break;
default:
break;
}
query = query.Skip((page - 1) * number).Take(number);
var lessons = query.ToList();
return lessons;
}
public int GetNumberOfLessons()
{
return DbContext.Lessons.Count();
}
public LessonEntity GetLessonById(int id)
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(u => u.Id == id);
@ -66,12 +88,10 @@ public class LessonDataService : ILessonService<LessonEntity>
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (lessonEntity == null)
{
return false;
}
DbContext.Lessons.Remove(lessonEntity);
DbContext.SaveChangesAsync();
DbContext.SaveChanges();
return true;
}
@ -79,30 +99,28 @@ public class LessonDataService : ILessonService<LessonEntity>
{
var updatingLesson = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (updatingLesson == null)
{
throw new ArgumentException("Impossible de trouver la leçon", nameof(id));
}
foreach (var pptt in typeof(LessonEntity).GetProperties()
.Where(p => p.CanWrite && p.Name != nameof(LessonEntity.Id)))
{
pptt.SetValue(updatingLesson, pptt.GetValue(lesson));
}
updatingLesson.Title = lesson.Title;
updatingLesson.LastPublisher = lesson.LastPublisher;
updatingLesson.LastEdit = lesson.LastEdit;
DbContext.SaveChangesAsync();
DbContext.SaveChanges();
return updatingLesson;
}
public LessonEntity CreateLesson(string title, string lastPublisher, DateOnly? lastEdit)
public LessonEntity CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit)
{
var newLessonEntity = new LessonEntity()
{
Id = id > 0 && DbContext.Lessons.All(l => l.Id != id) ? id : 0,
Title = title,
LastPublisher = lastPublisher,
LastEdit = lastEdit,
};
DbContext.Lessons.Add(newLessonEntity);
DbContext.SaveChangesAsync();
DbContext.SaveChanges();
return newLessonEntity;
}
}

@ -0,0 +1,68 @@
using DbContextLib;
using Entities;
using Shared;
namespace DbDataManager.Service;
public class NotepadDataService : INotepadService<NotepadEntity>
{
private UserDbContext DbContext { get; set; }
public NotepadDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public NotepadEntity GetNotepadFromUserAndInquiryId(int userId, int inquiryId)
{
var user = DbContext.Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
{
throw new ArgumentException("Erreur, aucun utilisateur ne possède l'ID fourni");
}
var inquiry = DbContext.Inquiries.FirstOrDefault(i => i.Id == inquiryId);
if (inquiry == null)
{
throw new ArgumentException("Erreur, aucune enquête ne possède l'ID fourni");
}
var notepad = DbContext.Notepads.FirstOrDefault(n => n.UserId == userId && n.InquiryId == inquiryId);
if (notepad == null)
{
throw new ArgumentException("Erreur, aucun bloc-notes n'existe pour l'utilisateur et l'enquête donnés");
}
return notepad;
}
public void SetNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
var user = DbContext.Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
{
throw new ArgumentException("Erreur, aucun utilisateur ne possède l'ID fourni");
}
var inquiry = DbContext.Inquiries.FirstOrDefault(i => i.Id == inquiryId);
if (inquiry == null)
{
throw new ArgumentException("Erreur, aucune enquête ne possède l'ID fourni");
}
var notepad = DbContext.Notepads.FirstOrDefault(n => n.UserId == userId && n.InquiryId == inquiryId);
if (notepad != null)
{
notepad.Notes = notes;
//throw new ArgumentException("Erreur, un bloc-notes existe déjà pour l'utilisateur et l'enquête donnée");
}
else
{
DbContext.Notepads.Add(new NotepadEntity { UserId = userId, InquiryId = inquiryId, Notes = notes });
}
DbContext.SaveChangesAsync();
}
public void UpdateNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
var notepad = GetNotepadFromUserAndInquiryId(userId, inquiryId);
notepad.Notes = notes;
DbContext.SaveChangesAsync();
}
}

@ -18,6 +18,14 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
public IEnumerable<ParagraphEntity> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<ParagraphEntity> query = DbContext.Paragraphs.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
@ -46,6 +54,17 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
return paragraphs;
}
public IEnumerable<ParagraphEntity> GetParagraphsByLessonId(int lessonId)
{
var lesson = DbContext.Lessons.FirstOrDefault(l => l.Id == lessonId);
if (lesson == null)
{
throw new ArgumentException($"Erreur, la leçon ayant pour id {lessonId} est introuvable.");
}
var list = DbContext.Paragraphs.Where(p => p.LessonId == lessonId);
return list;
}
public ParagraphEntity GetParagraphById(int id)
{
var paragraphEntity = DbContext.Paragraphs.FirstOrDefault(u => u.Id == id);
@ -77,7 +96,7 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
}
DbContext.Paragraphs.Remove(paragraphEntity);
DbContext.SaveChangesAsync();
DbContext.SaveChanges();
return true;
}
@ -94,16 +113,25 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
{
pptt.SetValue(updatingParagraph, pptt.GetValue(paragraph));
}
/*updatingParagraph.ContentTitle = paragraph.ContentTitle;
updatingParagraph.ContentContent = paragraph.ContentContent;
updatingParagraph.Title = paragraph.Title;
updatingParagraph.Content = paragraph.Content;
updatingParagraph.Info = paragraph.Info;
updatingParagraph.Query = paragraph.Query;
updatingParagraph.Comment = paragraph.Comment;
updatingParagraph.LessonId = paragraph.LessonId;*/
DbContext.SaveChangesAsync();
return updatingParagraph;
}
public ParagraphEntity CreateParagraph(string title, string content, string info, string query, string comment,
public ParagraphEntity CreateParagraph(string contentTitle, string contentContent, string title, string content, string info, string query, string comment,
int lessonId)
{
var newParagraphEntity = new ParagraphEntity()
{
ContentContent = contentContent,
ContentTitle = contentTitle,
Title = title,
Content = content,
Info = info,

@ -0,0 +1,26 @@
using DbContextLib;
using Entities;
using Shared;
namespace DbDataManager.Service;
public class SolutionDataService : ISolutionService<SolutionEntity>
{
private UserDbContext DbContext { get; set; }
public SolutionDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public SolutionEntity GetSolutionByInquiryId(int id)
{
var solution = DbContext.Solutions.FirstOrDefault(s => s.OwnerId == id);
if (solution == null)
{
throw new ArgumentException($"Impossible de trouver la solution pour l'enquête d'id {id}", nameof(id));
}
return solution;
}
}

@ -18,6 +18,14 @@ public class SuccessDataService : ISuccessService<SuccessEntity>
public IEnumerable<SuccessEntity> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<SuccessEntity> query = DbContext.Successes.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
@ -40,31 +48,23 @@ public class SuccessDataService : ISuccessService<SuccessEntity>
return successes;
}
public SuccessEntity GetSuccessByUserId(int id)
public IEnumerable<SuccessEntity> GetSuccessesByUserId(int id)
{
var userEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == id);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver le succès", nameof(id));
}
return userEntity;
UserIdIsValid(id);
var successes = DbContext.Successes.Where(u => u.UserId == id);
return successes;
}
public SuccessEntity GetSuccessByInquiryId(int id)
public IEnumerable<SuccessEntity> GetSuccessesByInquiryId(int id)
{
var userEntity = DbContext.Successes.FirstOrDefault(u => u.InquiryId == id);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver le succès", nameof(id));
}
return userEntity;
InquiryIdIsValid(id);
var successes = DbContext.Successes.Where(u => u.InquiryId == id);
return successes;
}
public bool DeleteSuccess(int id)
public bool DeleteSuccess(int idUser, int idInquiry)
{
var successEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == id);
var successEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == idUser && u.InquiryId == idInquiry);
if (successEntity == null)
{
return false;
@ -75,34 +75,63 @@ public class SuccessDataService : ISuccessService<SuccessEntity>
return true;
}
public SuccessEntity UpdateSuccess(int id, SuccessEntity success)
public SuccessEntity UpdateSuccess(int idUser, int idInquiry, SuccessEntity success)
{
var updatingSuccess = DbContext.Successes.FirstOrDefault(u => u.UserId == id);
if (updatingSuccess == null)
{
throw new ArgumentException("Impossible de trouver le succès", nameof(id));
}
AreValdIds(idUser, idInquiry);
foreach (var pptt in typeof(SuccessEntity).GetProperties().Where(p =>
var updatingSuccess =
DbContext.Successes.FirstOrDefaultAsync(u => u.UserId == idUser && u.InquiryId == idInquiry);
if (updatingSuccess.Result == null) throw new ArgumentException("success", nameof(idUser));
/*foreach (var pptt in typeof(SuccessEntity).GetProperties().Where(p =>
p.CanWrite && p.Name != nameof(SuccessEntity.UserId) && p.Name != nameof(SuccessEntity.InquiryId)))
{
pptt.SetValue(updatingSuccess, pptt.GetValue(success));
}
}*/
updatingSuccess.Result.IsFinished = success.IsFinished;
DbContext.SaveChangesAsync();
return updatingSuccess;
return updatingSuccess.Result;
}
public SuccessEntity CreateSuccess(int userId, int inquiryId, bool isFinished)
{
var newSuccessEntity = new SuccessEntity()
AreValdIds(userId, inquiryId);
var newSuccessEntity = new SuccessEntity
{
UserId = userId,
InquiryId = inquiryId,
IsFinished = isFinished,
};
var success = DbContext.Successes.FirstOrDefaultAsync(s => s.UserId == userId && s.InquiryId == inquiryId);
if (success.Result != null) throw new ArgumentException("success", nameof(userId));
DbContext.Successes.Add(newSuccessEntity);
DbContext.SaveChangesAsync();
return newSuccessEntity;
}
private void AreValdIds(int userId, int inquiryId)
{
UserIdIsValid(userId);
InquiryIdIsValid(inquiryId);
}
private void UserIdIsValid(int userId)
{
var user = DbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (user.Result == null)
{
throw new ArgumentException("userId");
}
}
private void InquiryIdIsValid(int inquiryId)
{
var inquiry = DbContext.Inquiries.FirstOrDefaultAsync(u => u.Id == inquiryId);
if (inquiry.Result == null)
{
throw new ArgumentException("inquiryId");
}
}
}

@ -37,9 +37,65 @@ public class UserDataService : IUserService<UserEntity>
return userEntity;
}
public UserEntity GetUserByEmail(string email)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Email == email);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(email));
}
return userEntity;
}
public IEnumerable<UserEntity> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
IQueryable<UserEntity> query = DbContext.Users.Skip((page - 1) * number).Take(number);
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<UserEntity> query = DbContext.Users;
switch (orderCriteria)
{
case UserOrderCriteria.None:
break;
case UserOrderCriteria.ById:
query = query.OrderBy(s => s.Id);
break;
case UserOrderCriteria.ByUsername:
query = query.OrderBy(s => s.Username);
break;
case UserOrderCriteria.ByEmail:
query = query.OrderBy(s => s.Email);
break;
case UserOrderCriteria.ByIsAdmin:
query = query.OrderBy(s => s.IsAdmin);
break;
default:
break;
}
query = query.Skip((page - 1) * number).Take(number);
var users = query.ToList();
return users;
}
public IEnumerable<UserEntity> GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<UserEntity> query = DbContext.Users.Where(u => u.IsAdmin == false).Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case UserOrderCriteria.None:
@ -63,6 +119,10 @@ public class UserDataService : IUserService<UserEntity>
var users = query.ToList();
return users;
}
public int GetNumberOfUsers()
{
return DbContext.Users.Count();
}
public bool DeleteUser(int id)
{
@ -77,6 +137,18 @@ public class UserDataService : IUserService<UserEntity>
return true;
}
public bool DeleteUserByUsername(string username)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
return false;
}
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
}
public UserEntity UpdateUser(int id, UserEntity user)
{
var updatingUser = DbContext.Users.FirstOrDefault(u => u.Id == id);
@ -108,4 +180,24 @@ public class UserDataService : IUserService<UserEntity>
DbContext.SaveChangesAsync();
return newUserEntity;
}
public bool IsEmailTaken(string email)
{
var isEmail = DbContext.Users.Any(u => u.Email == email);
return isEmail;
}
public bool IsUsernameTaken(string username)
{
var isUsername = DbContext.Users.Any(u => u.Username == username);
return isUsername;
}
public UserEntity PromoteUser(int id)
{
var userEdit = GetUserById(id);
var newUserEntity = UpdateUser(id,new UserEntity{Id = id,Username = userEdit.Username,Password = userEdit.Password,Email = userEdit.Email,IsAdmin = true});
DbContext.SaveChangesAsync();
return newUserEntity;
}
}

@ -1,12 +1,15 @@
namespace Dto;
public class BlackListDTO
public class BlackListDto
{
public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
public BlackListDTO() {}
public BlackListDTO(string email, DateOnly expirationDate)
public BlackListDto()
{
}
public BlackListDto(string email, DateOnly expirationDate)
{
Email = email;
ExpirationDate = expirationDate;

@ -1,13 +1,21 @@
namespace Dto;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
public abstract class ContentLessonDTO
namespace Dto;
[DataContract]
public class ContentLessonDto
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "contentContent")]
public string ContentContent { get; set; }
[DataMember(Name = "contentTitle")]
public string ContentTitle { get; set; }
[DataMember(Name = "lessonId")]
public int LessonId { get; set; }
protected ContentLessonDTO(int id, string contentContent, string contentTitle, int lessonId)
public ContentLessonDto(int id, string contentContent, string contentTitle, int lessonId)
{
Id = id;
ContentContent = contentContent;
@ -15,14 +23,14 @@ public abstract class ContentLessonDTO
LessonId = lessonId;
}
protected ContentLessonDTO(string contentContent, string contentTitle, int lessonId)
protected ContentLessonDto(string contentContent, string contentTitle, int lessonId)
{
ContentContent = contentContent;
ContentTitle = contentTitle;
LessonId = lessonId;
}
protected ContentLessonDTO()
{
}
}
public ContentLessonDto()
{
}
}

@ -6,4 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\..\..\..\.nuget\packages\newtonsoft.json\13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

@ -1,17 +1,27 @@
namespace Dto;
using System.Runtime.Serialization;
public class InquiryDTO
namespace Dto;
[DataContract]
public class InquiryDto : IEquatable<InquiryDto>
{
public int Id { get; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public bool IsUser { get; set; }
public InquiryDTO(){}
public InquiryDTO(int id, string title, string description, bool isUser)
public InquiryDto()
{
}
public InquiryDto(int id, string title, string description, bool isUser)
{
Id = id;
Title = title;
@ -19,10 +29,45 @@ public class InquiryDTO
IsUser = isUser;
}
public InquiryDTO(string title, string description, bool isUser)
public InquiryDto(string title, string description, bool isUser)
{
Title = title;
Description = description;
IsUser = isUser;
}
public override string ToString()
{
return $"{Id}\t{Title}\t{Description}\t{IsUser}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as InquiryDto);
}
public bool Equals(InquiryDto other)
{
return (this.Id == other.Id);
}
public override int GetHashCode()
{
return Id;
}
}

@ -1,16 +1,16 @@
namespace Dto;
public class InquiryTableDTO
public class InquiryTableDto
{
public int OwnerId { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTableDTO()
public InquiryTableDto()
{
}
public InquiryTableDTO(int ownerId, string databaseName, string connectionInfo)
public InquiryTableDto(int ownerId, string databaseName, string connectionInfo)
{
OwnerId = ownerId;
DatabaseName = databaseName;

@ -1,29 +1,80 @@
namespace Dto;
using System.Net;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace Dto;
public class LessonDTO
[DataContract]
public class LessonDto : IEquatable<LessonDto>
{
public int Id { get; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string? Title { get; set; }
[DataMember]
public string? LastPublisher { get; set; }
[DataMember]
public DateOnly? LastEdit { get; set; }
public ICollection<ContentLessonDTO> Content { get; set; } = new List<ContentLessonDTO>();
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public ICollection<ContentLessonDto> Content { get; set; } = new List<ContentLessonDto>();
public LessonDTO()
public LessonDto()
{
}
public LessonDTO(int id, string title, string lastPublisher, DateOnly? lastEdit)
public LessonDto(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public LessonDTO(string title, string lastPublisher, DateOnly? lastEdit)
public LessonDto(int id, string title, string lastPublisher, DateOnly? lastEdit, ICollection<ContentLessonDto> content)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
Content = content;
}
public LessonDto(string title, string lastPublisher, DateOnly lastEdit)
{
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public override string ToString()
{
return $"{Id}\t{Title}\t{LastPublisher}\t{LastEdit}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as LessonDto);
}
public bool Equals(LessonDto other)
{
return (this.Id == other.Id);
}
public override int GetHashCode()
{
return Id;
}
}

@ -1,17 +1,17 @@
namespace Dto;
public class NotepadDTO
public class NotepadDto
{
public int Id { get; set; }
public int UserId { get; set; }
public int InquiryId { get; set; }
public string Notes { get; set; }
public NotepadDTO()
public NotepadDto()
{
}
public NotepadDTO(int id, int userId, int inquiryId, string notes)
public NotepadDto(int id, int userId, int inquiryId, string notes)
{
Id = id;
UserId = userId;
@ -19,7 +19,7 @@ public class NotepadDTO
Notes = notes;
}
public NotepadDTO(int userId, int inquiryId, string notes)
public NotepadDto(int userId, int inquiryId, string notes)
{
UserId = userId;
InquiryId = inquiryId;

@ -1,14 +1,32 @@
namespace Dto;
using System.Runtime.Serialization;
public class ParagraphDTO : ContentLessonDTO
namespace Dto;
[DataContract]
public class ParagraphDto : ContentLessonDto, IEquatable<ParagraphDto>
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "content")]
public string Content { get; set; }
[DataMember(Name = "info")]
public string Info { get; set; }
[DataMember(Name = "query")]
public string Query { get; set; }
[DataMember(Name = "comment")]
public string Comment { get; set; }
public ParagraphDTO(string title, string content, string info, string query, string comment, int lessonId) :
public ParagraphDto(string contentTitle, string contentContent, string title, string content, string info, string query, string comment, int lessonId) :
base(contentContent,
contentTitle, lessonId)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public ParagraphDto(string title, string content, string info, string query, string comment, int lessonId) :
base(content,
title, lessonId)
{
@ -19,7 +37,7 @@ public class ParagraphDTO : ContentLessonDTO
Comment = comment;
}
public ParagraphDTO(int id, string title, string content, string info, string query, string comment, int lessonId) :
public ParagraphDto(int id, string title, string content, string info, string query, string comment, int lessonId) :
base(id, content,
title, lessonId)
{
@ -31,7 +49,42 @@ public class ParagraphDTO : ContentLessonDTO
Comment = comment;
}
public ParagraphDTO() : base()
public ParagraphDto() : base()
{
}
public override string ToString()
{
return $"{Id}\t{Title}\t{Content}\t{Info}\t{Query}\t{Comment}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as ParagraphDto);
}
public bool Equals(ParagraphDto other)
{
return (this.Id == other.Id);
}
public override int GetHashCode()
{
return Id;
}
}

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dto
{
public class QueryDto
{
public string Result { get; set; }
}
}

@ -1,6 +1,6 @@
namespace Dto;
public class SolutionDTO
public class SolutionDto
{
public int OwnerId { get; set; }
public string MurdererFirstName { get; set; }
@ -9,11 +9,11 @@ public class SolutionDTO
public string MurderWeapon { get; set; }
public string Explanation { get; set; }
public SolutionDTO()
public SolutionDto()
{
}
public SolutionDTO(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
public SolutionDto(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explanation)
{
OwnerId = ownerId;
@ -24,7 +24,7 @@ public class SolutionDTO
Explanation = explanation;
}
public SolutionDTO(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
public SolutionDto(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
string explanation)
{
MurdererFirstName = murdererFirstName;

@ -1,19 +1,54 @@
namespace Dto;
public class SuccessDTO
public class SuccessDto : IEquatable<SuccessDto>
{
public int UserId { get; set; }
public int InquiryId { get; set; }
public bool IsFinished { get; set; }
public SuccessDTO()
public SuccessDto()
{
}
public SuccessDTO(int userId, int inquiryId, bool isFinished)
public SuccessDto(int userId, int inquiryId, bool isFinished)
{
UserId = userId;
InquiryId = inquiryId;
IsFinished = isFinished;
}
public override string ToString()
{
return $"User :{UserId}\t Enquête : {InquiryId}\t{IsFinished}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as SuccessDto);
}
public bool Equals(SuccessDto other)
{
return (this.UserId == other.UserId && this.InquiryId == other.InquiryId);
}
public override int GetHashCode()
{
return UserId * InquiryId;
}
}

@ -1,36 +1,67 @@
namespace Dto;
public class UserDTO
namespace Dto
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserDTO()
public class UserDto : IEquatable<UserDto>
{
}
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserDTO(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public UserDto()
{
}
public UserDTO(string username, string password, string email, bool isAdmin)
{
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public UserDto(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public override string ToString()
{
return $"{Id}\t{Username}\t{Email}\t{IsAdmin}";
public UserDto(string username, string password, string email, bool isAdmin)
{
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public override string ToString()
{
return $"{Id}\t{Username}\t{Email}\t{IsAdmin}";
}
public bool Equals(UserDto? other)
{
return (this.Id == other?.Id);
}
public override bool Equals(object? obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as UserDto);
}
public override int GetHashCode()
{
return Id;
}
}
}

@ -8,14 +8,4 @@ public class BlackListEntity
{
[Key] public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
public BlackListEntity()
{
}
public BlackListEntity(string email, DateOnly expirationDate)
{
Email = email;
ExpirationDate = expirationDate;
}
}

@ -7,32 +7,6 @@ public abstract class ContentLessonEntity
public int Id { get; set; }
public string ContentContent { get; set; }
public string ContentTitle { get; set; }
[ForeignKey(nameof(Lesson))] public virtual int LessonId { get; set; }
public virtual LessonEntity Lesson { get; set; } = null!;
protected ContentLessonEntity()
{
}
protected ContentLessonEntity(int id, string contentContent, string contentTitle)
{
Id = id;
ContentContent = contentContent;
ContentTitle = contentTitle;
}
protected ContentLessonEntity(int id, int lessonId, string contentContent, string contentTitle)
{
Id = id;
LessonId = lessonId;
ContentContent = contentContent;
ContentTitle = contentTitle;
}
protected ContentLessonEntity(string contentContent, string contentTitle)
{
ContentContent = contentContent;
ContentTitle = contentTitle;
}
[ForeignKey(nameof(Lesson))] public int LessonId { get; set; }
public LessonEntity Lesson { get; set; } = null!;
}

@ -5,33 +5,8 @@ namespace Entities;
public class InquiryEntity
{
[Key] public int Id { get; }
[Key] public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsUser { get; set; }
public InquiryEntity()
{
}
public InquiryEntity(int id)
{
Id = id;
}
public InquiryEntity(string title, string description, bool isUser)
{
Id = 0;
Title = title;
Description = description;
IsUser = isUser;
}
public InquiryEntity(int id, string title, string description, bool isUser)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
}
}

@ -15,27 +15,4 @@ public class InquiryTableEntity
public InquiryEntity Owner { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTableEntity()
{
}
public InquiryTableEntity(int inquiryId)
{
OwnerId = inquiryId;
}
public InquiryTableEntity(int inquiryId, string databaseName, string connectionInfo)
{
OwnerId = inquiryId;
DatabaseName = databaseName;
ConnectionInfo = connectionInfo;
}
public InquiryTableEntity(InquiryEntity owner, string databaseName, string connectionInfo)
{
Owner = owner;
DatabaseName = databaseName;
ConnectionInfo = connectionInfo;
}
}

@ -6,27 +6,8 @@ namespace Entities;
public class LessonEntity
{
public int Id { get; set; }
public string? Title { get; set; }
public string? LastPublisher { get; set; }
public DateOnly? LastEdit { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public ICollection<ContentLessonEntity> Content { get; set; } = new List<ContentLessonEntity>();
public LessonEntity()
{
}
public LessonEntity(int id, string title, string lastPublisher, DateOnly? lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public LessonEntity(string title, string lastPublisher, DateOnly? lastEdit)
{
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
}

@ -13,27 +13,4 @@ public class NotepadEntity
[ForeignKey(nameof(Inquiry))] public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public string Notes { get; set; }
public NotepadEntity()
{
}
public NotepadEntity(int id, int userId, UserEntity user, int inquiryId, InquiryEntity inquiry, string notes)
{
Id = id;
UserId = userId;
User = user;
InquiryId = inquiryId;
Inquiry = inquiry;
Notes = notes;
}
public NotepadEntity(int userId, UserEntity user, int inquiryId, InquiryEntity inquiry, string notes)
{
UserId = userId;
User = user;
InquiryId = inquiryId;
Inquiry = inquiry;
Notes = notes;
}
}

@ -14,28 +14,4 @@ public class ParagraphEntity : ContentLessonEntity
public string Info { get; set; }
public string Query { get; set; }
public string Comment { get; set; }
public ParagraphEntity()
{
}
public ParagraphEntity(int id, string title, string content, string info, string query,
string comment, int idLesson) : base(id, idLesson, content, title)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public ParagraphEntity(string title, string content, string info, string query, string comment) : base(content,
title)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
}

@ -13,52 +13,9 @@ public class SolutionEntity
public int OwnerId { get; set; }
public InquiryEntity? Owner { get; set; }
public string? MurdererFirstName { get; set; }
public string? MurdererLastName { get; set; }
public string? MurderPlace { get; set; }
public string? MurderWeapon { get; set; }
public string? Explaination { get; set; }
public SolutionEntity()
{
}
public SolutionEntity(int ownerId)
{
OwnerId = ownerId;
}
public SolutionEntity(int ownerId, InquiryEntity? owner, string murdererFirstName, string murdererLastName,
string murderPlace, string murderWeapon, string explaination)
{
OwnerId = ownerId;
Owner = owner;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explaination;
}
public SolutionEntity(InquiryEntity? owner, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explaination)
{
Owner = owner;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explaination;
}
public SolutionEntity(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explanation)
{
OwnerId = ownerId;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explanation;
}
public string MurdererFirstName { get; set; }
public string MurdererLastName { get; set; }
public string MurderPlace { get; set; }
public string MurderWeapon { get; set; }
public string Explaination { get; set; }
}

@ -11,31 +11,4 @@ public class SuccessEntity
[ForeignKey(nameof(Inquiry))] public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public bool IsFinished { get; set; }
public SuccessEntity()
{
}
public SuccessEntity(int userId, UserEntity user, int inquiryId, InquiryEntity inquiry, bool isFinished)
{
UserId = userId;
User = user;
InquiryId = inquiryId;
Inquiry = inquiry;
IsFinished = isFinished;
}
public SuccessEntity(int userId, int inquiryId, bool isFinished)
{
UserId = userId;
InquiryId = inquiryId;
IsFinished = isFinished;
}
public SuccessEntity(UserEntity user, InquiryEntity inquiry, bool isFinished)
{
User = user;
Inquiry = inquiry;
IsFinished = isFinished;
}
}

@ -1,8 +1,11 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Entities;
[Table("User")]
[Index(nameof(Username), IsUnique = true)]
[Index(nameof(Email), IsUnique = true)]
public class UserEntity
{
public int Id { get; set; }
@ -10,30 +13,4 @@ public class UserEntity
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserEntity()
{
}
public UserEntity(int id)
{
Id = id;
}
public UserEntity(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public UserEntity(string username, string password, string email, bool isAdmin)
{
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
}

@ -3,12 +3,12 @@
public class Lesson
{
public int Id { get; }
public string? Title { get; set; }
public string? LastPublisher { get; set; }
public DateOnly? LastEdit { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public ICollection<ContentLesson> Content { get; set; } = new List<ContentLesson>();
public Lesson(int id, string title, string lastPublisher, DateOnly? lastEdit)
public Lesson(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Title = title;
@ -16,7 +16,7 @@ public class Lesson
LastEdit = lastEdit;
}
public Lesson(string title, string lastPublisher, DateOnly? lastEdit)
public Lesson(string title, string lastPublisher, DateOnly lastEdit)
{
Title = title;
LastPublisher = lastPublisher;

@ -0,0 +1,6 @@
namespace Model.OrderCriteria;
public enum BlackListOdrerCriteria
{
None, ByEmail, ByExpirationDate
}

@ -5,5 +5,6 @@ public enum InquiryOrderCriteria
None,
ByTitle,
ByDescription,
ByIsUser
ByIsUser,
ById
}

@ -5,5 +5,6 @@ public enum LessonOrderCriteria
None,
ByTitle,
ByLastPublisher,
ByLastEdit
ByLastEdit,
ById
}

@ -7,30 +7,30 @@ public class Solution
public string MurdererLastName { get; set; }
public string MurderPlace { get; set; }
public string MurderWeapon { get; set; }
public string Explanation { get; set; }
public string Explaination { get; set; }
public Solution()
{
}
public Solution(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explanation)
string murderWeapon, string explaination)
{
OwnerId = ownerId;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explanation = explanation;
Explaination = explaination;
}
public Solution(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
string explanation)
string explaination)
{
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explanation = explanation;
Explaination = explaination;
}
}

@ -0,0 +1,12 @@
using Model.OrderCriteria;
namespace Shared;
public interface IBlackListService<TBlackList>
{
public IEnumerable<TBlackList> GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria);
public int GetNumberOfBannedUsers();
public TBlackList? GetUserBannedByEmail(string email);
public bool BanUser(string username);
public bool UnbanUser(string email);
}

@ -5,6 +5,7 @@ namespace Shared;
public interface IInquiryService<TInquiry>
{
public IEnumerable<TInquiry> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria);
public int GetNumberOfInquiries();
public TInquiry GetInquiryById(int id);
public TInquiry GetInquiryByTitle(string title);
public bool DeleteInquiry(int id);

@ -0,0 +1,6 @@
namespace Shared;
public interface IInquiryTableService<TInquiryTable>
{
public string GetDatabaseNameByInquiryId(int id);
}

@ -5,9 +5,10 @@ namespace Shared;
public interface ILessonService<TLesson>
{
public IEnumerable<TLesson> GetLessons(int page, int number, LessonOrderCriteria orderCriteria);
public int GetNumberOfLessons();
public TLesson GetLessonById(int id);
public TLesson GetLessonByTitle(string title);
public bool DeleteLesson(int id);
public TLesson UpdateLesson(int id, TLesson lesson);
public TLesson CreateLesson(string title, string lastPublisher, DateOnly? lastEdit);
public TLesson CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit);
}

@ -0,0 +1,10 @@
namespace Shared;
public interface INotepadService<TNotepad>
{
public TNotepad GetNotepadFromUserAndInquiryId(int userId, int inquiryId);
public void SetNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes);
public void UpdateNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes);
}

@ -5,12 +5,13 @@ namespace Shared
public interface IParagraphService<TParagraph>
{
public IEnumerable<TParagraph> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria);
public IEnumerable<TParagraph> GetParagraphsByLessonId(int lessonId);
public TParagraph GetParagraphById(int id);
public TParagraph GetParagraphByTitle(string title);
public bool DeleteParagraph(int id);
public TParagraph UpdateParagraph(int id, TParagraph paragraph);
public TParagraph CreateParagraph(string title, string content, string info, string query, string comment,
public TParagraph CreateParagraph(string contentTitle, string contentContent, string title, string content, string info, string query, string comment,
int lessonId);
}
}

@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc;
using Model.OrderCriteria;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dto;
namespace Shared
{
public interface IQueryService<TQuery>
{
public TQuery ExecuteQuery(string query, string database);
public QueryDto GetTables(string database);
public QueryDto GetColumns(string database,string table);
}
}

@ -0,0 +1,6 @@
namespace Shared;
public interface ISolutionService<TSolution>
{
public TSolution GetSolutionByInquiryId(int id);
}

@ -5,10 +5,10 @@ namespace Shared
public interface ISuccessService<TSuccess>
{
public IEnumerable<TSuccess> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria);
public TSuccess GetSuccessByUserId(int id);
public TSuccess GetSuccessByInquiryId(int id);
public bool DeleteSuccess(int id);
public TSuccess UpdateSuccess(int id, TSuccess success);
public IEnumerable<TSuccess> GetSuccessesByUserId(int id);
public IEnumerable<TSuccess> GetSuccessesByInquiryId(int id);
public bool DeleteSuccess(int idUser, int idInquiry);
public TSuccess UpdateSuccess(int idUser, int idInquiry, TSuccess success);
public TSuccess CreateSuccess(int userId, int inquiryId, bool isFinished);
}
}

@ -5,10 +5,17 @@ namespace Shared
public interface IUserService<TUser>
{
public IEnumerable<TUser> GetUsers(int page, int number, UserOrderCriteria orderCriteria);
public IEnumerable<TUser> GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria);
public int GetNumberOfUsers();
public TUser GetUserById(int id);
public TUser GetUserByUsername(string username);
public TUser GetUserByEmail(string email);
public bool DeleteUser(int id);
public bool DeleteUserByUsername(string username);
public TUser UpdateUser(int id, TUser user);
public TUser CreateUser(string username, string password, string email, bool isAdmin);
public bool IsEmailTaken(string email);
public bool IsUsernameTaken(string username);
public TUser PromoteUser(int id);
}
}

@ -6,17 +6,17 @@ namespace Shared.Mapper;
public static class BlackListMapper
{
public static BlackListDTO FromModelToDTO(this BlackList model)
public static BlackListDto FromModelToDto(this BlackList model)
{
return new BlackListDTO(model.Email, model.ExpirationDate);
return new BlackListDto(model.Email, model.ExpirationDate);
}
public static BlackListDTO FromEntityToDTO(this BlackListEntity ent)
public static BlackListDto FromEntityToDto(this BlackListEntity ent)
{
return new BlackListDTO(ent.Email, ent.ExpirationDate);
return new BlackListDto(ent.Email, ent.ExpirationDate);
}
public static BlackList FromDTOToModel(this BlackListDTO dto)
public static BlackList FromDtoToModel(this BlackListDto dto)
{
return new BlackList(dto.Email, dto.ExpirationDate);
}
@ -26,13 +26,21 @@ public static class BlackListMapper
return new BlackList(ent.Email, ent.ExpirationDate);
}
public static BlackListEntity FromDTOToEntity(this BlackListDTO dto)
public static BlackListEntity FromDtoToEntity(this BlackListDto dto)
{
return new BlackListEntity(dto.Email, dto.ExpirationDate);
return new BlackListEntity
{
Email = dto.Email,
ExpirationDate = dto.ExpirationDate
};
}
public static BlackListEntity FromModelToEntity(this BlackList model)
{
return new BlackListEntity(model.Email, model.ExpirationDate);
return new BlackListEntity
{
Email = model.Email,
ExpirationDate = model.ExpirationDate
};
}
}

@ -0,0 +1,13 @@
using Dto;
using Entities;
using Model;
namespace Shared.Mapper;
public static class ContentLessonMapper
{
public static ContentLessonDto FromEntityToDto(this ContentLessonEntity entity)
{
return new ContentLessonDto(entity.Id, entity.ContentContent, entity.ContentTitle, entity.LessonId);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class InquiryMapper
{
public static Inquiry FromDTOToModel(this InquiryDTO inqDto)
public static Inquiry FromDtoToModel(this InquiryDto inqDto)
{
return new Inquiry(inqDto.Id, inqDto.Title, inqDto.Description, inqDto.IsUser);
}
@ -19,21 +19,33 @@ public static class InquiryMapper
public static InquiryEntity FromModelToEntity(this Inquiry inq)
{
return new InquiryEntity(inq.Id, inq.Title, inq.Description, inq.IsUser);
return new InquiryEntity
{
Id = inq.Id,
Title = inq.Title,
Description = inq.Description,
IsUser = inq.IsUser
};
}
public static InquiryEntity FromDTOToEntity(this InquiryDTO inqDto)
public static InquiryEntity FromDtoToEntity(this InquiryDto inqDto)
{
return new InquiryEntity(inqDto.Id, inqDto.Title, inqDto.Description, inqDto.IsUser);
return new InquiryEntity
{
Id = inqDto.Id,
Title = inqDto.Title,
Description = inqDto.Description,
IsUser = inqDto.IsUser
};
}
public static InquiryDTO FromModelToDTO(this Inquiry inq)
public static InquiryDto FromModelToDto(this Inquiry inq)
{
return new InquiryDTO(inq.Id, inq.Title, inq.Description, inq.IsUser);
return new InquiryDto(inq.Id, inq.Title, inq.Description, inq.IsUser);
}
public static InquiryDTO FromEntityToDTO(this InquiryEntity inqEntity)
public static InquiryDto FromEntityToDto(this InquiryEntity inqEntity)
{
return new InquiryDTO(inqEntity.Id, inqEntity.Title, inqEntity.Description, inqEntity.IsUser);
return new InquiryDto(inqEntity.Id, inqEntity.Title, inqEntity.Description, inqEntity.IsUser);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class InquiryTableMapper
{
public static InquiryTable FromDTOToModel(this InquiryTableDTO inqTDto)
public static InquiryTable FromDtoToModel(this InquiryTableDto inqTDto)
{
return new InquiryTable(inqTDto.OwnerId, inqTDto.ConnectionInfo, inqTDto.DatabaseName);
}
@ -16,23 +16,33 @@ public static class InquiryTableMapper
return new InquiryTable(inqTEntity.OwnerId, inqTEntity.ConnectionInfo, inqTEntity.DatabaseName);
}
public static InquiryTableDTO FromModelToDTO(this InquiryTable inqT)
public static InquiryTableDto FromModelToDto(this InquiryTable inqT)
{
return new InquiryTableDTO(inqT.OwnerId, inqT.DatabaseName, inqT.ConnectionInfo);
return new InquiryTableDto(inqT.OwnerId, inqT.DatabaseName, inqT.ConnectionInfo);
}
public static InquiryTableDTO FromEntityToDTO(this InquiryTableEntity inqTEntity)
public static InquiryTableDto FromEntityToDto(this InquiryTableEntity inqTEntity)
{
return new InquiryTableDTO(inqTEntity.OwnerId, inqTEntity.DatabaseName, inqTEntity.ConnectionInfo);
return new InquiryTableDto(inqTEntity.OwnerId, inqTEntity.DatabaseName, inqTEntity.ConnectionInfo);
}
public static InquiryTableEntity FromModelToEntity(this InquiryTable inqT)
{
return new InquiryTableEntity(inqT.OwnerId, inqT.DatabaseName, inqT.ConnectionInfo);
return new InquiryTableEntity
{
OwnerId = inqT.OwnerId,
DatabaseName = inqT.DatabaseName,
ConnectionInfo = inqT.ConnectionInfo
};
}
public static InquiryTableEntity FromDTOToEntity(this InquiryTableDTO dto)
public static InquiryTableEntity FromDtoToEntity(this InquiryTableDto dto)
{
return new InquiryTableEntity(dto.OwnerId, dto.DatabaseName, dto.ConnectionInfo);
return new InquiryTableEntity
{
OwnerId = dto.OwnerId,
DatabaseName = dto.DatabaseName,
ConnectionInfo = dto.ConnectionInfo
};
}
}

@ -6,29 +6,43 @@ namespace Shared.Mapper;
public static class LessonMapper
{
public static LessonDTO FromModelToDTO(this Lesson model)
public static LessonDto FromModelToDto(this Lesson model)
{
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit);
return new LessonDto(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonDTO FromEntityToDTO(this LessonEntity model)
public static LessonDto FromEntityToDto(this LessonEntity model)
{
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit);
return new LessonDto(model.Id, model.Title, model.LastPublisher, model.LastEdit, model.Content.Select(c => c.FromEntityToDto()).ToList());
}
public static LessonEntity FromModelToEntity(this Lesson model)
{
return new LessonEntity(model.Id, model.Title, model.LastPublisher, model.LastEdit);
return new LessonEntity
{
Id = model.Id,
Title = model.Title,
LastPublisher = model.LastPublisher,
LastEdit = model.LastEdit
};
}
public static LessonEntity FromDTOToEntity(this LessonDTO dto)
public static LessonEntity FromDtoToEntity(this LessonDto dto)
{
return new LessonEntity(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
DateTime date = DateTime.Now;
return new LessonEntity
{
Id = dto.Id,
Title = dto.Title,
LastPublisher = dto.LastPublisher,
LastEdit = dto.LastEdit ?? new DateOnly(date.Year,date.Month,date.Day)
};
}
public static Lesson FromDTOToModel(this LessonDTO dto)
public static Lesson FromDtoToModel(this LessonDto dto)
{
return new Lesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
DateTime date = DateTime.Now;
return new Lesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit ?? new DateOnly(date.Year,date.Month,date.Day));
}
public static Lesson FromEntityToModel(this LessonEntity entity)

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class NotepadMapper
{
public static Notepad FromDTOToModel(this NotepadDTO dto)
public static Notepad FromDtoToModel(this NotepadDto dto)
{
return new Notepad(dto.Id, dto.UserId, dto.InquiryId, dto.Notes);
}
@ -16,25 +16,49 @@ public static class NotepadMapper
return new Notepad(ent.Id, ent.UserId, ent.InquiryId, ent.Notes);
}
public static NotepadDTO FromModelToDTO(this Notepad not)
public static NotepadDto FromModelToDto(this Notepad not)
{
return new NotepadDTO(not.Id, not.UserId, not.InquiryId, not.Notes);
return new NotepadDto(not.Id, not.UserId, not.InquiryId, not.Notes);
}
public static NotepadDTO FromEntityToDTO(this NotepadEntity ent)
public static NotepadDto FromEntityToDto(this NotepadEntity ent)
{
return new NotepadDTO(ent.Id, ent.UserId, ent.InquiryId, ent.Notes);
return new NotepadDto(ent.Id, ent.UserId, ent.InquiryId, ent.Notes);
}
public static NotepadEntity FromDTOToEntity(this NotepadDTO dto)
public static NotepadEntity FromDtoToEntity(this NotepadDto dto)
{
return new NotepadEntity(dto.Id, new UserEntity(dto.UserId), dto.UserId, new InquiryEntity(dto.InquiryId),
dto.Notes);
return new NotepadEntity
{
Id = dto.Id,
User = new UserEntity
{
Id = dto.UserId
},
UserId = dto.UserId,
Inquiry = new InquiryEntity
{
Id = dto.InquiryId
},
Notes = dto.Notes
};
}
public static NotepadEntity FromModelToEntity(this Notepad not)
{
return new NotepadEntity(not.Id, new UserEntity(not.UserId), not.UserId, new InquiryEntity(not.InquiryId),
not.Notes);
return new NotepadEntity
{
Id = not.Id,
User = new UserEntity
{
Id = not.UserId
},
UserId = not.UserId,
Inquiry = new InquiryEntity
{
Id = not.InquiryId
},
Notes = not.Notes
};
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class ParagraphMapper
{
public static Paragraph FromDTOToModel(this ParagraphDTO dto)
public static Paragraph FromDtoToModel(this ParagraphDto dto)
{
return new Paragraph(dto.ContentTitle, dto.ContentContent, dto.Info, dto.Query, dto.Comment);
}
@ -16,27 +16,44 @@ public static class ParagraphMapper
return new Paragraph(model.ContentTitle, model.ContentContent, model.Info, model.Query, model.Comment);
}
public static ParagraphDTO FromEntityToDTO(this ParagraphEntity model)
public static ParagraphDto FromEntityToDto(this ParagraphEntity model)
{
return new ParagraphDTO(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
return new ParagraphDto(model.Id, model.Title, model.Content, model.Info, model.Query,
model.Comment, model.LessonId);
}
public static ParagraphDTO FromModelToDTO(this Paragraph model)
public static ParagraphDto FromModelToDto(this Paragraph model)
{
return new ParagraphDTO(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
return new ParagraphDto(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
model.Comment, model.LessonId);
}
public static ParagraphEntity FromDTOToEntity(this ParagraphDTO dto)
public static ParagraphEntity FromDtoToEntity(this ParagraphDto dto)
{
return new ParagraphEntity(dto.Id, dto.ContentTitle, dto.ContentContent, dto.Info, dto.Query, dto.Comment,
dto.LessonId);
return new ParagraphEntity
{
Id = dto.Id,
ContentTitle = dto.ContentTitle,
ContentContent = dto.ContentContent,
Title = dto.Title,
Content = dto.Content,
Info = dto.Info,
Query = dto.Query,
Comment = dto.Comment,
LessonId = dto.LessonId
};
}
public static ParagraphEntity FromModelToEntity(this Paragraph model)
{
return new ParagraphEntity(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
model.Comment, model.LessonId);
return new ParagraphEntity
{
Id = model.Id,
ContentTitle = model.ContentTitle,
ContentContent = model.ContentContent,
Info = model.Info,
Query = model.Query,
Comment = model.Comment, LessonId = model.LessonId
};
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class SolutionMapper
{
public static Solution FromDTOToModel(this SolutionDTO dto)
public static Solution FromDtoToModel(this SolutionDto dto)
{
return new Solution(dto.OwnerId, dto.MurdererFirstName, dto.MurdererLastName, dto.MurderPlace, dto.MurderWeapon,
dto.Explanation);
@ -18,27 +18,49 @@ public static class SolutionMapper
entity.MurderWeapon, entity.Explaination);
}
public static SolutionDTO FromModelToDTO(this Solution model)
public static SolutionDto FromModelToDto(this Solution model)
{
return new SolutionDTO(model.OwnerId, model.MurdererFirstName, model.MurdererLastName, model.MurderPlace,
model.MurderWeapon, model.Explanation);
return new SolutionDto(model.OwnerId, model.MurdererFirstName, model.MurdererLastName, model.MurderPlace,
model.MurderWeapon, model.Explaination);
}
public static SolutionDTO FromEntityToDTO(this SolutionEntity entity)
public static SolutionDto FromEntityToDto(this SolutionEntity entity)
{
return new SolutionDTO(entity.OwnerId, entity.MurdererFirstName, entity.MurdererLastName, entity.MurderPlace,
return new SolutionDto(entity.OwnerId, entity.MurdererFirstName, entity.MurdererLastName, entity.MurderPlace,
entity.MurderWeapon, entity.Explaination);
}
public static SolutionEntity FromModelToEntity(this Solution model)
{
return new SolutionEntity(model.OwnerId, new InquiryEntity(model.OwnerId), model.MurdererFirstName,
model.MurdererLastName, model.MurderPlace, model.MurderWeapon, model.Explanation);
return new SolutionEntity
{
OwnerId = model.OwnerId,
Owner = new InquiryEntity
{
Id = model.OwnerId
},
MurdererFirstName = model.MurdererFirstName,
MurdererLastName = model.MurdererLastName,
MurderPlace = model.MurderPlace,
MurderWeapon = model.MurderWeapon,
Explaination = model.Explaination
};
}
public static SolutionEntity FromDTOToEntity(this SolutionDTO dto)
public static SolutionEntity FromDtoToEntity(this SolutionDto dto)
{
return new SolutionEntity(dto.OwnerId, new InquiryEntity(dto.OwnerId), dto.MurdererFirstName,
dto.MurdererLastName, dto.MurderPlace, dto.MurderWeapon, dto.Explanation);
return new SolutionEntity
{
OwnerId = dto.OwnerId,
Owner = new InquiryEntity
{
Id = dto.OwnerId
},
MurdererFirstName = dto.MurdererFirstName,
MurdererLastName = dto.MurdererLastName,
MurderPlace = dto.MurderPlace,
MurderWeapon = dto.MurderWeapon,
Explaination = dto.Explanation
};
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class SuccessMapper
{
public static Success FromDTOToModel(this SuccessDTO dto)
public static Success FromDtoToModel(this SuccessDto dto)
{
return new Success(dto.UserId, dto.InquiryId, dto.IsFinished);
}
@ -16,25 +16,49 @@ public static class SuccessMapper
return new Success(ent.UserId, ent.InquiryId, ent.IsFinished);
}
public static SuccessDTO FromModelToDTO(this Success suc)
public static SuccessDto FromModelToDto(this Success suc)
{
return new SuccessDTO(suc.UserId, suc.InquiryId, suc.IsFinished);
return new SuccessDto(suc.UserId, suc.InquiryId, suc.IsFinished);
}
public static SuccessDTO FromEntityToDTO(this SuccessEntity ent)
public static SuccessDto FromEntityToDto(this SuccessEntity ent)
{
return new SuccessDTO(ent.UserId, ent.InquiryId, ent.IsFinished);
return new SuccessDto(ent.UserId, ent.InquiryId, ent.IsFinished);
}
public static SuccessEntity FromDTOToEntity(this SuccessDTO dto)
public static SuccessEntity FromDtoToEntity(this SuccessDto dto)
{
return new SuccessEntity(dto.UserId, new UserEntity(dto.UserId), dto.InquiryId,
new InquiryEntity(dto.InquiryId), dto.IsFinished);
return new SuccessEntity
{
UserId = dto.UserId,
User = new UserEntity
{
Id = dto.UserId
},
InquiryId = dto.InquiryId,
Inquiry = new InquiryEntity
{
Id = dto.InquiryId
},
IsFinished = dto.IsFinished
};
}
public static SuccessEntity FromModelToEntity(this Success suc)
{
return new SuccessEntity(suc.UserId, new UserEntity(suc.UserId), suc.InquiryId,
new InquiryEntity(suc.InquiryId), suc.IsFinished);
return new SuccessEntity
{
UserId = suc.UserId,
User = new UserEntity
{
Id = suc.UserId
},
InquiryId = suc.InquiryId,
Inquiry = new InquiryEntity
{
Id = suc.InquiryId
},
IsFinished = suc.IsFinished
};
}
}

@ -6,14 +6,21 @@ namespace Shared.Mapper;
public static class UserMapper
{
public static User FromDTOToModel(this UserDTO dto)
public static User FromDtoToModel(this UserDto dto)
{
return new User(dto.Id, dto.Username, dto.Password, dto.Email, dto.IsAdmin);
}
public static UserEntity FromDTOToEntity(this UserDTO dto)
public static UserEntity FromDtoToEntity(this UserDto dto)
{
return new UserEntity(dto.Id, dto.Username, dto.Password, dto.Email, dto.IsAdmin);
return new UserEntity
{
Id = dto.Id,
Username = dto.Username,
Password = dto.Password,
Email = dto.Email,
IsAdmin = dto.IsAdmin
};
}
public static User FromEntityToModel(this UserEntity entity)
@ -21,18 +28,25 @@ public static class UserMapper
return new User(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
}
public static UserDTO FromEntityToDTO(this UserEntity entity)
public static UserDto FromEntityToDto(this UserEntity entity)
{
return new UserDTO(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
return new UserDto(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
}
public static UserDTO FromModelToDTO(this User user)
public static UserDto FromModelToDto(this User user)
{
return new UserDTO(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
return new UserDto(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
}
public static UserEntity FromModelToEntity(this User user)
{
return new UserEntity(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
return new UserEntity
{
Id = user.Id,
Username = user.Username,
Password = user.Password,
Email = user.Email,
IsAdmin = user.IsAdmin
};
}
}

@ -0,0 +1,643 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using StubbedContextLib;
#nullable disable
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubbedContext))]
[Migration("20240624134431_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.HasSequence("ContentLessonEntitySequence");
modelBuilder.Entity("Entities.BlackListEntity", b =>
{
b.Property<string>("Email")
.HasColumnType("text");
b.Property<DateOnly>("ExpirationDate")
.HasColumnType("date");
b.HasKey("Email");
b.ToTable("BlackList");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValueSql("nextval('\"ContentLessonEntitySequence\"')");
NpgsqlPropertyBuilderExtensions.UseSequence(b.Property<int>("Id"));
b.Property<string>("ContentContent")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentTitle")
.IsRequired()
.HasColumnType("text");
b.Property<int>("LessonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("LessonId");
b.ToTable((string)null);
b.UseTpcMappingStrategy();
});
modelBuilder.Entity("Entities.InquiryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsUser")
.HasColumnType("boolean");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Inquiries");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("ConnectionInfo")
.IsRequired()
.HasColumnType("text");
b.Property<string>("DatabaseName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("InquiryTable");
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateOnly>("LastEdit")
.HasColumnType("date");
b.Property<string>("LastPublisher")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Lesson");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("InquiryId");
b.HasIndex("UserId");
b.ToTable("Notepad");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("Explaination")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderPlace")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderWeapon")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererFirstName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererLastName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("Solution");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<bool>("IsFinished")
.HasColumnType("boolean");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("InquiryId");
b.HasIndex("UserId");
b.ToTable("Success");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("User");
b.HasData(
new
{
Id = 1,
Email = "Johnny.RATTON@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$7Dq.5Bf5WlHBMRqHBp5Ag.5PCCnvLrBXsuMGGJnV4l4WdngeDBpnW",
Username = "johnny"
},
new
{
Id = 2,
Email = "Maxime.SAPOUNTZIS@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$OT8g325JcE9mIdc.DiEKpem3kwNBdRcQ22vT2i5IB7KmfBfek4662",
Username = "maxime"
},
new
{
Id = 3,
Email = "Clement.CHIEU@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$Qc40bG8aCDvRSVjlWIn.1Orkd52fVMxBM2uQypVVwgu/mkeM8rnVK",
Username = "clement"
},
new
{
Id = 4,
Email = "Erwan.MENAGER@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$AW23BQcrS7d//LK0CtHuH.599OfYinEKCLkTz8Sbrtn.XYWE0u0BO",
Username = "erwan"
},
new
{
Id = 5,
Email = "Victor.GABORIT@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$ZOly/r95doGABtnypi8CAun1VnMRP1ct.idsUpXGe3pwjRYqv3ZQy",
Username = "victor"
});
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Entities.ParagraphEntity", b =>
{
b.HasBaseType("Entities.ContentLessonEntity");
b.Property<string>("Comment")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Query")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.ToTable("Paragraph");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.HasOne("Entities.LessonEntity", "Lesson")
.WithMany("Content")
.HasForeignKey("LessonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Lesson");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Navigation("Content");
});
#pragma warning restore 612, 618
}
}
}

@ -0,0 +1,478 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateSequence(
name: "ContentLessonEntitySequence");
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
PasswordHash = table.Column<string>(type: "text", nullable: true),
SecurityStamp = table.Column<string>(type: "text", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
PhoneNumber = table.Column<string>(type: "text", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "BlackList",
columns: table => new
{
Email = table.Column<string>(type: "text", nullable: false),
ExpirationDate = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BlackList", x => x.Email);
});
migrationBuilder.CreateTable(
name: "Inquiries",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
IsUser = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Inquiries", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Lesson",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
LastPublisher = table.Column<string>(type: "text", nullable: false),
LastEdit = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Lesson", x => x.Id);
});
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Username = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
IsAdmin = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RoleId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "text", nullable: false),
ProviderKey = table.Column<string>(type: "text", nullable: false),
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
UserId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
LoginProvider = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "InquiryTable",
columns: table => new
{
OwnerId = table.Column<int>(type: "integer", nullable: false),
DatabaseName = table.Column<string>(type: "text", nullable: false),
ConnectionInfo = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_InquiryTable", x => x.OwnerId);
table.ForeignKey(
name: "FK_InquiryTable_Inquiries_OwnerId",
column: x => x.OwnerId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Solution",
columns: table => new
{
OwnerId = table.Column<int>(type: "integer", nullable: false),
MurdererFirstName = table.Column<string>(type: "text", nullable: false),
MurdererLastName = table.Column<string>(type: "text", nullable: false),
MurderPlace = table.Column<string>(type: "text", nullable: false),
MurderWeapon = table.Column<string>(type: "text", nullable: false),
Explaination = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Solution", x => x.OwnerId);
table.ForeignKey(
name: "FK_Solution_Inquiries_OwnerId",
column: x => x.OwnerId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Paragraph",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false, defaultValueSql: "nextval('\"ContentLessonEntitySequence\"')"),
ContentContent = table.Column<string>(type: "text", nullable: false),
ContentTitle = table.Column<string>(type: "text", nullable: false),
LessonId = table.Column<int>(type: "integer", nullable: false),
Title = table.Column<string>(type: "text", nullable: false),
Content = table.Column<string>(type: "text", nullable: false),
Info = table.Column<string>(type: "text", nullable: false),
Query = table.Column<string>(type: "text", nullable: false),
Comment = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Paragraph", x => x.Id);
table.ForeignKey(
name: "FK_Paragraph_Lesson_LessonId",
column: x => x.LessonId,
principalTable: "Lesson",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Notepad",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
InquiryId = table.Column<int>(type: "integer", nullable: false),
Notes = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Notepad", x => x.Id);
table.ForeignKey(
name: "FK_Notepad_Inquiries_InquiryId",
column: x => x.InquiryId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Notepad_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Success",
columns: table => new
{
InquiryId = table.Column<int>(type: "integer", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: false),
IsFinished = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Success", x => x.InquiryId);
table.ForeignKey(
name: "FK_Success_Inquiries_InquiryId",
column: x => x.InquiryId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Success_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Email", "IsAdmin", "Password", "Username" },
values: new object[,]
{
{ 1, "Johnny.RATTON@etu.uca.fr", true, "$2a$10$7Dq.5Bf5WlHBMRqHBp5Ag.5PCCnvLrBXsuMGGJnV4l4WdngeDBpnW", "johnny" },
{ 2, "Maxime.SAPOUNTZIS@etu.uca.fr", true, "$2a$10$OT8g325JcE9mIdc.DiEKpem3kwNBdRcQ22vT2i5IB7KmfBfek4662", "maxime" },
{ 3, "Clement.CHIEU@etu.uca.fr", true, "$2a$10$Qc40bG8aCDvRSVjlWIn.1Orkd52fVMxBM2uQypVVwgu/mkeM8rnVK", "clement" },
{ 4, "Erwan.MENAGER@etu.uca.fr", true, "$2a$10$AW23BQcrS7d//LK0CtHuH.599OfYinEKCLkTz8Sbrtn.XYWE0u0BO", "erwan" },
{ 5, "Victor.GABORIT@etu.uca.fr", true, "$2a$10$ZOly/r95doGABtnypi8CAun1VnMRP1ct.idsUpXGe3pwjRYqv3ZQy", "victor" }
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Notepad_InquiryId",
table: "Notepad",
column: "InquiryId");
migrationBuilder.CreateIndex(
name: "IX_Notepad_UserId",
table: "Notepad",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Paragraph_LessonId",
table: "Paragraph",
column: "LessonId");
migrationBuilder.CreateIndex(
name: "IX_Success_UserId",
table: "Success",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_User_Email",
table: "User",
column: "Email",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_User_Username",
table: "User",
column: "Username",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "BlackList");
migrationBuilder.DropTable(
name: "InquiryTable");
migrationBuilder.DropTable(
name: "Notepad");
migrationBuilder.DropTable(
name: "Paragraph");
migrationBuilder.DropTable(
name: "Solution");
migrationBuilder.DropTable(
name: "Success");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "Lesson");
migrationBuilder.DropTable(
name: "Inquiries");
migrationBuilder.DropTable(
name: "User");
migrationBuilder.DropSequence(
name: "ContentLessonEntitySequence");
}
}
}

@ -0,0 +1,640 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using StubbedContextLib;
#nullable disable
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubbedContext))]
partial class StubbedContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.HasSequence("ContentLessonEntitySequence");
modelBuilder.Entity("Entities.BlackListEntity", b =>
{
b.Property<string>("Email")
.HasColumnType("text");
b.Property<DateOnly>("ExpirationDate")
.HasColumnType("date");
b.HasKey("Email");
b.ToTable("BlackList");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValueSql("nextval('\"ContentLessonEntitySequence\"')");
NpgsqlPropertyBuilderExtensions.UseSequence(b.Property<int>("Id"));
b.Property<string>("ContentContent")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentTitle")
.IsRequired()
.HasColumnType("text");
b.Property<int>("LessonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("LessonId");
b.ToTable((string)null);
b.UseTpcMappingStrategy();
});
modelBuilder.Entity("Entities.InquiryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsUser")
.HasColumnType("boolean");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Inquiries");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("ConnectionInfo")
.IsRequired()
.HasColumnType("text");
b.Property<string>("DatabaseName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("InquiryTable");
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateOnly>("LastEdit")
.HasColumnType("date");
b.Property<string>("LastPublisher")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Lesson");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("InquiryId");
b.HasIndex("UserId");
b.ToTable("Notepad");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("Explaination")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderPlace")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderWeapon")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererFirstName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererLastName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("Solution");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<bool>("IsFinished")
.HasColumnType("boolean");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("InquiryId");
b.HasIndex("UserId");
b.ToTable("Success");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("User");
b.HasData(
new
{
Id = 1,
Email = "Johnny.RATTON@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$7Dq.5Bf5WlHBMRqHBp5Ag.5PCCnvLrBXsuMGGJnV4l4WdngeDBpnW",
Username = "johnny"
},
new
{
Id = 2,
Email = "Maxime.SAPOUNTZIS@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$OT8g325JcE9mIdc.DiEKpem3kwNBdRcQ22vT2i5IB7KmfBfek4662",
Username = "maxime"
},
new
{
Id = 3,
Email = "Clement.CHIEU@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$Qc40bG8aCDvRSVjlWIn.1Orkd52fVMxBM2uQypVVwgu/mkeM8rnVK",
Username = "clement"
},
new
{
Id = 4,
Email = "Erwan.MENAGER@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$AW23BQcrS7d//LK0CtHuH.599OfYinEKCLkTz8Sbrtn.XYWE0u0BO",
Username = "erwan"
},
new
{
Id = 5,
Email = "Victor.GABORIT@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$ZOly/r95doGABtnypi8CAun1VnMRP1ct.idsUpXGe3pwjRYqv3ZQy",
Username = "victor"
});
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Entities.ParagraphEntity", b =>
{
b.HasBaseType("Entities.ContentLessonEntity");
b.Property<string>("Comment")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Query")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.ToTable("Paragraph");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.HasOne("Entities.LessonEntity", "Lesson")
.WithMany("Content")
.HasForeignKey("LessonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Lesson");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Navigation("Content");
});
#pragma warning restore 612, 618
}
}
}

@ -1,5 +1,6 @@
using System.Security.Cryptography;
using DbContextLib;
using DevOne.Security.Cryptography.BCrypt;
using Entities;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.EntityFrameworkCore;
@ -12,74 +13,200 @@ public class StubbedContext : UserDbContext
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserEntity>().HasData(
new UserEntity(1, "johnny", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Johnny.RATTON@etu.uca.fr", true),
new UserEntity(2, "maxime", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Maxime.SAPOUNTZIS@etu.uca.fr", true),
new UserEntity(3, "clement", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Clement.CHIEU@etu.uca.fr", true),
new UserEntity(4, "erwan", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Erwan.MENAGER@etu.uca.fr", true),
new UserEntity(5, "victor", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Victor.GABORIT@etu.uca.fr", true));
base.OnModelCreating(builder);
builder.Entity<UserEntity>().HasData(
new UserEntity
{
Id = 1,
Username = "johnny",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Johnny.RATTON@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 2,
Username = "maxime",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Maxime.SAPOUNTZIS@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 3,
Username = "clement",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Clement.CHIEU@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 4,
Username = "erwan",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Erwan.MENAGER@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 5,
Username = "victor",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Victor.GABORIT@etu.uca.fr",
IsAdmin = true
});
modelBuilder.Entity<InquiryTableEntity>().HasData(
new InquiryTableEntity(1, "Inquiry1",
"Server=localhost;Database=Inquiry1;Trusted_Connection=True;MultipleActiveResultSets=true"),
new InquiryTableEntity(2, "Inquiry2",
"Server=localhost;Database=Inquiry2;Trusted_Connection=True;MultipleActiveResultSets=true"),
new InquiryTableEntity(3, "Inquiry3",
"Server=localhost;Database=Inquiry3;Trusted_Connection=True;MultipleActiveResultSets=true"));
/*builder.Entity<InquiryTableEntity>().HasData(
new InquiryTableEntity
{
OwnerId = 1,
DatabaseName = "Inquiry1",
ConnectionInfo =
"Server=localhost;Database=Inquiry1;Trusted_Connection=True;MultipleActiveResultSets=true"
},
new InquiryTableEntity
{
OwnerId = 2,
DatabaseName = "Inquiry2",
ConnectionInfo =
"Server=localhost;Database=Inquiry2;Trusted_Connection=True;MultipleActiveResultSets=true"
},
new InquiryTableEntity
{
OwnerId = 3,
DatabaseName = "Inquiry3",
ConnectionInfo =
"Server=localhost;Database=Inquiry3;Trusted_Connection=True;MultipleActiveResultSets=true"
});
modelBuilder.Entity<SolutionEntity>().HasData(
new SolutionEntity(1, "Maxime", "Sapountzis", "La cuisine", "Le couteau", "Parce que c'est Maxime"),
new SolutionEntity(2, "Johnny", "Ratton", "La cuisine", "Le couteau", "Parce que il est fou"),
new SolutionEntity(3, "Erwan", "Menager", "La salle de bain", "L'arachide", "Parce que c'est Erwan"));
builder.Entity<SolutionEntity>().HasData(
new SolutionEntity
{
OwnerId = 1,
MurdererFirstName = "Maxime",
MurdererLastName = "Sapountzis",
MurderPlace = "La cuisine",
MurderWeapon = "Le couteau",
Explaination = "Parce que c'est Maxime"
},
new SolutionEntity
{
OwnerId = 2,
MurdererFirstName = "Johnny",
MurdererLastName = "Ratton",
MurderPlace = "La cuisine",
MurderWeapon = "Le couteau",
Explaination = "Parce que il est fou"
},
new SolutionEntity
{
OwnerId = 3,
MurdererFirstName = "Erwan",
MurdererLastName = "Menager",
MurderPlace = "La salle de bain",
MurderWeapon = "L'arachide",
Explaination = "Parce que c'est Erwan"
});
modelBuilder.Entity<LessonEntity>().HasData(
new LessonEntity(1, "La cuisine", "Maxime", new DateOnly(2021, 10, 10)),
new LessonEntity(2, "La salle de bain", "Erwan", new DateOnly(2021, 10, 10)),
new LessonEntity(3, "La chambre", "Johnny", new DateOnly(2021, 10, 10)),
new LessonEntity(4, "Le salon", "Clement", new DateOnly(2021, 10, 10)));
builder.Entity<InquiryEntity>().HasData(
new InquiryEntity
{
Id = 1,
Title = "L'enquête de la carotte",
Description = "La description de l'inquiry1",
IsUser = true
},
new InquiryEntity
{
Id = 2,
Title = "L'enquête sur les orang outan",
Description = "The new description",
IsUser = false
},
new InquiryEntity
{
Id = 3,
Title = "L'enquête sur les parapluies",
Description = "Il pleuvait",
IsUser = false
}
);
modelBuilder.Entity<ParagraphEntity>().HasData(
new ParagraphEntity(1, "Le premier paragraphe", "Le contenu du premier paragraphe", "Attention", "La query",
"Le commentaire", 1),
new ParagraphEntity(2, "Le deuxième paragraphe", "Le contenu du deuxième paragraphe", "Attention",
"La query", "Le commentaire", 1),
new ParagraphEntity(3, "Le troisième paragraphe", "Le contenu du troisième paragraphe", "Attention",
"query", "commentaire", 2),
new ParagraphEntity(4, "Le quatrième paragraphe", "Le contenu du quatrième paragraphe", "Attention",
"La query", "Le commentaire", 3),
new ParagraphEntity(5, "Le cinquième paragraphe", "Le contenu du quatrième paragraphe", "Attention",
"La query", "Le commentaire", 4));
modelBuilder.Entity<InquiryEntity>().HasData(
new InquiryEntity(1, "L'enquête de la carotte", "La description de l'inquiry1", true),
new InquiryEntity(2, "L'enquête sur les orang outan", "The new description", false),
new InquiryEntity(3, "L'enquête sur les parapluies", "Il pleuvait", false));
builder.Entity<SuccessEntity>().HasData(
new SuccessEntity
{
UserId = 1,
InquiryId = 1,
IsFinished = true
},
new SuccessEntity
{
UserId = 2,
InquiryId = 2,
IsFinished = false
},
new SuccessEntity
{
UserId = 3,
InquiryId = 3,
IsFinished = true
}
);
builder.Entity<LessonEntity>().HasData(
new LessonEntity
{
Id = 1, Title = "Lesson N°1", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
},
new LessonEntity
{
Id = 2, Title = "Lesson N°2", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
},
new LessonEntity
{
Id = 3, Title = "Lesson N°3", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
},
new LessonEntity
{
Id = 4, Title = "Lesson N°4", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
}
);
builder.Entity<ParagraphEntity>().HasData(
new ParagraphEntity { Id = 1, LessonId = 1, ContentTitle = "Paragraph N°1", ContentContent = "Content of paragraph N°1", Title = "Title Paragraph N°1", Content = "Content of paragraph N°1", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°1"},
new ParagraphEntity { Id = 2, LessonId = 1, ContentTitle = "Paragraph N°2", ContentContent = "Content of paragraph N°2", Title = "Title Paragraph N°2", Content = "Content of paragraph N°2", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°2"},
new ParagraphEntity { Id = 3, LessonId = 1, ContentTitle = "Paragraph N°3", ContentContent = "Content of paragraph N°3", Title = "Title Paragraph N°3", Content = "Content of paragraph N°3", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°3"},
new ParagraphEntity { Id = 4, LessonId = 2, ContentTitle = "Paragraph N°1", ContentContent = "Content of paragraph N°1", Title = "Title Paragraph N°1", Content = "Content of paragraph N°1", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°1"}
);*/
}
}

@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

@ -0,0 +1,195 @@
using API.Controllers;
using Dto;
using Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using Model.OrderCriteria;
using Moq;
using Shared;
using TestAPI.Extensions;
namespace TestAPI;
public class BlackListUnitTest
{
private readonly Mock<IBlackListService<BlackListDto>> _blackListService;
public BlackListUnitTest()
{
_blackListService = new Mock<IBlackListService<BlackListDto>>();
}
[Fact]
public void IsBanned()
{
_blackListService.Setup(x => x.GetUserBannedByEmail("email@example.com"))
.Returns(new BlackListDto { Email = "email@example.com", ExpirationDate = DateOnly.FromDateTime(DateTime.Now)});
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = usersController.GetUserBannedByEmail("email@example.com");
Assert.Equal(typeof(OkObjectResult), result.GetType());
}
[Fact]
public void IsBannedNotFound()
{
_blackListService.Setup(x => x.GetUserBannedByEmail("example@notfound.com"))
.Returns<BlackListDto?>(null);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = usersController.GetUserBannedByEmail("example@notfound.com");
Assert.Equal(typeof(NotFoundObjectResult), result.GetType());
}
[Fact]
public void BanUser()
{
_blackListService.Setup(x => x.BanUser("Test1"))
.Returns(true);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.BanUser("Test1");
Assert.Equal(typeof(OkObjectResult), userResult.GetType());
}
[Fact]
public void BanUserNotFound()
{
_blackListService.Setup(x => x.BanUser("Test1"))
.Returns(true);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.BanUser("Test42");
Assert.Equal(typeof(NotFoundResult), userResult.GetType());
}
[Fact]
public void UnbanUser()
{
_blackListService.Setup(x => x.UnbanUser("example@email.com"))
.Returns(true);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.UnbanUser("example@email.com");
Assert.Equal(typeof(OkObjectResult), userResult.GetType());
}
[Fact]
public void UnbanUserNotFound()
{
_blackListService.Setup(x => x.UnbanUser("example@email.com"))
.Returns(false);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.UnbanUser("example@email.com");
Assert.Equal(typeof(NotFoundResult), userResult.GetType());
}
[Fact]
public void GetBannedUsers_NoneOrderCriteria()
{
_blackListService.Setup(x => x.GetBannedUsers(1,10,BlackListOdrerCriteria.None))
.Returns(new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
});
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1,10,BlackListOdrerCriteria.None);
Assert.Equal(typeof(OkObjectResult), result.GetType());
if (result is OkObjectResult okObjectResult)
{
var valeur = okObjectResult.Value;
Assert.NotNull(valeur);
Assert.Equal(GetBlackList().ToString(), valeur.ToString());
Assert.True(GetBlackList().SequenceEqual(valeur as IEnumerable<BlackListDto>, new BlackListDtoEqualityComparer()));
}
}
[Fact]
public void GetBannedUsers_OrderByEmail()
{
_blackListService.Setup(x => x.GetBannedUsers(1,10,BlackListOdrerCriteria.ByEmail))
.Returns(new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
});
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1,10,BlackListOdrerCriteria.ByEmail);
Assert.Equal(typeof(OkObjectResult), result.GetType());
if (result is OkObjectResult okObjectResult)
{
var valeur = okObjectResult.Value;
Assert.NotNull(valeur);
Assert.Equal(GetBlackList().ToString(), valeur.ToString());
Assert.True(GetBlackList().SequenceEqual(valeur as IEnumerable<BlackListDto>, new BlackListDtoEqualityComparer()));
}
}
[Fact]
public void GetBannedUsers_OrderedByExpirationDate()
{
_blackListService.Setup(x => x.GetBannedUsers(1,10,BlackListOdrerCriteria.ByExpirationDate))
.Returns(new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
});
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1,10,BlackListOdrerCriteria.ByExpirationDate);
Assert.Equal(typeof(OkObjectResult), result.GetType());
if (result is OkObjectResult okObjectResult)
{
var valeur = okObjectResult.Value;
Assert.NotNull(valeur);
Assert.Equal(GetBlackList().ToString(), valeur.ToString());
Assert.True(GetBlackList().SequenceEqual(valeur as IEnumerable<BlackListDto>, new BlackListDtoEqualityComparer()));
}
}
[Fact]
public void Get_0_BannedUsers_OrderedByNone()
{
_blackListService.Setup(x => x.GetBannedUsers(1, 10, BlackListOdrerCriteria.None))
.Returns(new List<BlackListDto>());
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1, 10, BlackListOdrerCriteria.None);
Assert.Equal(typeof(StatusCodeResult), result.GetType());
if (result is NotFoundObjectResult notFoundObjectResult)
{
var valeur = notFoundObjectResult.Value;
Assert.NotNull(valeur);
}
}
[Fact]
public void GetNbBannedUsers()
{
_blackListService.Setup(x => x.GetNumberOfBannedUsers())
.Returns(10);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.GetNumberOfBannedUsers();
Assert.Equal(typeof(OkObjectResult), userResult.GetType());
Assert.Equal(10, ((KeyValuePair<string,int>)(userResult as OkObjectResult).Value).Value);
}
private IEnumerable<BlackListDto> GetBlackList()
{
return new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
};
}
}

@ -0,0 +1,16 @@
using Dto;
namespace TestAPI.Extensions;
public class BlackListDtoEqualityComparer : EqualityComparer<BlackListDto>
{
public override bool Equals(BlackListDto x, BlackListDto y)
{
return x.Email == y.Email;
}
public override int GetHashCode(BlackListDto obj)
{
return obj.Email.GetHashCode();
}
}

@ -0,0 +1,16 @@
using Dto;
namespace TestAPI.Extensions;
class InquiryIdEqualityComparer : EqualityComparer<InquiryDto>
{
public override bool Equals(InquiryDto x, InquiryDto y)
{
return x.Id == y.Id;
}
public override int GetHashCode(InquiryDto obj)
{
return obj.Id;
}
}

@ -0,0 +1,16 @@
using Dto;
namespace TestAPI.Extensions;
class LessonIdEqualityComparer : EqualityComparer<LessonDto>
{
public override bool Equals(LessonDto x, LessonDto y)
{
return x.Id == y.Id;
}
public override int GetHashCode(LessonDto obj)
{
return obj.Id;
}
}

@ -0,0 +1,16 @@
using Dto;
namespace TestAPI.Extensions;
class ParagraphIdEqualityComparer : EqualityComparer<ParagraphDto>
{
public override bool Equals(ParagraphDto x, ParagraphDto y)
{
return x.Id == y.Id;
}
public override int GetHashCode(ParagraphDto obj)
{
return obj.Id;
}
}

@ -0,0 +1,16 @@
using Dto;
namespace TestAPI.Extensions;
class SuccessIdEqualityComparer : EqualityComparer<SuccessDto>
{
public override bool Equals(SuccessDto x, SuccessDto y)
{
return x.UserId == y.UserId && x.InquiryId == y.InquiryId;
}
public override int GetHashCode(SuccessDto obj)
{
return obj.UserId * obj.InquiryId;
}
}

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

Loading…
Cancel
Save