├── .gitattributes ├── .github └── workflows │ └── azure-webapps-dotnet-core.yml ├── .gitignore ├── ApiResourcesNet7.sln ├── README.md └── TalentManagementAPI ├── TalentManagementAPI.Application ├── Behaviours │ └── ValidationBehaviour.cs ├── DTOs │ └── Email │ │ └── EmailRequest.cs ├── Enums │ └── Roles.cs ├── Exceptions │ ├── ApiException.cs │ └── ValidationException.cs ├── Features │ ├── Employees │ │ └── Queries │ │ │ └── GetEmployees │ │ │ ├── GetEmployeesQuery.cs │ │ │ ├── GetEmployeesViewModel.cs │ │ │ └── PagedEmployeesQuery.cs │ └── Positions │ │ ├── Commands │ │ ├── CreatePosition │ │ │ ├── CreatePositionCommand.cs │ │ │ ├── CreatePositionCommandValidator.cs │ │ │ └── InsertMockPositionCommand.cs │ │ ├── DeletePositionById │ │ │ └── DeleteProductByIdCommand.cs │ │ └── UpdatePosition │ │ │ └── UpdatePositionCommand.cs │ │ └── Queries │ │ ├── GetPositionById │ │ └── GetPositionByIdQuery.cs │ │ └── GetPositions │ │ ├── GetPositionsQuery.cs │ │ ├── GetPositionsViewModel.cs │ │ └── PagedPositionsQuery.cs ├── Helpers │ ├── DataShapeHelper.cs │ └── ModelHelper.cs ├── Interfaces │ ├── IDataShapeHelper.cs │ ├── IDateTimeService.cs │ ├── IEmailService.cs │ ├── IGenericRepositoryAsync.cs │ ├── IMockService.cs │ ├── IModelHelper.cs │ └── Repositories │ │ ├── IEmployeeRepositoryAsync.cs │ │ └── IPositionRepositoryAsync.cs ├── Mappings │ └── GeneralProfile.cs ├── Parameters │ ├── Column.cs │ ├── Order.cs │ ├── PagingParameter.cs │ ├── QueryParameter.cs │ ├── RecordsCount.cs │ └── Search.cs ├── ServiceExtensions.cs ├── TalentManagementAPI.Application.csproj └── Wrappers │ ├── PagedDataTableResponse.cs │ ├── PagedResponse.cs │ └── Response.cs ├── TalentManagementAPI.Domain ├── Common │ ├── AuditableBaseEntity.cs │ └── BaseEntity.cs ├── Entities │ ├── Employee.cs │ ├── Entity.cs │ └── Position.cs ├── Enums │ └── Gender.cs ├── Settings │ └── MailSettings.cs └── TalentManagementAPI.Domain.csproj ├── TalentManagementAPI.Infrastructure.Persistence ├── Contexts │ └── ApplicationDbContext.cs ├── Migrations │ ├── 20230211230526_InitialMigration.Designer.cs │ ├── 20230211230526_InitialMigration.cs │ └── ApplicationDbContextModelSnapshot.cs ├── Repositories │ ├── EmployeeRepositoryAsync.cs │ ├── GenericRepositoryAsync.cs │ └── PositionRepositoryAsync.cs ├── ServiceRegistration.cs └── TalentManagementAPI.Infrastructure.Persistence.csproj ├── TalentManagementAPI.Infrastructure.Shared ├── Mock │ ├── EmployeeBogusConfig.cs │ ├── PositionInsertBogusConfig.cs │ └── PositionSeedBogusConfig.cs ├── ServiceRegistration.cs ├── Services │ ├── DateTimeService.cs │ ├── EmailService.cs │ └── MockService.cs └── TalentManagementAPI.Infrastructure.Shared.csproj └── TalentManagementAPI.WebApi ├── Apiresources.WebApi.xml ├── Controllers ├── BaseApiController.cs ├── MetaController.cs └── v1 │ ├── EmployeesController.cs │ └── PositionsController.cs ├── Extensions ├── AppExtensions.cs ├── AuthorizationConsts.cs └── ServiceExtensions.cs ├── Middlewares └── ErrorHandlerMiddleware.cs ├── Models └── Metadata.cs ├── Program.cs ├── Properties └── launchSettings.json ├── TalentManagementAPI.WebApi.csproj ├── TalentManagementAPI.WebApi.xml ├── appsettings.Development.json └── appsettings.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/azure-webapps-dotnet-core.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build and push a .NET Core app to an Azure Web App when a commit is pushed to your default branch. 2 | # 3 | # This workflow assumes you have already created the target Azure App Service web app. 4 | # For instructions see https://docs.microsoft.com/en-us/azure/app-service/quickstart-dotnetcore?tabs=net60&pivots=development-environment-vscode 5 | # 6 | # To configure this workflow: 7 | # 8 | # 1. Download the Publish Profile for your Azure Web App. You can download this file from the Overview page of your Web App in the Azure Portal. 9 | # For more information: https://docs.microsoft.com/en-us/azure/app-service/deploy-github-actions?tabs=applevel#generate-deployment-credentials 10 | # 11 | # 2. Create a secret in your repository named AZURE_WEBAPP_PUBLISH_PROFILE, paste the publish profile contents as the value of the secret. 12 | # For instructions on obtaining the publish profile see: https://docs.microsoft.com/azure/app-service/deploy-github-actions#configure-the-github-secret 13 | # 14 | # 3. Change the value for the AZURE_WEBAPP_NAME. Optionally, change the AZURE_WEBAPP_PACKAGE_PATH and DOTNET_VERSION environment variables below. 15 | # 16 | # For more information on GitHub Actions for Azure: https://github.com/Azure/Actions 17 | # For more information on the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy 18 | # For more samples to get started with GitHub Action workflows to deploy to Azure: https://github.com/Azure/actions-workflow-samples 19 | 20 | name: Build and deploy ASP.Net Core app to an Azure Web App 21 | 22 | env: 23 | AZURE_WEBAPP_NAME: ApiResources # set this to the name of your Azure Web App 24 | AZURE_WEBAPP_PACKAGE_PATH: '.' # set this to the path to your web app project, defaults to the repository root 25 | DOTNET_VERSION: '7' # set this to the .NET Core version to use 26 | 27 | on: 28 | push: 29 | branches: [ "master" ] 30 | workflow_dispatch: 31 | 32 | permissions: 33 | contents: read 34 | 35 | jobs: 36 | build: 37 | runs-on: ubuntu-latest 38 | 39 | steps: 40 | - uses: actions/checkout@v3 41 | 42 | - name: Set up .NET Core 43 | uses: actions/setup-dotnet@v3 44 | with: 45 | dotnet-version: ${{ env.DOTNET_VERSION }} 46 | 47 | - name: Set up dependency caching for faster builds 48 | uses: actions/cache@v3 49 | with: 50 | path: ~/.nuget/packages 51 | key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }} 52 | restore-keys: | 53 | ${{ runner.os }}-nuget- 54 | 55 | - name: Build with dotnet 56 | run: dotnet build --configuration Release 57 | 58 | - name: dotnet publish 59 | run: dotnet publish -c Release -o ${{env.DOTNET_ROOT}}/myapp 60 | 61 | - name: Upload artifact for deployment job 62 | uses: actions/upload-artifact@v3 63 | with: 64 | name: .net-app 65 | path: ${{env.DOTNET_ROOT}}/myapp 66 | 67 | deploy: 68 | permissions: 69 | contents: none 70 | runs-on: ubuntu-latest 71 | needs: build 72 | environment: 73 | name: 'Development' 74 | url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} 75 | 76 | steps: 77 | - name: Download artifact from build job 78 | uses: actions/download-artifact@v3 79 | with: 80 | name: .net-app 81 | 82 | - name: Deploy to Azure Web App 83 | id: deploy-to-webapp 84 | uses: azure/webapps-deploy@v2 85 | with: 86 | app-name: ${{ env.AZURE_WEBAPP_NAME }} 87 | publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} 88 | package: ${{ env.AZURE_WEBAPP_PACKAGE_PATH }} 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /ApiResourcesNet7.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33213.308 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Presentation", "Presentation", "{32DF4157-BB16-473B-9DA7-3DFC4A4F0E3A}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TalentManagementAPI.WebApi", "TalentManagementAPI\TalentManagementAPI.WebApi\TalentManagementAPI.WebApi.csproj", "{8CFCABBC-D131-4E64-B350-E3C4404867AE}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{F72F8AE0-1E03-4458-9879-4A29DD91EC43}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TalentManagementAPI.Application", "TalentManagementAPI\TalentManagementAPI.Application\TalentManagementAPI.Application.csproj", "{2CF985B4-5D94-4405-B946-24E45E0B79DF}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TalentManagementAPI.Domain", "TalentManagementAPI\TalentManagementAPI.Domain\TalentManagementAPI.Domain.csproj", "{C2423C4F-1BEF-411C-BCDF-370AE4777CE9}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{8D90AA1A-231B-4A30-ABEF-C1D031A7F5A5}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TalentManagementAPI.Infrastructure.Persistence", "TalentManagementAPI\TalentManagementAPI.Infrastructure.Persistence\TalentManagementAPI.Infrastructure.Persistence.csproj", "{564EE677-77BA-4921-89B2-F873FAC22C93}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TalentManagementAPI.Infrastructure.Shared", "TalentManagementAPI\TalentManagementAPI.Infrastructure.Shared\TalentManagementAPI.Infrastructure.Shared.csproj", "{1B33FC9E-17D9-4104-AEEC-A402D6D5874C}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EDB3A0B7-420B-4781-801A-1A06998A0ADB}" 23 | ProjectSection(SolutionItems) = preProject 24 | README.md = README.md 25 | EndProjectSection 26 | EndProject 27 | Global 28 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 29 | Debug|Any CPU = Debug|Any CPU 30 | Release|Any CPU = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 33 | {8CFCABBC-D131-4E64-B350-E3C4404867AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {8CFCABBC-D131-4E64-B350-E3C4404867AE}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {8CFCABBC-D131-4E64-B350-E3C4404867AE}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {8CFCABBC-D131-4E64-B350-E3C4404867AE}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {2CF985B4-5D94-4405-B946-24E45E0B79DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {2CF985B4-5D94-4405-B946-24E45E0B79DF}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {2CF985B4-5D94-4405-B946-24E45E0B79DF}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {2CF985B4-5D94-4405-B946-24E45E0B79DF}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {C2423C4F-1BEF-411C-BCDF-370AE4777CE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {C2423C4F-1BEF-411C-BCDF-370AE4777CE9}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {C2423C4F-1BEF-411C-BCDF-370AE4777CE9}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {C2423C4F-1BEF-411C-BCDF-370AE4777CE9}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {564EE677-77BA-4921-89B2-F873FAC22C93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {564EE677-77BA-4921-89B2-F873FAC22C93}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {564EE677-77BA-4921-89B2-F873FAC22C93}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {564EE677-77BA-4921-89B2-F873FAC22C93}.Release|Any CPU.Build.0 = Release|Any CPU 49 | {1B33FC9E-17D9-4104-AEEC-A402D6D5874C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 50 | {1B33FC9E-17D9-4104-AEEC-A402D6D5874C}.Debug|Any CPU.Build.0 = Debug|Any CPU 51 | {1B33FC9E-17D9-4104-AEEC-A402D6D5874C}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {1B33FC9E-17D9-4104-AEEC-A402D6D5874C}.Release|Any CPU.Build.0 = Release|Any CPU 53 | EndGlobalSection 54 | GlobalSection(SolutionProperties) = preSolution 55 | HideSolutionNode = FALSE 56 | EndGlobalSection 57 | GlobalSection(NestedProjects) = preSolution 58 | {8CFCABBC-D131-4E64-B350-E3C4404867AE} = {32DF4157-BB16-473B-9DA7-3DFC4A4F0E3A} 59 | {2CF985B4-5D94-4405-B946-24E45E0B79DF} = {F72F8AE0-1E03-4458-9879-4A29DD91EC43} 60 | {C2423C4F-1BEF-411C-BCDF-370AE4777CE9} = {F72F8AE0-1E03-4458-9879-4A29DD91EC43} 61 | {564EE677-77BA-4921-89B2-F873FAC22C93} = {8D90AA1A-231B-4A30-ABEF-C1D031A7F5A5} 62 | {1B33FC9E-17D9-4104-AEEC-A402D6D5874C} = {8D90AA1A-231B-4A30-ABEF-C1D031A7F5A5} 63 | EndGlobalSection 64 | GlobalSection(ExtensibilityGlobals) = postSolution 65 | SolutionGuid = {B6C2FF39-F4C3-46F8-9660-AA780ECE358E} 66 | EndGlobalSection 67 | EndGlobal 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ApiResourcesNet7 2 | 3 | ## Blog post 4 | [Fullstack Angular 15, Bootstrap 5 & .NET 7 API: Project Demo](https://medium.com/scrum-and-coke/full-stack-angular-15-bootstrap-5-net-7-api-563227ef7a20) -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Behaviours/ValidationBehaviour.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using MediatR; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace TalentManagementAPI.Application.Behaviours 9 | { 10 | public class ValidationBehavior : IPipelineBehavior 11 | where TRequest : IRequest 12 | { 13 | private readonly IEnumerable> _validators; 14 | 15 | public ValidationBehavior(IEnumerable> validators) 16 | { 17 | _validators = validators; 18 | } 19 | 20 | public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) 21 | { 22 | if (_validators.Any()) 23 | { 24 | var context = new FluentValidation.ValidationContext(request); 25 | var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken))); 26 | var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList(); 27 | 28 | if (failures.Count != 0) 29 | throw new Exceptions.ValidationException(failures); 30 | } 31 | return await next(); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/DTOs/Email/EmailRequest.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.DTOs.Email 2 | { 3 | public class EmailRequest 4 | { 5 | public string To { get; set; } 6 | public string Subject { get; set; } 7 | public string Body { get; set; } 8 | public string From { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Enums/Roles.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Enums 2 | { 3 | public enum Roles 4 | { 5 | SuperAdmin, 6 | Admin, 7 | Manager, 8 | Employee 9 | } 10 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Exceptions/ApiException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | 4 | namespace TalentManagementAPI.Application.Exceptions 5 | { 6 | public class ApiException : Exception 7 | { 8 | public ApiException() : base() 9 | { 10 | } 11 | 12 | public ApiException(string message) : base(message) 13 | { 14 | } 15 | 16 | public ApiException(string message, params object[] args) 17 | : base(String.Format(CultureInfo.CurrentCulture, message, args)) 18 | { 19 | } 20 | 21 | public ApiException(string message, Exception innerException) : base(message, innerException) 22 | { 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation.Results; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace TalentManagementAPI.Application.Exceptions 6 | { 7 | public class ValidationException : Exception 8 | { 9 | public ValidationException() : base("One or more validation failures have occurred.") 10 | { 11 | Errors = new List(); 12 | } 13 | 14 | public List Errors { get; } 15 | 16 | public ValidationException(IEnumerable failures) 17 | : this() 18 | { 19 | foreach (var failure in failures) 20 | { 21 | Errors.Add(failure.ErrorMessage); 22 | } 23 | } 24 | 25 | public ValidationException(string message) : base(message) 26 | { 27 | } 28 | 29 | public ValidationException(string message, Exception innerException) : base(message, innerException) 30 | { 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Employees/Queries/GetEmployees/GetEmployeesQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces; 7 | using TalentManagementAPI.Application.Interfaces.Repositories; 8 | using TalentManagementAPI.Application.Parameters; 9 | using TalentManagementAPI.Application.Wrappers; 10 | using TalentManagementAPI.Domain.Entities; 11 | 12 | namespace TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees 13 | { 14 | /// 15 | /// GetAllEmployeesQuery - handles media IRequest 16 | /// BaseRequestParameter - contains paging parameters 17 | /// To add filter/search parameters, add search properties to the body of this class 18 | /// 19 | public class GetEmployeesQuery : QueryParameter, IRequest>> 20 | { 21 | //examples: 22 | public string EmployeeNumber { get; set; } 23 | public string EmployeeTitle { get; set; } 24 | public string LastName { get; set; } 25 | public string FirstName { get; set; } 26 | public string Email { get; set; } 27 | 28 | } 29 | 30 | public class GetAllEmployeesQueryHandler : IRequestHandler>> 31 | { 32 | private readonly IEmployeeRepositoryAsync _employeeRepository; 33 | private readonly IMapper _mapper; 34 | private readonly IModelHelper _modelHelper; 35 | 36 | 37 | 38 | /// 39 | /// Constructor for GetAllEmployeesQueryHandler class. 40 | /// 41 | /// IEmployeeRepositoryAsync object. 42 | /// IMapper object. 43 | /// IModelHelper object. 44 | /// 45 | /// GetAllEmployeesQueryHandler object. 46 | /// 47 | public GetAllEmployeesQueryHandler(IEmployeeRepositoryAsync employeeRepository, IMapper mapper, IModelHelper modelHelper) 48 | { 49 | _employeeRepository = employeeRepository; 50 | _mapper = mapper; 51 | _modelHelper = modelHelper; 52 | } 53 | 54 | 55 | 56 | /// 57 | /// Handles the GetEmployeesQuery request and returns a PagedResponse containing the requested data. 58 | /// 59 | /// The GetEmployeesQuery request. 60 | /// The cancellation token. 61 | /// A PagedResponse containing the requested data. 62 | public async Task>> Handle(GetEmployeesQuery request, CancellationToken cancellationToken) 63 | { 64 | var validFilter = request; 65 | //filtered fields security 66 | if (!string.IsNullOrEmpty(validFilter.Fields)) 67 | { 68 | //limit to fields in view model 69 | validFilter.Fields = _modelHelper.ValidateModelFields(validFilter.Fields); 70 | } 71 | if (string.IsNullOrEmpty(validFilter.Fields)) 72 | { 73 | //default fields from view model 74 | validFilter.Fields = _modelHelper.GetModelFields(); 75 | } 76 | // query based on filter 77 | var entityEmployees = await _employeeRepository.GetPagedEmployeeResponseAsync(validFilter); 78 | var data = entityEmployees.data; 79 | RecordsCount recordCount = entityEmployees.recordsCount; 80 | 81 | // response wrapper 82 | return new PagedResponse>(data, validFilter.PageNumber, validFilter.PageSize, recordCount); 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Employees/Queries/GetEmployees/GetEmployeesViewModel.cs: -------------------------------------------------------------------------------- 1 | using TalentManagementAPI.Domain.Entities; 2 | 3 | namespace TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees 4 | { 5 | public class GetEmployeesViewModel : Employee 6 | { 7 | 8 | } 9 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Employees/Queries/GetEmployees/PagedEmployeesQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces; 7 | using TalentManagementAPI.Application.Interfaces.Repositories; 8 | using TalentManagementAPI.Application.Parameters; 9 | using TalentManagementAPI.Application.Wrappers; 10 | using TalentManagementAPI.Domain.Entities; 11 | 12 | namespace TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees 13 | { 14 | public partial class PagedEmployeesQuery : IRequest>> 15 | { 16 | //strong type input parameters 17 | public int Draw { get; set; } //page number 18 | public int Start { get; set; } //Paging first record indicator. This is the start point in the current data set (0 index based - i.e. 0 is the first record). 19 | public int Length { get; set; } //page size 20 | public IList Order { get; set; } //Order by 21 | public Search Search { get; set; } //search criteria 22 | public IList Columns { get; set; } //select fields 23 | } 24 | 25 | public class PageEmployeeQueryHandler : IRequestHandler>> 26 | { 27 | private readonly IEmployeeRepositoryAsync _employeeRepository; 28 | private readonly IMapper _mapper; 29 | private readonly IModelHelper _modelHelper; 30 | 31 | 32 | 33 | /// 34 | /// Constructor for PageEmployeeQueryHandler class. 35 | /// 36 | /// IEmployeeRepositoryAsync object. 37 | /// IMapper object. 38 | /// IModelHelper object. 39 | /// 40 | /// PageEmployeeQueryHandler object. 41 | /// 42 | public PageEmployeeQueryHandler(IEmployeeRepositoryAsync employeeRepository, IMapper mapper, IModelHelper modelHelper) 43 | { 44 | _employeeRepository = employeeRepository; 45 | _mapper = mapper; 46 | _modelHelper = modelHelper; 47 | } 48 | 49 | 50 | 51 | /// 52 | /// Handles the PagedEmployeesQuery request and returns a PagedDataTableResponse. 53 | /// 54 | /// The PagedEmployeesQuery request. 55 | /// The cancellation token. 56 | /// A PagedDataTableResponse. 57 | public async Task>> Handle(PagedEmployeesQuery request, CancellationToken cancellationToken) 58 | { 59 | var validFilter = new GetEmployeesQuery(); 60 | 61 | // Draw map to PageNumber 62 | validFilter.PageNumber = (request.Start / request.Length) + 1; 63 | // Length map to PageSize 64 | validFilter.PageSize = request.Length; 65 | 66 | // Map order > OrderBy 67 | var colOrder = request.Order[0]; 68 | switch (colOrder.Column) 69 | { 70 | case 0: 71 | validFilter.OrderBy = colOrder.Dir == "asc" ? "LastName" : "LastName DESC"; 72 | break; 73 | 74 | case 1: 75 | validFilter.OrderBy = colOrder.Dir == "asc" ? "FirstName" : "FirstName DESC"; 76 | break; 77 | 78 | case 2: 79 | validFilter.OrderBy = colOrder.Dir == "asc" ? "EmployeeTitle" : "EmployeeTitle DESC"; 80 | break; 81 | case 3: 82 | validFilter.OrderBy = colOrder.Dir == "asc" ? "Email" : "Email DESC"; 83 | break; 84 | } 85 | 86 | // Map Search > searchable columns 87 | if (!string.IsNullOrEmpty(request.Search.Value)) 88 | { 89 | //limit to fields in view model 90 | validFilter.LastName = request.Search.Value; 91 | validFilter.FirstName = request.Search.Value; 92 | validFilter.Email = request.Search.Value; 93 | validFilter.EmployeeNumber = request.Search.Value; 94 | validFilter.EmployeeTitle = request.Search.Value; 95 | } 96 | if (string.IsNullOrEmpty(validFilter.Fields)) 97 | { 98 | //default fields from view model 99 | validFilter.Fields = _modelHelper.GetModelFields(); 100 | } 101 | // query based on filter 102 | var entityEmployees = await _employeeRepository.GetPagedEmployeeResponseAsync(validFilter); 103 | var data = entityEmployees.data; 104 | RecordsCount recordCount = entityEmployees.recordsCount; 105 | 106 | // response wrapper 107 | return new PagedDataTableResponse>(data, request.Draw, recordCount); 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Commands/CreatePosition/CreatePositionCommand.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using System; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces.Repositories; 7 | using TalentManagementAPI.Application.Wrappers; 8 | using TalentManagementAPI.Domain.Entities; 9 | 10 | namespace TalentManagementAPI.Application.Features.Positions.Commands.CreatePosition 11 | { 12 | public partial class CreatePositionCommand : IRequest> 13 | { 14 | public string PositionTitle { get; set; } 15 | public string PositionNumber { get; set; } 16 | public string PositionDescription { get; set; } 17 | public decimal PositionSalary { get; set; } 18 | } 19 | 20 | public class CreatePositionCommandHandler : IRequestHandler> 21 | { 22 | private readonly IPositionRepositoryAsync _positionRepository; 23 | private readonly IMapper _mapper; 24 | 25 | 26 | 27 | /// 28 | /// Constructor for CreatePositionCommandHandler class. 29 | /// 30 | /// IPositionRepositoryAsync object 31 | /// IMapper object 32 | /// 33 | /// CreatePositionCommandHandler object 34 | /// 35 | public CreatePositionCommandHandler(IPositionRepositoryAsync positionRepository, IMapper mapper) 36 | { 37 | _positionRepository = positionRepository; 38 | _mapper = mapper; 39 | } 40 | 41 | 42 | 43 | /// 44 | /// Handles the CreatePositionCommand request by mapping it to a position object and adding it to the position repository. 45 | /// 46 | /// The CreatePositionCommand request. 47 | /// The cancellation token. 48 | /// A response containing the Id of the created position. 49 | public async Task> Handle(CreatePositionCommand request, CancellationToken cancellationToken) 50 | { 51 | var position = _mapper.Map(request); 52 | await _positionRepository.AddAsync(position); 53 | return new Response(position.Id); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Commands/CreatePosition/CreatePositionCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagementAPI.Application.Interfaces.Repositories; 5 | 6 | namespace TalentManagementAPI.Application.Features.Positions.Commands.CreatePosition 7 | { 8 | public class CreatePositionCommandValidator : AbstractValidator 9 | { 10 | private readonly IPositionRepositoryAsync positionRepository; 11 | 12 | 13 | 14 | /// 15 | /// Constructor for CreatePositionCommandValidator class. 16 | /// 17 | /// IPositionRepositoryAsync object. 18 | /// 19 | /// CreatePositionCommandValidator object. 20 | /// 21 | public CreatePositionCommandValidator(IPositionRepositoryAsync positionRepository) 22 | { 23 | this.positionRepository = positionRepository; 24 | 25 | RuleFor(p => p.PositionNumber) 26 | .NotEmpty().WithMessage("{PropertyName} is required.") 27 | .NotNull() 28 | .MaximumLength(50).WithMessage("{PropertyName} must not exceed 50 characters.") 29 | .MustAsync(IsUniquePositionNumber).WithMessage("{PropertyName} already exists."); 30 | 31 | RuleFor(p => p.PositionTitle) 32 | .NotEmpty().WithMessage("{PropertyName} is required.") 33 | .NotNull() 34 | .MaximumLength(50).WithMessage("{PropertyName} must not exceed 50 characters."); 35 | } 36 | 37 | 38 | 39 | /// 40 | /// Checks if the given position number is unique. 41 | /// 42 | /// The position number to check. 43 | /// The cancellation token. 44 | /// A task that represents the asynchronous operation. 45 | private async Task IsUniquePositionNumber(string positionNumber, CancellationToken cancellationToken) 46 | { 47 | return await positionRepository.IsUniquePositionNumberAsync(positionNumber); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Commands/CreatePosition/InsertMockPositionCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagementAPI.Application.Interfaces.Repositories; 5 | using TalentManagementAPI.Application.Wrappers; 6 | 7 | namespace TalentManagementAPI.Application.Features.Positions.Commands.CreatePosition 8 | { 9 | public partial class InsertMockPositionCommand : IRequest> 10 | { 11 | public int RowCount { get; set; } 12 | } 13 | 14 | public class SeedPositionCommandHandler : IRequestHandler> 15 | { 16 | private readonly IPositionRepositoryAsync _positionRepository; 17 | 18 | 19 | 20 | /// 21 | /// Constructor for the SeedPositionCommandHandler class. 22 | /// 23 | /// The IPositionRepositoryAsync object to be used. 24 | /// 25 | /// A new instance of the SeedPositionCommandHandler class. 26 | /// 27 | public SeedPositionCommandHandler(IPositionRepositoryAsync positionRepository) 28 | { 29 | _positionRepository = positionRepository; 30 | } 31 | 32 | 33 | 34 | /// 35 | /// Handles the InsertMockPositionCommand by seeding the data in the PositionRepository and returning a Response. 36 | /// 37 | /// The InsertMockPositionCommand to be handled. 38 | /// The CancellationToken used for cancellation. 39 | /// A Response containing the number of rows inserted. 40 | public async Task> Handle(InsertMockPositionCommand request, CancellationToken cancellationToken) 41 | { 42 | await _positionRepository.SeedDataAsync(request.RowCount); 43 | return new Response(request.RowCount); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Commands/DeletePositionById/DeleteProductByIdCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using TalentManagementAPI.Application.Exceptions; 6 | using TalentManagementAPI.Application.Interfaces.Repositories; 7 | using TalentManagementAPI.Application.Wrappers; 8 | 9 | namespace TalentManagementAPI.Application.Features.Positions.Commands.DeletePositionById 10 | { 11 | public class DeletePositionByIdCommand : IRequest> 12 | { 13 | public Guid Id { get; set; } 14 | 15 | public class DeletePositionByIdCommandHandler : IRequestHandler> 16 | { 17 | private readonly IPositionRepositoryAsync _positionRepository; 18 | 19 | 20 | 21 | /// 22 | /// Constructor for DeletePositionByIdCommandHandler class. 23 | /// 24 | /// IPositionRepositoryAsync object 25 | /// 26 | /// DeletePositionByIdCommandHandler object 27 | /// 28 | public DeletePositionByIdCommandHandler(IPositionRepositoryAsync positionRepository) 29 | { 30 | _positionRepository = positionRepository; 31 | } 32 | 33 | 34 | 35 | /// 36 | /// Handles the DeletePositionByIdCommand and deletes the position with the given Id. 37 | /// 38 | /// The DeletePositionByIdCommand containing the Id of the position to delete. 39 | /// The cancellation token. 40 | /// A Response containing the Id of the deleted position. 41 | public async Task> Handle(DeletePositionByIdCommand command, CancellationToken cancellationToken) 42 | { 43 | var position = await _positionRepository.GetByIdAsync(command.Id); 44 | if (position == null) throw new ApiException($"Position Not Found."); 45 | await _positionRepository.DeleteAsync(position); 46 | return new Response(position.Id); 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Commands/UpdatePosition/UpdatePositionCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using TalentManagementAPI.Application.Exceptions; 6 | using TalentManagementAPI.Application.Interfaces.Repositories; 7 | using TalentManagementAPI.Application.Wrappers; 8 | 9 | namespace TalentManagementAPI.Application.Features.Positions.Commands.UpdatePosition 10 | { 11 | public class UpdatePositionCommand : IRequest> 12 | { 13 | public Guid Id { get; set; } 14 | public string PositionTitle { get; set; } 15 | public string PositionDescription { get; set; } 16 | public decimal PositionSalary { get; set; } 17 | 18 | public class UpdatePositionCommandHandler : IRequestHandler> 19 | { 20 | private readonly IPositionRepositoryAsync _positionRepository; 21 | 22 | 23 | 24 | /// 25 | /// Constructor for UpdatePositionCommandHandler class. 26 | /// 27 | /// IPositionRepositoryAsync object 28 | /// 29 | /// UpdatePositionCommandHandler object 30 | /// 31 | public UpdatePositionCommandHandler(IPositionRepositoryAsync positionRepository) 32 | { 33 | _positionRepository = positionRepository; 34 | } 35 | 36 | 37 | 38 | /// 39 | /// Handles the UpdatePositionCommand and updates the position in the repository. 40 | /// 41 | /// The command containing the updated position information. 42 | /// The cancellation token. 43 | /// A response containing the Id of the updated position. 44 | public async Task> Handle(UpdatePositionCommand command, CancellationToken cancellationToken) 45 | { 46 | var position = await _positionRepository.GetByIdAsync(command.Id); 47 | 48 | if (position == null) 49 | { 50 | throw new ApiException($"Position Not Found."); 51 | } 52 | else 53 | { 54 | position.PositionTitle = command.PositionTitle; 55 | position.PositionSalary = command.PositionSalary; 56 | position.PositionDescription = command.PositionDescription; 57 | await _positionRepository.UpdateAsync(position); 58 | return new Response(position.Id); 59 | } 60 | } 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Queries/GetPositionById/GetPositionByIdQuery.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using TalentManagementAPI.Application.Exceptions; 6 | using TalentManagementAPI.Application.Interfaces.Repositories; 7 | using TalentManagementAPI.Application.Wrappers; 8 | using TalentManagementAPI.Domain.Entities; 9 | 10 | namespace TalentManagementAPI.Application.Features.Positions.Queries.GetPositionById 11 | { 12 | public class GetPositionByIdQuery : IRequest> 13 | { 14 | public Guid Id { get; set; } 15 | 16 | public class GetPositionByIdQueryHandler : IRequestHandler> 17 | { 18 | private readonly IPositionRepositoryAsync _positionRepository; 19 | 20 | public GetPositionByIdQueryHandler(IPositionRepositoryAsync positionRepository) 21 | { 22 | _positionRepository = positionRepository; 23 | } 24 | 25 | public async Task> Handle(GetPositionByIdQuery query, CancellationToken cancellationToken) 26 | { 27 | var position = await _positionRepository.GetByIdAsync(query.Id); 28 | if (position == null) throw new ApiException($"Position Not Found."); 29 | return new Response(position); 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Queries/GetPositions/GetPositionsQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces; 7 | using TalentManagementAPI.Application.Interfaces.Repositories; 8 | using TalentManagementAPI.Application.Parameters; 9 | using TalentManagementAPI.Application.Wrappers; 10 | using TalentManagementAPI.Domain.Entities; 11 | 12 | namespace TalentManagementAPI.Application.Features.Positions.Queries.GetPositions 13 | { 14 | public class GetPositionsQuery : QueryParameter, IRequest>> 15 | { 16 | public string PositionNumber { get; set; } 17 | public string PositionTitle { get; set; } 18 | public string PositionDescription { get; set; } 19 | } 20 | 21 | public class GetAllPositionsQueryHandler : IRequestHandler>> 22 | { 23 | private readonly IPositionRepositoryAsync _positionRepository; 24 | private readonly IMapper _mapper; 25 | private readonly IModelHelper _modelHelper; 26 | 27 | 28 | 29 | /// 30 | /// Constructor for GetAllPositionsQueryHandler class. 31 | /// 32 | /// IPositionRepositoryAsync object. 33 | /// IMapper object. 34 | /// IModelHelper object. 35 | /// 36 | /// GetAllPositionsQueryHandler object. 37 | /// 38 | public GetAllPositionsQueryHandler(IPositionRepositoryAsync positionRepository, IMapper mapper, IModelHelper modelHelper) 39 | { 40 | _positionRepository = positionRepository; 41 | _mapper = mapper; 42 | _modelHelper = modelHelper; 43 | } 44 | 45 | 46 | 47 | /// 48 | /// Handles the GetPositionsQuery request and returns a PagedResponse containing the data and records count. 49 | /// 50 | /// The GetPositionsQuery request. 51 | /// The cancellation token. 52 | /// A PagedResponse containing the data and records count. 53 | public async Task>> Handle(GetPositionsQuery request, CancellationToken cancellationToken) 54 | { 55 | 56 | var validFilter = request; 57 | //filtered fields security 58 | if (!string.IsNullOrEmpty(validFilter.Fields)) 59 | { 60 | //limit to fields in view model 61 | validFilter.Fields = _modelHelper.ValidateModelFields(validFilter.Fields); 62 | } 63 | if (string.IsNullOrEmpty(validFilter.Fields)) 64 | { 65 | //default fields from view model 66 | validFilter.Fields = _modelHelper.GetModelFields(); 67 | } 68 | // query based on filter 69 | var entityPositions = await _positionRepository.GetPagedPositionReponseAsync(validFilter); 70 | var data = entityPositions.data; 71 | RecordsCount recordCount = entityPositions.recordsCount; 72 | // response wrapper 73 | return new PagedResponse>(data, validFilter.PageNumber, validFilter.PageSize, recordCount); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Queries/GetPositions/GetPositionsViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TalentManagementAPI.Application.Features.Positions.Queries.GetPositions 4 | { 5 | public class GetPositionsViewModel 6 | { 7 | public Guid Id { get; set; } 8 | public string PositionTitle { get; set; } 9 | public string PositionNumber { get; set; } 10 | public string PositionDescription { get; set; } 11 | public decimal PositionSalary { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Features/Positions/Queries/GetPositions/PagedPositionsQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces; 7 | using TalentManagementAPI.Application.Interfaces.Repositories; 8 | using TalentManagementAPI.Application.Parameters; 9 | using TalentManagementAPI.Application.Wrappers; 10 | using TalentManagementAPI.Domain.Entities; 11 | 12 | namespace TalentManagementAPI.Application.Features.Positions.Queries.GetPositions 13 | { 14 | public partial class PagedPositionsQuery : IRequest>> 15 | { 16 | //strong type input parameters 17 | public int Draw { get; set; } //page number 18 | public int Start { get; set; } //Paging first record indicator. This is the start point in the current data set (0 index based - i.e. 0 is the first record). 19 | public int Length { get; set; } //page size 20 | public IList Order { get; set; } //Order by 21 | public Search Search { get; set; } //search criteria 22 | public IList Columns { get; set; } //select fields 23 | } 24 | 25 | public class PagePositionQueryHandler : IRequestHandler>> 26 | { 27 | private readonly IPositionRepositoryAsync _positionRepository; 28 | private readonly IModelHelper _modelHelper; 29 | 30 | 31 | 32 | /// 33 | /// Constructor for PagePositionQueryHandler class. 34 | /// 35 | /// IPositionRepositoryAsync object. 36 | /// IMapper object. 37 | /// IModelHelper object. 38 | /// 39 | /// PagePositionQueryHandler object. 40 | /// 41 | public PagePositionQueryHandler(IPositionRepositoryAsync positionRepository, IMapper mapper, IModelHelper modelHelper) 42 | { 43 | _positionRepository = positionRepository; 44 | _modelHelper = modelHelper; 45 | } 46 | 47 | 48 | 49 | /// 50 | /// Handles the specified PagedPositionsQuery request with the given CancellationToken. 51 | /// 52 | public async Task>> Handle(PagedPositionsQuery request, CancellationToken cancellationToken) 53 | { 54 | var validFilter = new GetPositionsQuery(); 55 | 56 | // Draw map to PageNumber 57 | validFilter.PageNumber = (request.Start / request.Length) + 1; 58 | // Length map to PageSize 59 | validFilter.PageSize = request.Length; 60 | 61 | // Map order > OrderBy 62 | var colOrder = request.Order[0]; 63 | switch (colOrder.Column) 64 | { 65 | case 0: 66 | validFilter.OrderBy = colOrder.Dir == "asc" ? "PositionNumber" : "PositionNumber DESC"; 67 | break; 68 | 69 | case 1: 70 | validFilter.OrderBy = colOrder.Dir == "asc" ? "PositionTitle" : "PositionTitle DESC"; 71 | break; 72 | 73 | case 2: 74 | validFilter.OrderBy = colOrder.Dir == "asc" ? "PositionDescription" : "PositionDescription DESC"; 75 | break; 76 | } 77 | 78 | // Map Search > searchable columns 79 | if (!string.IsNullOrEmpty(request.Search.Value)) 80 | { 81 | //limit to fields in view model 82 | validFilter.PositionNumber = request.Search.Value; 83 | validFilter.PositionTitle = request.Search.Value; 84 | validFilter.PositionDescription = request.Search.Value; 85 | } 86 | if (string.IsNullOrEmpty(validFilter.Fields)) 87 | { 88 | //default fields from view model 89 | validFilter.Fields = _modelHelper.GetModelFields(); 90 | } 91 | // query based on filter 92 | var entityPositions = await _positionRepository.GetPagedPositionReponseAsync(validFilter); 93 | var data = entityPositions.data; 94 | RecordsCount recordCount = entityPositions.recordsCount; 95 | 96 | // response wrapper 97 | return new PagedDataTableResponse>(data, request.Draw, recordCount); 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Helpers/DataShapeHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces; 7 | using TalentManagementAPI.Domain.Entities; 8 | 9 | namespace TalentManagementAPI.Application.Helpers 10 | { 11 | public class DataShapeHelper : IDataShapeHelper 12 | { 13 | public PropertyInfo[] Properties { get; set; } 14 | 15 | public DataShapeHelper() 16 | { 17 | Properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 18 | } 19 | 20 | public IEnumerable ShapeData(IEnumerable entities, string fieldsString) 21 | { 22 | var requiredProperties = GetRequiredProperties(fieldsString); 23 | 24 | return FetchData(entities, requiredProperties); 25 | } 26 | 27 | public async Task> ShapeDataAsync(IEnumerable entities, string fieldsString) 28 | { 29 | var requiredProperties = GetRequiredProperties(fieldsString); 30 | 31 | return await Task.Run(() => FetchData(entities, requiredProperties)); 32 | } 33 | 34 | public Entity ShapeData(T entity, string fieldsString) 35 | { 36 | var requiredProperties = GetRequiredProperties(fieldsString); 37 | 38 | return FetchDataForEntity(entity, requiredProperties); 39 | } 40 | 41 | private IEnumerable GetRequiredProperties(string fieldsString) 42 | { 43 | var requiredProperties = new List(); 44 | 45 | if (!string.IsNullOrWhiteSpace(fieldsString)) 46 | { 47 | var fields = fieldsString.Split(',', StringSplitOptions.RemoveEmptyEntries); 48 | 49 | foreach (var field in fields) 50 | { 51 | var property = Properties.FirstOrDefault(pi => pi.Name.Equals(field.Trim(), StringComparison.InvariantCultureIgnoreCase)); 52 | 53 | if (property == null) 54 | continue; 55 | 56 | requiredProperties.Add(property); 57 | } 58 | } 59 | else 60 | { 61 | requiredProperties = Properties.ToList(); 62 | } 63 | 64 | return requiredProperties; 65 | } 66 | 67 | private IEnumerable FetchData(IEnumerable entities, IEnumerable requiredProperties) 68 | { 69 | var shapedData = new List(); 70 | 71 | foreach (var entity in entities) 72 | { 73 | var shapedObject = FetchDataForEntity(entity, requiredProperties); 74 | shapedData.Add(shapedObject); 75 | } 76 | 77 | return shapedData; 78 | } 79 | 80 | private Entity FetchDataForEntity(T entity, IEnumerable requiredProperties) 81 | { 82 | var shapedObject = new Entity(); 83 | 84 | foreach (var property in requiredProperties) 85 | { 86 | var objectPropertyValue = property.GetValue(entity); 87 | shapedObject.TryAdd(property.Name, objectPropertyValue); 88 | } 89 | 90 | return shapedObject; 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Helpers/ModelHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using TalentManagementAPI.Application.Interfaces; 4 | 5 | namespace TalentManagementAPI.Application.Helpers 6 | { 7 | public class ModelHelper : IModelHelper 8 | { 9 | /// 10 | /// Check field name in the model class 11 | /// 12 | /// 13 | /// 14 | /// 15 | public string ValidateModelFields(string fields) 16 | { 17 | string retString = string.Empty; 18 | 19 | var bindingFlags = System.Reflection.BindingFlags.Instance | 20 | System.Reflection.BindingFlags.NonPublic | 21 | System.Reflection.BindingFlags.Public; 22 | var listFields = typeof(T).GetProperties(bindingFlags).Select(f => f.Name).ToList(); 23 | string[] arrayFields = fields.Split(','); 24 | foreach (var field in arrayFields) 25 | { 26 | if (listFields.Contains(field.Trim(), StringComparer.OrdinalIgnoreCase)) 27 | retString += field + ","; 28 | }; 29 | return retString; 30 | } 31 | 32 | /// 33 | /// Get list of field names in the model class 34 | /// 35 | /// 36 | /// 37 | public string GetModelFields() 38 | { 39 | string retString = string.Empty; 40 | 41 | var bindingFlags = System.Reflection.BindingFlags.Instance | 42 | System.Reflection.BindingFlags.NonPublic | 43 | System.Reflection.BindingFlags.Public; 44 | var listFields = typeof(T).GetProperties(bindingFlags).Select(f => f.Name).ToList(); 45 | 46 | foreach (string field in listFields) 47 | { 48 | retString += field + ","; 49 | } 50 | 51 | return retString; 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/IDataShapeHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using TalentManagementAPI.Domain.Entities; 4 | 5 | namespace TalentManagementAPI.Application.Interfaces 6 | { 7 | public interface IDataShapeHelper 8 | { 9 | IEnumerable ShapeData(IEnumerable entities, string fieldsString); 10 | 11 | Task> ShapeDataAsync(IEnumerable entities, string fieldsString); 12 | 13 | Entity ShapeData(T entity, string fieldsString); 14 | } 15 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/IDateTimeService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TalentManagementAPI.Application.Interfaces 4 | { 5 | public interface IDateTimeService 6 | { 7 | DateTime NowUtc { get; } 8 | } 9 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/IEmailService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using TalentManagementAPI.Application.DTOs.Email; 3 | 4 | namespace TalentManagementAPI.Application.Interfaces 5 | { 6 | public interface IEmailService 7 | { 8 | Task SendAsync(EmailRequest request); 9 | } 10 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/IGenericRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace TalentManagementAPI.Application.Interfaces 6 | { 7 | 8 | 9 | /// 10 | /// Represents an interface for a generic repository with asynchronous methods. 11 | /// 12 | /// The type of entity. 13 | /// 14 | /// An asynchronous repository for the specified entity type. 15 | /// 16 | public interface IGenericRepositoryAsync where T : class 17 | { 18 | Task GetByIdAsync(Guid id); 19 | 20 | Task> GetAllAsync(); 21 | 22 | Task> GetPagedReponseAsync(int pageNumber, int pageSize); 23 | 24 | Task> GetPagedAdvancedReponseAsync(int pageNumber, int pageSize, string orderBy, string fields); 25 | 26 | Task AddAsync(T entity); 27 | 28 | Task BulkInsertAsync(IList entity); 29 | 30 | Task UpdateAsync(T entity); 31 | 32 | Task DeleteAsync(T entity); 33 | } 34 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/IMockService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using TalentManagementAPI.Domain.Entities; 3 | 4 | namespace TalentManagementAPI.Application.Interfaces 5 | { 6 | 7 | 8 | /// 9 | /// Interface for MockService. 10 | /// 11 | /// 12 | /// List of positions, employees, and seed positions. 13 | /// 14 | public interface IMockService 15 | { 16 | List GetPositions(int rowCount); 17 | 18 | List GetEmployees(int rowCount); 19 | 20 | List SeedPositions(int rowCount); 21 | } 22 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/IModelHelper.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Interfaces 2 | { 3 | 4 | 5 | /// 6 | /// Interface for providing helper methods for models. 7 | /// 8 | /// 9 | /// GetModelFields() - Returns a string of model fields. 10 | /// ValidateModelFields(string fields) - Validates the given model fields and returns a string. 11 | /// 12 | public interface IModelHelper 13 | { 14 | string GetModelFields(); 15 | 16 | string ValidateModelFields(string fields); 17 | } 18 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/Repositories/IEmployeeRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees; 4 | using TalentManagementAPI.Application.Parameters; 5 | using TalentManagementAPI.Domain.Entities; 6 | 7 | namespace TalentManagementAPI.Application.Interfaces.Repositories 8 | { 9 | 10 | 11 | /// 12 | /// Interface for retrieving paged employee response asynchronously. 13 | /// 14 | /// The request parameters. 15 | /// 16 | /// A task that represents the asynchronous operation. 17 | /// 18 | public interface IEmployeeRepositoryAsync : IGenericRepositoryAsync 19 | { 20 | Task<(IEnumerable data, RecordsCount recordsCount)> GetPagedEmployeeResponseAsync(GetEmployeesQuery requestParameters); 21 | } 22 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Interfaces/Repositories/IPositionRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using TalentManagementAPI.Application.Features.Positions.Queries.GetPositions; 4 | using TalentManagementAPI.Application.Parameters; 5 | using TalentManagementAPI.Domain.Entities; 6 | 7 | namespace TalentManagementAPI.Application.Interfaces.Repositories 8 | { 9 | 10 | 11 | /// 12 | /// Repository interface for Position entity with asynchronous methods. 13 | /// 14 | /// Position number to check for uniqueness. 15 | /// 16 | /// Task indicating whether the position number is unique. 17 | /// 18 | /// Number of rows to seed. 19 | /// 20 | /// Task indicating the completion of seeding. 21 | /// 22 | /// Parameters for the query. 23 | /// Data to be returned. 24 | /// Number of records. 25 | /// 26 | /// Task containing the paged response. 27 | /// 28 | public interface IPositionRepositoryAsync : IGenericRepositoryAsync 29 | { 30 | Task IsUniquePositionNumberAsync(string positionNumber); 31 | 32 | Task SeedDataAsync(int rowCount); 33 | 34 | Task<(IEnumerable data, RecordsCount recordsCount)> GetPagedPositionReponseAsync(GetPositionsQuery requestParameters); 35 | } 36 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Mappings/GeneralProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees; 3 | using TalentManagementAPI.Application.Features.Positions.Commands.CreatePosition; 4 | using TalentManagementAPI.Application.Features.Positions.Queries.GetPositions; 5 | using TalentManagementAPI.Domain.Entities; 6 | 7 | namespace TalentManagementAPI.Application.Mappings 8 | { 9 | public class GeneralProfile : Profile 10 | { 11 | public GeneralProfile() 12 | { 13 | CreateMap().ReverseMap(); 14 | CreateMap().ReverseMap(); 15 | CreateMap(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Parameters/Column.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Parameters 2 | { 3 | public class Column 4 | { 5 | public string Data { get; set; } 6 | public string Name { get; set; } 7 | public bool Searchable { get; set; } 8 | public bool Orderable { get; set; } 9 | public Search Search { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Parameters/Order.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Parameters 2 | { 3 | public class Order 4 | { 5 | public int Column { get; set; } 6 | public string Dir { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Parameters/PagingParameter.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Parameters 2 | { 3 | public class PagingParameter 4 | { 5 | private const int maxPageSize = 200; 6 | public int PageNumber { get; set; } = 1; 7 | private int _pageSize = 10; 8 | 9 | public int PageSize 10 | { 11 | get 12 | { 13 | return _pageSize; 14 | } 15 | set 16 | { 17 | _pageSize = (value > maxPageSize) ? maxPageSize : value; 18 | } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Parameters/QueryParameter.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Parameters 2 | { 3 | public class QueryParameter : PagingParameter 4 | { 5 | public virtual string OrderBy { get; set; } 6 | public virtual string Fields { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Parameters/RecordsCount.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Parameters 2 | { 3 | public class RecordsCount 4 | { 5 | public int RecordsFiltered { get; set; } 6 | public int RecordsTotal { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Parameters/Search.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Application.Parameters 2 | { 3 | public class Search 4 | { 5 | public string Value { get; set; } 6 | public bool Regex { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/ServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using MediatR; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using System.Reflection; 5 | using TalentManagementAPI.Application.Behaviours; 6 | using TalentManagementAPI.Application.Helpers; 7 | using TalentManagementAPI.Application.Interfaces; 8 | using TalentManagementAPI.Domain.Entities; 9 | 10 | namespace TalentManagementAPI.Application 11 | { 12 | public static class ServiceExtensions 13 | { 14 | public static void AddApplicationLayer(this IServiceCollection services) 15 | { 16 | services.AddAutoMapper(Assembly.GetExecutingAssembly()); 17 | services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); 18 | services.AddMediatR(Assembly.GetExecutingAssembly()); 19 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); 20 | services.AddScoped, DataShapeHelper>(); 21 | services.AddScoped, DataShapeHelper>(); 22 | services.AddScoped(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/TalentManagementAPI.Application.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | 1.0.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Wrappers/PagedDataTableResponse.cs: -------------------------------------------------------------------------------- 1 | using TalentManagementAPI.Application.Parameters; 2 | 3 | namespace TalentManagementAPI.Application.Wrappers 4 | { 5 | public class PagedDataTableResponse : Response 6 | { 7 | public int Draw { get; set; } 8 | public int RecordsFiltered { get; set; } 9 | public int RecordsTotal { get; set; } 10 | 11 | 12 | 13 | /// 14 | /// Constructor for PagedDataTableResponse class. 15 | /// 16 | /// Data to be returned. 17 | /// Page number. 18 | /// Records count. 19 | /// 20 | /// An instance of PagedDataTableResponse. 21 | /// 22 | public PagedDataTableResponse(T data, int pageNumber, RecordsCount recordsCount) 23 | { 24 | this.Draw = pageNumber; 25 | this.RecordsFiltered = recordsCount.RecordsFiltered; 26 | this.RecordsTotal = recordsCount.RecordsTotal; 27 | this.Data = data; 28 | this.Message = null; 29 | this.Succeeded = true; 30 | this.Errors = null; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Wrappers/PagedResponse.cs: -------------------------------------------------------------------------------- 1 | using TalentManagementAPI.Application.Parameters; 2 | 3 | namespace TalentManagementAPI.Application.Wrappers 4 | { 5 | public class PagedResponse : Response 6 | { 7 | public virtual int PageNumber { get; set; } 8 | public int PageSize { get; set; } 9 | public int RecordsFiltered { get; set; } 10 | public int RecordsTotal { get; set; } 11 | 12 | 13 | 14 | /// 15 | /// Constructor for PagedResponse class. 16 | /// 17 | /// Data to be returned. 18 | /// Page number. 19 | /// Page size. 20 | /// Records count. 21 | /// 22 | /// An instance of PagedResponse. 23 | /// 24 | public PagedResponse(T data, int pageNumber, int pageSize, RecordsCount recordsCount) 25 | { 26 | this.PageNumber = pageNumber; 27 | this.PageSize = pageSize; 28 | this.RecordsFiltered = recordsCount.RecordsFiltered; 29 | this.RecordsTotal = recordsCount.RecordsTotal; 30 | this.Data = data; 31 | this.Message = null; 32 | this.Succeeded = true; 33 | this.Errors = null; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Application/Wrappers/Response.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace TalentManagementAPI.Application.Wrappers 4 | { 5 | public class Response 6 | { 7 | public Response() 8 | { 9 | } 10 | 11 | 12 | 13 | /// 14 | /// Constructor for Response object. 15 | /// 16 | /// The data to be stored in the Response object. 17 | /// Optional message to be stored in the Response object. 18 | /// A Response object with the given data and message. 19 | public Response(T data, string message = null) 20 | { 21 | Succeeded = true; 22 | Message = message; 23 | Data = data; 24 | } 25 | 26 | 27 | 28 | /// 29 | /// Constructor for Response class. 30 | /// 31 | /// The message to be set. 32 | /// 33 | /// A Response object with Succeeded set to false and Message set to the given message. 34 | /// 35 | public Response(string message) 36 | { 37 | Succeeded = false; 38 | Message = message; 39 | } 40 | 41 | public bool Succeeded { get; set; } 42 | public string Message { get; set; } 43 | public List Errors { get; set; } 44 | public T Data { get; set; } 45 | } 46 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Common/AuditableBaseEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TalentManagementAPI.Domain.Common 4 | { 5 | public abstract class AuditableBaseEntity : BaseEntity 6 | { 7 | public string CreatedBy { get; set; } 8 | public DateTime Created { get; set; } 9 | public string LastModifiedBy { get; set; } 10 | public DateTime? LastModified { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Common/BaseEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TalentManagementAPI.Domain.Common 4 | { 5 | public abstract class BaseEntity 6 | { 7 | public virtual Guid Id { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Entities/Employee.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using TalentManagementAPI.Domain.Enums; 4 | 5 | namespace TalentManagementAPI.Domain.Entities 6 | { 7 | public class Employee 8 | { 9 | public Guid Id { get; set; } 10 | [Required] 11 | [StringLength(100, MinimumLength = 2)] 12 | public string FirstName { get; set; } 13 | public string MiddleName { get; set; } 14 | [Required] 15 | [StringLength(100, MinimumLength = 2)] 16 | public string LastName { get; set; } 17 | public string EmployeeTitle { get; set; } 18 | [Required] 19 | public DateTime DOB { get; set; } 20 | [Required] 21 | [EmailAddress] 22 | public string Email { get; set; } 23 | public Gender Gender { get; set; } 24 | public string EmployeeNumber { get; set; } 25 | public string Suffix { get; set; } 26 | public string Phone { get; set; } 27 | } 28 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Entities/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Dynamic; 5 | using System.Xml; 6 | using System.Xml.Schema; 7 | using System.Xml.Serialization; 8 | 9 | namespace TalentManagementAPI.Domain.Entities 10 | { 11 | public class Entity : DynamicObject, IXmlSerializable, IDictionary 12 | { 13 | private readonly string _root = "Entity"; 14 | private readonly IDictionary _expando = null; 15 | 16 | public Entity() 17 | { 18 | _expando = new ExpandoObject(); 19 | } 20 | 21 | public override bool TryGetMember(GetMemberBinder binder, out object result) 22 | { 23 | if (_expando.TryGetValue(binder.Name, out object value)) 24 | { 25 | result = value; 26 | return true; 27 | } 28 | 29 | return base.TryGetMember(binder, out result); 30 | } 31 | 32 | public override bool TrySetMember(SetMemberBinder binder, object value) 33 | { 34 | _expando[binder.Name] = value; 35 | 36 | return true; 37 | } 38 | 39 | public XmlSchema GetSchema() 40 | { 41 | throw new NotImplementedException(); 42 | } 43 | 44 | public void ReadXml(XmlReader reader) 45 | { 46 | reader.ReadStartElement(_root); 47 | 48 | while (!reader.Name.Equals(_root)) 49 | { 50 | string typeContent; 51 | Type underlyingType; 52 | var name = reader.Name; 53 | 54 | reader.MoveToAttribute("type"); 55 | typeContent = reader.ReadContentAsString(); 56 | underlyingType = Type.GetType(typeContent); 57 | reader.MoveToContent(); 58 | _expando[name] = reader.ReadElementContentAs(underlyingType, null); 59 | } 60 | } 61 | 62 | public void WriteXml(XmlWriter writer) 63 | { 64 | foreach (var key in _expando.Keys) 65 | { 66 | var value = _expando[key]; 67 | WriteLinksToXml(key, value, writer); 68 | } 69 | } 70 | 71 | private void WriteLinksToXml(string key, object value, XmlWriter writer) 72 | { 73 | writer.WriteStartElement(key); 74 | writer.WriteString(value.ToString()); 75 | writer.WriteEndElement(); 76 | } 77 | 78 | public void Add(string key, object value) 79 | { 80 | _expando.Add(key, value); 81 | } 82 | 83 | public bool ContainsKey(string key) 84 | { 85 | return _expando.ContainsKey(key); 86 | } 87 | 88 | public ICollection Keys 89 | { 90 | get { return _expando.Keys; } 91 | } 92 | 93 | public bool Remove(string key) 94 | { 95 | return _expando.Remove(key); 96 | } 97 | 98 | public bool TryGetValue(string key, out object value) 99 | { 100 | return _expando.TryGetValue(key, out value); 101 | } 102 | 103 | public ICollection Values 104 | { 105 | get { return _expando.Values; } 106 | } 107 | 108 | public object this[string key] 109 | { 110 | get 111 | { 112 | return _expando[key]; 113 | } 114 | set 115 | { 116 | _expando[key] = value; 117 | } 118 | } 119 | 120 | public void Add(KeyValuePair item) 121 | { 122 | _expando.Add(item); 123 | } 124 | 125 | public void Clear() 126 | { 127 | _expando.Clear(); 128 | } 129 | 130 | public bool Contains(KeyValuePair item) 131 | { 132 | return _expando.Contains(item); 133 | } 134 | 135 | public void CopyTo(KeyValuePair[] array, int arrayIndex) 136 | { 137 | _expando.CopyTo(array, arrayIndex); 138 | } 139 | 140 | public int Count 141 | { 142 | get { return _expando.Count; } 143 | } 144 | 145 | public bool IsReadOnly 146 | { 147 | get { return _expando.IsReadOnly; } 148 | } 149 | 150 | public bool Remove(KeyValuePair item) 151 | { 152 | return _expando.Remove(item); 153 | } 154 | 155 | public IEnumerator> GetEnumerator() 156 | { 157 | return _expando.GetEnumerator(); 158 | } 159 | 160 | IEnumerator IEnumerable.GetEnumerator() 161 | { 162 | return GetEnumerator(); 163 | } 164 | } 165 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Entities/Position.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | using TalentManagementAPI.Domain.Common; 4 | 5 | namespace TalentManagementAPI.Domain.Entities 6 | { 7 | public class Position : AuditableBaseEntity 8 | { 9 | [Required] 10 | [StringLength(250, MinimumLength = 2)] 11 | public string PositionTitle { get; set; } 12 | [Required] 13 | [StringLength(100, MinimumLength = 2)] 14 | public string PositionNumber { get; set; } 15 | [Required] 16 | [StringLength(1000, MinimumLength = 2)] 17 | public string PositionDescription { get; set; } 18 | public string PostionArea { get; set; } 19 | [StringLength(100, MinimumLength = 2)] 20 | public string PostionType { get; set; } 21 | [Column(TypeName = "decimal(18,2)")] 22 | public decimal PositionSalary { get; set; } 23 | } 24 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Enums/Gender.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Domain.Enums 2 | { 3 | public enum Gender 4 | { 5 | Male, 6 | Female 7 | } 8 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/Settings/MailSettings.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.Domain.Settings 2 | { 3 | public class MailSettings 4 | { 5 | public string EmailFrom { get; set; } 6 | public string SmtpHost { get; set; } 7 | public int SmtpPort { get; set; } 8 | public string SmtpUser { get; set; } 9 | public string SmtpPass { get; set; } 10 | public string DisplayName { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Domain/TalentManagementAPI.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | 1.0.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Persistence/Contexts/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using Microsoft.Extensions.Logging; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Interfaces; 7 | using TalentManagementAPI.Domain.Common; 8 | using TalentManagementAPI.Domain.Entities; 9 | 10 | namespace TalentManagementAPI.Infrastructure.Persistence.Contexts 11 | { 12 | public class ApplicationDbContext : DbContext 13 | { 14 | private readonly IDateTimeService _dateTime; 15 | private readonly ILoggerFactory _loggerFactory; 16 | 17 | 18 | 19 | /// 20 | /// Constructor for ApplicationDbContext 21 | /// 22 | /// Options for the DbContext 23 | /// Service for getting the current date and time 24 | /// Factory for creating loggers 25 | /// 26 | /// An instance of ApplicationDbContext 27 | /// 28 | public ApplicationDbContext(DbContextOptions options, 29 | IDateTimeService dateTime, 30 | ILoggerFactory loggerFactory 31 | ) : base(options) 32 | { 33 | ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 34 | _dateTime = dateTime; 35 | _loggerFactory = loggerFactory; 36 | } 37 | 38 | public DbSet Positions { get; set; } 39 | 40 | 41 | 42 | /// 43 | /// Overrides the SaveChangesAsync method to set the Created and LastModified properties of entities. 44 | /// 45 | /// 46 | /// A Task that represents the asynchronous operation. 47 | /// 48 | public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) 49 | { 50 | foreach (var entry in ChangeTracker.Entries()) 51 | { 52 | switch (entry.State) 53 | { 54 | case EntityState.Added: 55 | entry.Entity.Created = _dateTime.NowUtc; 56 | break; 57 | 58 | case EntityState.Modified: 59 | entry.Entity.LastModified = _dateTime.NowUtc; 60 | break; 61 | } 62 | } 63 | return base.SaveChangesAsync(cancellationToken); 64 | } 65 | 66 | 67 | 68 | /// 69 | /// Overrides the OnModelCreating method to seed the database with mock data. 70 | /// 71 | protected override void OnModelCreating(ModelBuilder builder) 72 | { 73 | var _mockData = this.Database.GetService(); 74 | var seedPositions = _mockData.SeedPositions(1000); 75 | builder.Entity().HasData(seedPositions); 76 | 77 | base.OnModelCreating(builder); 78 | } 79 | 80 | 81 | 82 | /// 83 | /// Configures the DbContextOptionsBuilder with a LoggerFactory. 84 | /// 85 | /// The DbContextOptionsBuilder to configure. 86 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 87 | { 88 | optionsBuilder.UseLoggerFactory(_loggerFactory); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Persistence/Repositories/EmployeeRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using LinqKit; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Dynamic.Core; 5 | using System.Threading.Tasks; 6 | using TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees; 7 | using TalentManagementAPI.Application.Interfaces; 8 | using TalentManagementAPI.Application.Interfaces.Repositories; 9 | using TalentManagementAPI.Application.Parameters; 10 | using TalentManagementAPI.Domain.Entities; 11 | using TalentManagementAPI.Infrastructure.Persistence.Contexts; 12 | using TalentManagementAPI.Infrastructure.Persistence.Repository; 13 | 14 | namespace TalentManagementAPI.Infrastructure.Persistence.Repositories 15 | { 16 | public class EmployeeRepositoryAsync : GenericRepositoryAsync, IEmployeeRepositoryAsync 17 | { 18 | private readonly IDataShapeHelper _dataShaper; 19 | private readonly IMockService _mockData; 20 | 21 | 22 | 23 | /// 24 | /// Constructor for EmployeeRepositoryAsync class. 25 | /// 26 | /// ApplicationDbContext object. 27 | /// IDataShapeHelper object. 28 | /// IMockService object. 29 | /// 30 | /// 31 | /// 32 | public EmployeeRepositoryAsync(ApplicationDbContext dbContext, 33 | IDataShapeHelper dataShaper, 34 | IMockService mockData) : base(dbContext) 35 | { 36 | _dataShaper = dataShaper; 37 | _mockData = mockData; 38 | } 39 | 40 | 41 | 42 | /// 43 | /// Retrieves a paged list of employees based on the provided query parameters. 44 | /// 45 | /// The query parameters used to filter and page the data. 46 | /// A tuple containing the paged list of employees and the total number of records. 47 | public async Task<(IEnumerable data, RecordsCount recordsCount)> GetPagedEmployeeResponseAsync(GetEmployeesQuery requestParameters) 48 | { 49 | IQueryable result; 50 | 51 | var employeeTitle = requestParameters.EmployeeTitle; 52 | var lastName = requestParameters.LastName; 53 | var firstName = requestParameters.FirstName; 54 | var email = requestParameters.Email; 55 | 56 | var pageNumber = requestParameters.PageNumber; 57 | var pageSize = requestParameters.PageSize; 58 | var orderBy = requestParameters.OrderBy; 59 | var fields = requestParameters.Fields; 60 | 61 | int recordsTotal, recordsFiltered; 62 | 63 | int seedCount = 1000; 64 | 65 | result = _mockData.GetEmployees(seedCount) 66 | .AsQueryable(); 67 | 68 | // Count records total 69 | recordsTotal = result.Count(); 70 | 71 | // filter data 72 | FilterByColumn(ref result, employeeTitle, lastName, firstName, email); 73 | 74 | // Count records after filter 75 | recordsFiltered = result.Count(); 76 | 77 | //set Record counts 78 | var recordsCount = new RecordsCount 79 | { 80 | RecordsFiltered = recordsFiltered, 81 | RecordsTotal = recordsTotal 82 | }; 83 | 84 | // set order by 85 | if (!string.IsNullOrWhiteSpace(orderBy)) 86 | { 87 | result = result.OrderBy(orderBy); 88 | } 89 | 90 | //limit query fields 91 | if (!string.IsNullOrWhiteSpace(fields)) 92 | { 93 | result = result.Select("new(" + fields + ")"); 94 | } 95 | // paging 96 | result = result 97 | .Skip((pageNumber - 1) * pageSize) 98 | .Take(pageSize); 99 | 100 | 101 | // retrieve data to list 102 | // var resultData = await result.ToListAsync(); 103 | // Note: Bogus library does not support await for AsQueryable. 104 | // Workaround: fake await with Task.Run and use regular ToList 105 | var resultData = await Task.Run(() => result.ToList()); 106 | 107 | // shape data 108 | var shapeData = _dataShaper.ShapeData(resultData, fields); 109 | 110 | return (shapeData, recordsCount); 111 | } 112 | 113 | 114 | 115 | /// 116 | /// Filters an IQueryable of employees based on the provided parameters. 117 | /// 118 | /// The IQueryable of employees to filter. 119 | /// The employee title to filter by. 120 | /// The last name to filter by. 121 | /// The first name to filter by. 122 | /// The email to filter by. 123 | private void FilterByColumn(ref IQueryable employees, string employeeTitle, string lastName, string firstName, string email) 124 | { 125 | if (!employees.Any()) 126 | return; 127 | 128 | if (string.IsNullOrEmpty(employeeTitle) && string.IsNullOrEmpty(lastName) && string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(email)) 129 | return; 130 | 131 | var predicate = PredicateBuilder.New(); 132 | 133 | if (!string.IsNullOrEmpty(employeeTitle)) 134 | predicate = predicate.Or(p => p.EmployeeTitle.ToLower().Contains(employeeTitle.ToLower().Trim())); 135 | 136 | if (!string.IsNullOrEmpty(lastName)) 137 | predicate = predicate.Or(p => p.LastName.ToLower().Contains(lastName.ToLower().Trim())); 138 | 139 | if (!string.IsNullOrEmpty(firstName)) 140 | predicate = predicate.Or(p => p.FirstName.ToLower().Contains(firstName.ToLower().Trim())); 141 | 142 | if (!string.IsNullOrEmpty(email)) 143 | predicate = predicate.Or(p => p.Email.ToLower().Contains(email.ToLower().Trim())); 144 | 145 | 146 | employees = employees.Where(predicate); 147 | } 148 | } 149 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Persistence/Repositories/GenericRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using EFCore.BulkExtensions; 2 | using Microsoft.EntityFrameworkCore; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Dynamic.Core; 7 | using System.Threading.Tasks; 8 | using TalentManagementAPI.Application.Interfaces; 9 | using TalentManagementAPI.Infrastructure.Persistence.Contexts; 10 | 11 | namespace TalentManagementAPI.Infrastructure.Persistence.Repository 12 | { 13 | public class GenericRepositoryAsync : IGenericRepositoryAsync where T : class 14 | { 15 | private readonly ApplicationDbContext _dbContext; 16 | 17 | 18 | 19 | /// 20 | /// Constructor for GenericRepositoryAsync class. 21 | /// 22 | /// ApplicationDbContext object. 23 | /// 24 | /// No return value. 25 | /// 26 | public GenericRepositoryAsync(ApplicationDbContext dbContext) 27 | { 28 | _dbContext = dbContext; 29 | } 30 | 31 | 32 | 33 | /// 34 | /// Retrieves an entity with the given Id from the database. 35 | /// 36 | /// The Id of the entity to be retrieved. 37 | /// The entity with the given Id. 38 | public virtual async Task GetByIdAsync(Guid id) 39 | { 40 | return await _dbContext.Set().FindAsync(id); 41 | } 42 | 43 | 44 | 45 | /// 46 | /// Gets a paged response from the database. 47 | /// 48 | /// The page number. 49 | /// The page size. 50 | /// A list of objects. 51 | public async Task> GetPagedReponseAsync(int pageNumber, int pageSize) 52 | { 53 | return await _dbContext 54 | .Set() 55 | .Skip((pageNumber - 1) * pageSize) 56 | .Take(pageSize) 57 | .AsNoTracking() 58 | .ToListAsync(); 59 | } 60 | 61 | 62 | 63 | /// 64 | /// Retrieves a paged list of advanced responses from the database. 65 | /// 66 | /// The page number. 67 | /// The page size. 68 | /// The order by clause. 69 | /// The fields to select. 70 | /// A list of advanced responses. 71 | public async Task> GetPagedAdvancedReponseAsync(int pageNumber, int pageSize, string orderBy, string fields) 72 | { 73 | return await _dbContext 74 | .Set() 75 | .Skip((pageNumber - 1) * pageSize) 76 | .Take(pageSize) 77 | .Select("new(" + fields + ")") 78 | .OrderBy(orderBy) 79 | .AsNoTracking() 80 | .ToListAsync(); 81 | } 82 | 83 | 84 | 85 | /// 86 | /// Adds an entity to the database asynchronously. 87 | /// 88 | /// The entity to be added. 89 | /// The entity that was added. 90 | public async Task AddAsync(T entity) 91 | { 92 | await _dbContext.Set().AddAsync(entity); 93 | await _dbContext.SaveChangesAsync(); 94 | return entity; 95 | } 96 | 97 | 98 | 99 | /// 100 | /// Asynchronously bulk inserts a list of entities into the database. 101 | /// 102 | /// The list of entities to be inserted. 103 | /// A task that represents the asynchronous operation. 104 | public async Task BulkInsertAsync(IList entity) 105 | { 106 | await _dbContext.BulkInsertAsync(entity); 107 | } 108 | 109 | 110 | 111 | 112 | /// 113 | /// Updates an entity in the database. 114 | /// 115 | /// The entity to be updated. 116 | /// A task that represents the asynchronous operation. 117 | public async Task UpdateAsync(T entity) 118 | { 119 | _dbContext.Entry(entity).State = EntityState.Modified; 120 | await _dbContext.SaveChangesAsync(); 121 | } 122 | 123 | 124 | 125 | /// 126 | /// Asynchronously deletes an entity from the database. 127 | /// 128 | /// The entity to delete. 129 | /// A task that represents the asynchronous delete operation. 130 | public async Task DeleteAsync(T entity) 131 | { 132 | _dbContext.Set().Remove(entity); 133 | await _dbContext.SaveChangesAsync(); 134 | } 135 | 136 | 137 | 138 | /// 139 | /// Retrieves a list of all entities from the database. 140 | /// 141 | /// A list of all entities. 142 | public async Task> GetAllAsync() 143 | { 144 | return await _dbContext 145 | .Set() 146 | .ToListAsync(); 147 | } 148 | } 149 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Persistence/Repositories/PositionRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using LinqKit; 2 | using Microsoft.EntityFrameworkCore; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Dynamic.Core; 6 | using System.Threading.Tasks; 7 | using TalentManagementAPI.Application.Features.Positions.Queries.GetPositions; 8 | using TalentManagementAPI.Application.Interfaces; 9 | using TalentManagementAPI.Application.Interfaces.Repositories; 10 | using TalentManagementAPI.Application.Parameters; 11 | using TalentManagementAPI.Domain.Entities; 12 | using TalentManagementAPI.Infrastructure.Persistence.Contexts; 13 | using TalentManagementAPI.Infrastructure.Persistence.Repository; 14 | 15 | namespace TalentManagementAPI.Infrastructure.Persistence.Repositories 16 | { 17 | public class PositionRepositoryAsync : GenericRepositoryAsync, IPositionRepositoryAsync 18 | { 19 | private readonly DbSet _positions; 20 | private readonly IDataShapeHelper _dataShaper; 21 | private readonly IMockService _mockData; 22 | 23 | 24 | 25 | /// 26 | /// Constructor for PositionRepositoryAsync class. 27 | /// 28 | /// ApplicationDbContext object. 29 | /// IDataShapeHelper object. 30 | /// IMockService object. 31 | /// 32 | /// PositionRepositoryAsync object. 33 | /// 34 | public PositionRepositoryAsync(ApplicationDbContext dbContext, 35 | IDataShapeHelper dataShaper, IMockService mockData) : base(dbContext) 36 | { 37 | _positions = dbContext.Set(); 38 | _dataShaper = dataShaper; 39 | _mockData = mockData; 40 | } 41 | 42 | 43 | 44 | /// 45 | /// Checks if the given position number is unique. 46 | /// 47 | /// The position number to check. 48 | /// A boolean indicating if the position number is unique. 49 | public async Task IsUniquePositionNumberAsync(string positionNumber) 50 | { 51 | return await _positions 52 | .AllAsync(p => p.PositionNumber != positionNumber); 53 | } 54 | 55 | 56 | 57 | /// 58 | /// Seeds the data asynchronously. 59 | /// 60 | /// The row count. 61 | /// A representing the asynchronous operation. 62 | public async Task SeedDataAsync(int rowCount) 63 | { 64 | await this.BulkInsertAsync(_mockData.GetPositions(rowCount)); 65 | } 66 | 67 | 68 | 69 | /// 70 | /// Retrieves a paged response of positions based on the given query parameters. 71 | /// 72 | /// The query parameters used to filter and page the response. 73 | /// A tuple containing the paged response of positions and the total number of records. 74 | public async Task<(IEnumerable data, RecordsCount recordsCount)> GetPagedPositionReponseAsync(GetPositionsQuery requestParameters) 75 | { 76 | var positionNumber = requestParameters.PositionNumber; 77 | var positionTitle = requestParameters.PositionTitle; 78 | var positionDescription = requestParameters.PositionDescription; 79 | 80 | var pageNumber = requestParameters.PageNumber; 81 | var pageSize = requestParameters.PageSize; 82 | var orderBy = requestParameters.OrderBy; 83 | var fields = requestParameters.Fields; 84 | 85 | int recordsTotal, recordsFiltered; 86 | 87 | // Setup IQueryable 88 | var result = _positions 89 | .AsNoTracking() 90 | .AsExpandable(); 91 | 92 | // Count records total 93 | recordsTotal = await result.CountAsync(); 94 | 95 | // filter data 96 | FilterByColumn(ref result, positionNumber, positionTitle, positionDescription); 97 | 98 | // Count records after filter 99 | recordsFiltered = await result.CountAsync(); 100 | 101 | //set Record counts 102 | var recordsCount = new RecordsCount 103 | { 104 | RecordsFiltered = recordsFiltered, 105 | RecordsTotal = recordsTotal 106 | }; 107 | 108 | // set order by 109 | if (!string.IsNullOrWhiteSpace(orderBy)) 110 | { 111 | result = result.OrderBy(orderBy); 112 | } 113 | 114 | // select columns 115 | if (!string.IsNullOrWhiteSpace(fields)) 116 | { 117 | result = result.Select("new(" + fields + ")"); 118 | } 119 | // paging 120 | result = result 121 | .Skip((pageNumber - 1) * pageSize) 122 | .Take(pageSize); 123 | 124 | // retrieve data to list 125 | var resultData = await result.ToListAsync(); 126 | // shape data 127 | var shapeData = _dataShaper.ShapeData(resultData, fields); 128 | 129 | return (shapeData, recordsCount); 130 | } 131 | 132 | 133 | 134 | /// 135 | /// Filters a given IQueryable by position number, title, and description. 136 | /// 137 | private void FilterByColumn(ref IQueryable positions, string positionNumber, string positionTitle, string positionDescription) 138 | { 139 | if (!positions.Any()) 140 | return; 141 | 142 | if (string.IsNullOrEmpty(positionTitle) && string.IsNullOrEmpty(positionNumber) && string.IsNullOrEmpty(positionDescription)) 143 | return; 144 | 145 | var predicate = PredicateBuilder.New(); 146 | 147 | if (!string.IsNullOrEmpty(positionNumber)) 148 | predicate = predicate.Or(p => p.PositionNumber.ToLower().Contains(positionNumber.ToLower().Trim())); 149 | 150 | if (!string.IsNullOrEmpty(positionTitle)) 151 | predicate = predicate.Or(p => p.PositionTitle.ToLower().Contains(positionTitle.ToLower().Trim())); 152 | 153 | if (!string.IsNullOrEmpty(positionDescription)) 154 | predicate = predicate.Or(p => p.PositionDescription.ToLower().Contains(positionDescription.ToLower().Trim())); 155 | 156 | 157 | positions = positions.Where(predicate); 158 | } 159 | } 160 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Persistence/ServiceRegistration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using TalentManagementAPI.Application.Interfaces; 5 | using TalentManagementAPI.Application.Interfaces.Repositories; 6 | using TalentManagementAPI.Infrastructure.Persistence.Contexts; 7 | using TalentManagementAPI.Infrastructure.Persistence.Repositories; 8 | using TalentManagementAPI.Infrastructure.Persistence.Repository; 9 | 10 | namespace TalentManagementAPI.Infrastructure.Persistence 11 | { 12 | public static class ServiceRegistration 13 | { 14 | public static void AddPersistenceInfrastructure(this IServiceCollection services, IConfiguration configuration) 15 | { 16 | if (configuration.GetValue("UseInMemoryDatabase")) 17 | { 18 | services.AddDbContext(options => 19 | options.UseInMemoryDatabase("ApplicationDb")); 20 | } 21 | else 22 | { 23 | services.AddDbContext(options => 24 | options.UseSqlServer( 25 | configuration.GetConnectionString("DefaultConnection"), 26 | b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName))); 27 | } 28 | 29 | #region Repositories 30 | 31 | services.AddTransient(typeof(IGenericRepositoryAsync<>), typeof(GenericRepositoryAsync<>)); 32 | services.AddTransient(); 33 | services.AddTransient(); 34 | 35 | #endregion Repositories 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Persistence/TalentManagementAPI.Infrastructure.Persistence.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | 1.0.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/Mock/EmployeeBogusConfig.cs: -------------------------------------------------------------------------------- 1 | using AutoBogus; 2 | using Bogus; 3 | using System; 4 | using TalentManagementAPI.Domain.Entities; 5 | using TalentManagementAPI.Domain.Enums; 6 | 7 | namespace TalentManagementAPI.Infrastructure.Shared.Mock 8 | { 9 | public class EmployeeBogusConfig : AutoFaker 10 | { 11 | public EmployeeBogusConfig() 12 | { 13 | Randomizer.Seed = new Random(8675309); 14 | RuleFor(p => p.Id, f => Guid.NewGuid()); 15 | RuleFor(p => p.FirstName, f => f.Name.FirstName()); 16 | RuleFor(p => p.MiddleName, f => f.Name.FirstName()); 17 | RuleFor(p => p.LastName, f => f.Name.LastName()); 18 | RuleFor(p => p.EmployeeTitle, f => f.Name.JobTitle()); 19 | RuleFor(p => p.Suffix, f => f.Name.Suffix()); 20 | RuleFor(p => p.Email, (f, p) => f.Internet.Email(p.FirstName, p.LastName)); 21 | RuleFor(p => p.DOB, f => f.Date.Past(18)); 22 | RuleFor(p => p.Gender, f => f.PickRandom()); 23 | RuleFor(p => p.EmployeeNumber, f => f.Commerce.Ean13()); 24 | RuleFor(p => p.Phone, f => f.Phone.PhoneNumber("(###)-###-####")); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/Mock/PositionInsertBogusConfig.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using System; 3 | using TalentManagementAPI.Domain.Entities; 4 | 5 | namespace TalentManagementAPI.Infrastructure.Shared.Mock 6 | { 7 | public class PositionInsertBogusConfig : Faker 8 | { 9 | public PositionInsertBogusConfig() 10 | { 11 | RuleFor(o => o.Id, f => Guid.NewGuid()); 12 | RuleFor(o => o.PositionTitle, f => f.Name.JobTitle()); 13 | RuleFor(o => o.PositionNumber, f => f.Commerce.Ean13()); 14 | RuleFor(o => o.PositionDescription, f => f.Name.JobDescriptor()); 15 | RuleFor(o => o.PositionSalary, f => f.Finance.Amount()); 16 | RuleFor(o => o.Created, f => f.Date.Past(1)); 17 | RuleFor(o => o.CreatedBy, f => f.Name.FullName()); 18 | RuleFor(o => o.LastModified, f => f.Date.Recent(1)); 19 | RuleFor(o => o.LastModifiedBy, f => f.Name.FullName()); 20 | 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/Mock/PositionSeedBogusConfig.cs: -------------------------------------------------------------------------------- 1 | using AutoBogus; 2 | using Bogus; 3 | using System; 4 | using TalentManagementAPI.Domain.Entities; 5 | 6 | namespace TalentManagementAPI.Infrastructure.Shared.Mock 7 | { 8 | public class PositionSeedBogusConfig : AutoFaker 9 | { 10 | public PositionSeedBogusConfig() 11 | { 12 | Randomizer.Seed = new Random(8675309); 13 | RuleFor(o => o.Id, f => Guid.NewGuid()); 14 | RuleFor(o => o.PositionTitle, f => f.Name.JobTitle()); 15 | RuleFor(o => o.PositionNumber, f => f.Commerce.Ean13()); 16 | RuleFor(o => o.PositionDescription, f => f.Name.JobDescriptor()); 17 | RuleFor(o => o.PositionSalary, f => f.Finance.Amount()); 18 | RuleFor(o => o.Created, f => f.Date.Past(1)); 19 | RuleFor(o => o.CreatedBy, f => f.Name.FullName()); 20 | RuleFor(o => o.LastModified, f => f.Date.Recent(1)); 21 | RuleFor(o => o.LastModifiedBy, f => f.Name.FullName()); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/ServiceRegistration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TalentManagementAPI.Application.Interfaces; 4 | using TalentManagementAPI.Domain.Settings; 5 | using TalentManagementAPI.Infrastructure.Shared.Services; 6 | 7 | namespace TalentManagementAPI.Infrastructure.Shared 8 | { 9 | public static class ServiceRegistration 10 | { 11 | public static void AddSharedInfrastructure(this IServiceCollection services, IConfiguration _config) 12 | { 13 | services.Configure(_config.GetSection("MailSettings")); 14 | services.AddTransient(); 15 | services.AddTransient(); 16 | services.AddTransient(); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/Services/DateTimeService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using TalentManagementAPI.Application.Interfaces; 3 | 4 | namespace TalentManagementAPI.Infrastructure.Shared.Services 5 | { 6 | public class DateTimeService : IDateTimeService 7 | { 8 | public DateTime NowUtc => DateTime.UtcNow; 9 | } 10 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/Services/EmailService.cs: -------------------------------------------------------------------------------- 1 | using MailKit.Net.Smtp; 2 | using MailKit.Security; 3 | using Microsoft.Extensions.Logging; 4 | using Microsoft.Extensions.Options; 5 | using MimeKit; 6 | using System.Threading.Tasks; 7 | using TalentManagementAPI.Application.DTOs.Email; 8 | using TalentManagementAPI.Application.Exceptions; 9 | using TalentManagementAPI.Application.Interfaces; 10 | using TalentManagementAPI.Domain.Settings; 11 | 12 | namespace TalentManagementAPI.Infrastructure.Shared.Services 13 | { 14 | public class EmailService : IEmailService 15 | { 16 | public MailSettings _mailSettings { get; } 17 | public ILogger _logger { get; } 18 | 19 | public EmailService(IOptions mailSettings, ILogger logger) 20 | { 21 | _mailSettings = mailSettings.Value; 22 | _logger = logger; 23 | } 24 | 25 | public async Task SendAsync(EmailRequest request) 26 | { 27 | try 28 | { 29 | // create message 30 | var email = new MimeMessage(); 31 | email.Sender = MailboxAddress.Parse(request.From ?? _mailSettings.EmailFrom); 32 | email.To.Add(MailboxAddress.Parse(request.To)); 33 | email.Subject = request.Subject; 34 | var builder = new BodyBuilder(); 35 | builder.HtmlBody = request.Body; 36 | email.Body = builder.ToMessageBody(); 37 | using var smtp = new SmtpClient(); 38 | smtp.Connect(_mailSettings.SmtpHost, _mailSettings.SmtpPort, SecureSocketOptions.StartTls); 39 | smtp.Authenticate(_mailSettings.SmtpUser, _mailSettings.SmtpPass); 40 | await smtp.SendAsync(email); 41 | smtp.Disconnect(true); 42 | } 43 | catch (System.Exception ex) 44 | { 45 | _logger.LogError(ex.Message, ex); 46 | throw new ApiException(ex.Message); 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/Services/MockService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using TalentManagementAPI.Application.Interfaces; 3 | using TalentManagementAPI.Domain.Entities; 4 | using TalentManagementAPI.Infrastructure.Shared.Mock; 5 | 6 | namespace TalentManagementAPI.Infrastructure.Shared.Services 7 | { 8 | public class MockService : IMockService 9 | { 10 | 11 | 12 | /// 13 | /// Generates a list of positions using the PositionInsertBogusConfig class. 14 | /// 15 | /// The number of positions to generate. 16 | /// A list of generated positions. 17 | public List GetPositions(int rowCount) 18 | { 19 | var faker = new PositionInsertBogusConfig(); 20 | return faker.Generate(rowCount); 21 | } 22 | 23 | 24 | 25 | /// 26 | /// Gets a list of Employees using the EmployeeBogusConfig class. 27 | /// 28 | /// The number of Employees to generate. 29 | /// A list of Employees. 30 | public List GetEmployees(int rowCount) 31 | { 32 | var faker = new EmployeeBogusConfig(); 33 | return faker.Generate(rowCount); 34 | } 35 | 36 | 37 | 38 | /// 39 | /// Generates a list of seed positions using the PositionSeedBogusConfig class. 40 | /// 41 | /// The number of seed positions to generate. 42 | /// A list of seed positions. 43 | public List SeedPositions(int rowCount) 44 | { 45 | var faker = new PositionSeedBogusConfig(); 46 | return faker.Generate(rowCount); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.Infrastructure.Shared/TalentManagementAPI.Infrastructure.Shared.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | 1.0.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Apiresources.WebApi.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TalentManagementAPI.WebApi 5 | 6 | 7 | 8 | 9 | GET: api/controller 10 | 11 | 12 | 13 | 14 | 15 | 16 | GET: api/controller 17 | 18 | 19 | 20 | 21 | 22 | 23 | GET api/controller/5 24 | 25 | 26 | 27 | 28 | 29 | 30 | POST api/controller 31 | 32 | 33 | 34 | 35 | 36 | 37 | Bulk insert fake data by specifying number of rows 38 | 39 | 40 | 41 | 42 | 43 | 44 | Support Ngx-DataTables https://medium.com/scrum-and-coke/angular-11-pagination-of-zillion-rows-45d8533538c0 45 | 46 | 47 | 48 | 49 | 50 | 51 | PUT api/controller/5 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | DELETE api/controller/5 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Controllers/BaseApiController.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace TalentManagementAPI.WebApi.Controllers 6 | { 7 | [ApiController] 8 | [Route("api/v{version:apiVersion}/[controller]")] 9 | public abstract class BaseApiController : ControllerBase 10 | { 11 | private IMediator _mediator; 12 | protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService(); 13 | } 14 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Controllers/MetaController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Diagnostics; 3 | 4 | namespace TalentManagementAPI.WebApi.Controllers 5 | { 6 | public class MetaController : BaseApiController 7 | { 8 | [HttpGet("/info")] 9 | public ActionResult Info() 10 | { 11 | var assembly = typeof(Program).Assembly; 12 | 13 | var lastUpdate = System.IO.File.GetLastWriteTime(assembly.Location); 14 | var version = FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion; 15 | 16 | return Ok($"Version: {version}, Last Updated: {lastUpdate}"); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Controllers/v1/EmployeesController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Threading.Tasks; 3 | using TalentManagementAPI.Application.Features.Employees.Queries.GetEmployees; 4 | 5 | // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 6 | 7 | namespace TalentManagementAPI.WebApi.Controllers.v1 8 | { 9 | [ApiVersion("1.0")] 10 | public class EmployeesController : BaseApiController 11 | { 12 | 13 | /// 14 | /// Gets a list of employees based on the specified filter. 15 | /// 16 | /// The filter used to get the list of employees. 17 | /// A list of employees. 18 | [HttpGet] 19 | public async Task Get([FromQuery] GetEmployeesQuery filter) 20 | { 21 | return Ok(await Mediator.Send(filter)); 22 | } 23 | 24 | /// 25 | /// Retrieves a paged list of employees. 26 | /// Support Ngx-DataTables https://medium.com/scrum-and-coke/angular-11-pagination-of-zillion-rows-45d8533538c0 27 | /// 28 | /// The query parameters for the paged list. 29 | /// A paged list of employees. 30 | [HttpPost] 31 | [Route("Paged")] 32 | public async Task Paged(PagedEmployeesQuery query) 33 | { 34 | return Ok(await Mediator.Send(query)); 35 | } 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Controllers/v1/PositionsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Diagnostics; 6 | using System.Security.Claims; 7 | using System.Threading.Tasks; 8 | using TalentManagementAPI.Application.Features.Positions.Commands.CreatePosition; 9 | using TalentManagementAPI.Application.Features.Positions.Commands.DeletePositionById; 10 | using TalentManagementAPI.Application.Features.Positions.Commands.UpdatePosition; 11 | using TalentManagementAPI.Application.Features.Positions.Queries.GetPositionById; 12 | using TalentManagementAPI.Application.Features.Positions.Queries.GetPositions; 13 | using TalentManagementAPI.WebApi.Extensions; 14 | 15 | // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 16 | 17 | namespace TalentManagementAPI.WebApi.Controllers.v1 18 | { 19 | [ApiVersion("1.0")] 20 | public class PositionsController : BaseApiController 21 | { 22 | 23 | /// 24 | /// Gets a list of positions based on the provided filter. 25 | /// 26 | /// The filter used to query the positions. 27 | /// A list of positions. 28 | [HttpGet] 29 | public async Task Get([FromQuery] GetPositionsQuery filter) 30 | { 31 | return Ok(await Mediator.Send(filter)); 32 | } 33 | 34 | /// 35 | /// Gets a position by its Id. 36 | /// 37 | /// The Id of the position. 38 | /// The position with the specified Id. 39 | [HttpGet("{id}")] 40 | [Authorize] 41 | public async Task Get(Guid id) 42 | { 43 | return Ok(await Mediator.Send(new GetPositionByIdQuery { Id = id })); 44 | } 45 | 46 | /// 47 | /// Creates a new position. 48 | /// 49 | /// The command containing the data for the new position. 50 | /// A 201 Created response containing the newly created position. 51 | [HttpPost] 52 | [Authorize] 53 | [ProducesResponseType(StatusCodes.Status201Created)] 54 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 55 | public async Task Post(CreatePositionCommand command) 56 | { 57 | var resp = await Mediator.Send(command); 58 | return CreatedAtAction(nameof(Post), resp); 59 | } 60 | 61 | /// 62 | /// Sends an InsertMockPositionCommand to the mediator. 63 | /// 64 | /// The command to be sent. 65 | /// The result of the command. 66 | [HttpPost] 67 | [Route("AddMock")] 68 | //[Authorize] 69 | public async Task AddMock(InsertMockPositionCommand command) 70 | { 71 | return Ok(await Mediator.Send(command)); 72 | } 73 | 74 | /// 75 | /// Retrieves a paged list of positions. 76 | /// 77 | /// The query parameters for the paged list. 78 | /// A paged list of positions. 79 | [HttpPost] 80 | [Authorize] 81 | [Route("Paged")] 82 | public async Task Paged(PagedPositionsQuery query) 83 | { 84 | // debug 85 | var user = HttpContext?.User!; 86 | var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value; 87 | var name = User.FindFirst("name")?.Value; 88 | 89 | // print debug information to the console 90 | Debug.WriteLine($"User ID: {userId}"); 91 | Debug.WriteLine($"Name: {name}"); 92 | 93 | 94 | return Ok(await Mediator.Send(query)); 95 | } 96 | 97 | /// 98 | /// Updates a position with the given id using the provided command. 99 | /// 100 | /// The id of the position to update. 101 | /// The command containing the updated information. 102 | /// The updated position. 103 | [HttpPut("{id}")] 104 | [Authorize(Policy = AuthorizationConsts.AdminPolicy)] 105 | public async Task Put(Guid id, UpdatePositionCommand command) 106 | { 107 | if (id != command.Id) 108 | { 109 | return BadRequest(); 110 | } 111 | return Ok(await Mediator.Send(command)); 112 | } 113 | 114 | /// 115 | /// Deletes a position by its Id. 116 | /// 117 | /// The Id of the position to delete. 118 | /// The result of the deletion. 119 | [HttpDelete("{id}")] 120 | [Authorize(Policy = AuthorizationConsts.AdminPolicy)] 121 | public async Task Delete(Guid id) 122 | { 123 | return Ok(await Mediator.Send(new DeletePositionByIdCommand { Id = id })); 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Extensions/AppExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using TalentManagementAPI.WebApi.Middlewares; 3 | 4 | namespace TalentManagementAPI.WebApi.Extensions 5 | { 6 | public static class AppExtensions 7 | { 8 | public static void UseSwaggerExtension(this IApplicationBuilder app) 9 | { 10 | app.UseSwagger(); 11 | app.UseSwaggerUI(c => 12 | { 13 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "CleanArchitecture.TalentManagementAPI.WebApi"); 14 | }); 15 | } 16 | 17 | public static void UseErrorHandlingMiddleware(this IApplicationBuilder app) 18 | { 19 | app.UseMiddleware(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Extensions/AuthorizationConsts.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagementAPI.WebApi.Extensions 3 | { 4 | public class AuthorizationConsts 5 | { 6 | public const string AdminPolicy = "AdminPolicy"; 7 | public const string ManagerPolicy = "ManagerPolicy"; 8 | public const string EmployeePolicy = "EmployeePolicy"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Extensions/ServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using IdentityModel; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.OpenApi.Models; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Security.Claims; 10 | using System.Text.Json; 11 | 12 | namespace TalentManagementAPI.WebApi.Extensions 13 | { 14 | public static class ServiceExtensions 15 | { 16 | 17 | public static void AddSwaggerExtension(this IServiceCollection services) 18 | { 19 | services.AddSwaggerGen(c => 20 | { 21 | c.SwaggerDoc("v1", new OpenApiInfo 22 | { 23 | Version = "v1", 24 | Title = "Clean Architecture - TalentManagementAPI", 25 | Description = "This Api will be responsible for overall data distribution and authorization.", 26 | Contact = new OpenApiContact 27 | { 28 | Name = "Jane Doe", 29 | Email = "jdoe@janedoe.com", 30 | Url = new Uri("https://janedoe.com/contact"), 31 | } 32 | }); 33 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 34 | { 35 | Name = "Authorization", 36 | In = ParameterLocation.Header, 37 | Type = SecuritySchemeType.ApiKey, 38 | Scheme = "Bearer", 39 | BearerFormat = "JWT", 40 | Description = "Input your Bearer token in this format - Bearer {your token here} to access this API", 41 | }); 42 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 43 | { 44 | { 45 | new OpenApiSecurityScheme 46 | { 47 | Reference = new OpenApiReference 48 | { 49 | Type = ReferenceType.SecurityScheme, 50 | Id = "Bearer", 51 | }, 52 | Scheme = "Bearer", 53 | Name = "Bearer", 54 | In = ParameterLocation.Header, 55 | }, new List() 56 | }, 57 | }); 58 | }); 59 | } 60 | 61 | public static void AddControllersExtension(this IServiceCollection services) 62 | { 63 | services.AddControllers() 64 | .AddJsonOptions(options => 65 | { 66 | options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase; 67 | options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; 68 | }) 69 | ; 70 | } 71 | 72 | //Configure CORS to allow any origin, header and method. 73 | //Change the CORS policy based on your requirements. 74 | //More info see: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.0 75 | 76 | public static void AddCorsExtension(this IServiceCollection services) 77 | { 78 | services.AddCors(options => 79 | { 80 | options.AddPolicy("AllowAll", 81 | builder => 82 | { 83 | builder.AllowAnyOrigin() 84 | .AllowAnyHeader() 85 | .AllowAnyMethod(); 86 | }); 87 | }); 88 | } 89 | 90 | 91 | public static void AddVersionedApiExplorerExtension(this IServiceCollection services) 92 | { 93 | services.AddVersionedApiExplorer(o => 94 | { 95 | o.GroupNameFormat = "'v'VVV"; 96 | o.SubstituteApiVersionInUrl = true; 97 | }); 98 | } 99 | public static void AddApiVersioningExtension(this IServiceCollection services) 100 | { 101 | services.AddApiVersioning(config => 102 | { 103 | // Specify the default API Version as 1.0 104 | config.DefaultApiVersion = new ApiVersion(1, 0); 105 | // If the client hasn't specified the API version in the request, use the default API version number 106 | config.AssumeDefaultVersionWhenUnspecified = true; 107 | // Advertise the API versions supported for the particular endpoint 108 | config.ReportApiVersions = true; 109 | }); 110 | } 111 | public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration) 112 | { 113 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 114 | .AddJwtBearer(options => 115 | { 116 | options.RequireHttpsMetadata = false; 117 | options.Authority = configuration["Sts:ServerUrl"]; 118 | options.Audience = configuration["Sts:Audience"]; 119 | }); 120 | } 121 | public static void AddAuthorizationPolicies(this IServiceCollection services, IConfiguration configuration) 122 | { 123 | string admin = configuration["ApiRoles:AdminRole"], 124 | manager = configuration["ApiRoles:ManagerRole"], employee = configuration["ApiRoles:EmployeeRole"]; 125 | 126 | services.AddAuthorization(options => 127 | { 128 | options.AddPolicy(AuthorizationConsts.AdminPolicy, policy => policy.RequireRole(admin)); 129 | options.AddPolicy(AuthorizationConsts.ManagerPolicy, policy => policy.RequireRole(manager, admin)); 130 | options.AddPolicy(AuthorizationConsts.EmployeePolicy, policy => policy.RequireRole(employee, manager, admin)); 131 | }); 132 | } 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Middlewares/ErrorHandlerMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | using TalentManagementAPI.Application.Exceptions; 9 | using TalentManagementAPI.Application.Wrappers; 10 | 11 | namespace TalentManagementAPI.WebApi.Middlewares 12 | { 13 | public class ErrorHandlerMiddleware 14 | { 15 | private readonly RequestDelegate _next; 16 | private readonly ILogger _logger; 17 | 18 | public ErrorHandlerMiddleware(RequestDelegate next, ILogger logger) 19 | { 20 | _next = next; 21 | _logger = logger; 22 | } 23 | 24 | public async Task Invoke(HttpContext context) 25 | { 26 | try 27 | { 28 | await _next(context); 29 | } 30 | catch (Exception error) 31 | { 32 | var response = context.Response; 33 | response.ContentType = "application/json"; 34 | var responseModel = new Response() { Succeeded = false, Message = error?.Message }; 35 | 36 | switch (error) 37 | { 38 | case ApiException: 39 | // custom application error 40 | response.StatusCode = (int)HttpStatusCode.BadRequest; 41 | break; 42 | 43 | case ValidationException e: 44 | // custom application error 45 | response.StatusCode = (int)HttpStatusCode.BadRequest; 46 | responseModel.Errors = e.Errors; 47 | break; 48 | 49 | case KeyNotFoundException: 50 | // not found error 51 | response.StatusCode = (int)HttpStatusCode.NotFound; 52 | break; 53 | 54 | default: 55 | // unhandled error 56 | response.StatusCode = (int)HttpStatusCode.InternalServerError; 57 | break; 58 | } 59 | // use ILogger to log the exception message 60 | _logger.LogError(error.Message); 61 | 62 | var result = JsonSerializer.Serialize(responseModel); 63 | 64 | await response.WriteAsync(result); 65 | } 66 | } 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Models/Metadata.cs: -------------------------------------------------------------------------------- 1 | namespace TalentManagementAPI.WebApi.Models 2 | { 3 | public class Metadata 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using Serilog; 7 | using System; 8 | using TalentManagementAPI.Application; 9 | using TalentManagementAPI.Infrastructure.Persistence; 10 | using TalentManagementAPI.Infrastructure.Persistence.Contexts; 11 | using TalentManagementAPI.Infrastructure.Shared; 12 | using TalentManagementAPI.WebApi.Extensions; 13 | 14 | try 15 | { 16 | var builder = WebApplication.CreateBuilder(args); 17 | // load up serilog configuraton 18 | Log.Logger = new LoggerConfiguration() 19 | .ReadFrom.Configuration(builder.Configuration) 20 | .Enrich.FromLogContext() 21 | .CreateLogger(); 22 | builder.Host.UseSerilog(Log.Logger); 23 | builder.Services.AddApplicationLayer(); 24 | builder.Services.AddPersistenceInfrastructure(builder.Configuration); 25 | builder.Services.AddSharedInfrastructure(builder.Configuration); 26 | builder.Services.AddSwaggerExtension(); 27 | builder.Services.AddControllersExtension(); 28 | // CORS 29 | builder.Services.AddCorsExtension(); 30 | // Health check 31 | builder.Services.AddHealthChecks() 32 | .AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")) 33 | .AddDbContextCheck(); 34 | // API Security 35 | builder.Services.AddJWTAuthentication(builder.Configuration); 36 | builder.Services.AddAuthorizationPolicies(builder.Configuration); 37 | // API version 38 | builder.Services.AddApiVersioningExtension(); 39 | // API explorer 40 | builder.Services.AddMvcCore() 41 | .AddApiExplorer(); 42 | // API explorer version 43 | builder.Services.AddVersionedApiExplorerExtension(); 44 | var app = builder.Build(); 45 | if (app.Environment.IsDevelopment()) 46 | { 47 | app.UseDeveloperExceptionPage(); 48 | } 49 | else 50 | { 51 | app.UseExceptionHandler("/Error"); 52 | app.UseHsts(); 53 | } 54 | 55 | using (var scope = app.Services.CreateScope()) 56 | { 57 | var services = scope.ServiceProvider; 58 | var dbContext = services.GetRequiredService(); 59 | // use context 60 | // For fast prototype, use dbContext.Database.EnsureCreated() 61 | dbContext.Database.EnsureCreated(); 62 | // To automate migration on startup, use dbContext.Database.Migrate(); 63 | // dbContext.Database.Migrate(); 64 | } 65 | 66 | 67 | // Add this line; you'll need `using Serilog;` up the top, too 68 | app.UseSerilogRequestLogging(); 69 | app.UseHttpsRedirection(); 70 | app.UseRouting(); 71 | //Enable CORS 72 | app.UseCors("AllowAll"); 73 | app.UseAuthentication(); 74 | app.UseAuthorization(); 75 | app.UseSwaggerExtension(); 76 | app.UseErrorHandlingMiddleware(); 77 | app.MapHealthChecks("/health"); 78 | app.MapControllers(); 79 | app.Run(); 80 | 81 | Log.Information("Application Starting"); 82 | 83 | } 84 | catch (Exception ex) 85 | { 86 | Log.Warning(ex, "An error occurred starting the application"); 87 | } 88 | finally 89 | { 90 | Log.CloseAndFlush(); 91 | } 92 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:57712", 7 | "sslPort": 44378 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | }, 19 | "sqlDebugging": false, 20 | "nativeDebugging": false 21 | }, 22 | "TalentManagementAPI.WebApi": { 23 | "commandName": "Project", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | }, 29 | "applicationUrl": "https://localhost:9001;http://localhost:5000" 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/TalentManagementAPI.WebApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | Fuji Nguyen 6 | workcontrolgit 7 | https://github.com/workcontrolgit 8 | Public 9 | https://github.com/workcontrolgit 10 | 1.0.0 11 | 12 | 13 | 14 | TalentManagementAPI.WebApi.xml 15 | 1701;1702;1591 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | all 32 | runtime; build; native; contentfiles; analyzers; buildtransitive 33 | 34 | 35 | all 36 | runtime; build; native; contentfiles; analyzers; buildtransitive 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/TalentManagementAPI.WebApi.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TalentManagementAPI.WebApi 5 | 6 | 7 | 8 | 9 | Gets a list of employees based on the specified filter. 10 | 11 | The filter used to get the list of employees. 12 | A list of employees. 13 | 14 | 15 | 16 | Retrieves a paged list of employees. 17 | Support Ngx-DataTables https://medium.com/scrum-and-coke/angular-11-pagination-of-zillion-rows-45d8533538c0 18 | 19 | The query parameters for the paged list. 20 | A paged list of employees. 21 | 22 | 23 | 24 | Gets a list of positions based on the provided filter. 25 | 26 | The filter used to query the positions. 27 | A list of positions. 28 | 29 | 30 | 31 | Gets a position by its Id. 32 | 33 | The Id of the position. 34 | The position with the specified Id. 35 | 36 | 37 | 38 | Creates a new position. 39 | 40 | The command containing the data for the new position. 41 | A 201 Created response containing the newly created position. 42 | 43 | 44 | 45 | Sends an InsertMockPositionCommand to the mediator. 46 | 47 | The command to be sent. 48 | The result of the command. 49 | 50 | 51 | 52 | Retrieves a paged list of positions. 53 | 54 | The query parameters for the paged list. 55 | A paged list of positions. 56 | 57 | 58 | 59 | Updates a position with the given id using the provided command. 60 | 61 | The id of the position to update. 62 | The command containing the updated information. 63 | The updated position. 64 | 65 | 66 | 67 | Deletes a position by its Id. 68 | 69 | The Id of the position to delete. 70 | The result of the deletion. 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "MailSettings": { 3 | "EmailFrom": "info@codewithmukesh.com", 4 | "SmtpHost": "smtp.ethereal.email", 5 | "SmtpPort": 587, 6 | "SmtpUser": "doyle.sauer@ethereal.email", 7 | "SmtpPass": "6X4wBQQYgU14F23VYc", 8 | "DisplayName": "Mukesh Murugan" 9 | } 10 | } -------------------------------------------------------------------------------- /TalentManagementAPI/TalentManagementAPI.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "Microsoft.EntityFrameworkCore.Database.Command": "Information" 6 | } 7 | }, 8 | "UseInMemoryDatabase": false, 9 | "ConnectionStrings": { 10 | "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TalentManagementAPIDb;Integrated Security=True;MultipleActiveResultSets=True" 11 | }, 12 | "Serilog": { 13 | "Using": [ ], 14 | "MinimumLevel": { 15 | "Default": "Debug", 16 | "Override": { 17 | "Microsoft": "Warning", 18 | "Microsoft.EntityFrameworkCore.Database.Command": "Warning", 19 | "System": "Warning" 20 | } 21 | }, 22 | "WriteTo": [ 23 | { "Name": "Console" }, 24 | { 25 | "Name": "Logger", 26 | "Args": { 27 | "configureLogger": { 28 | "Filter": [ 29 | { 30 | "Name": "ByIncludingOnly", 31 | "Args": { 32 | "expression": "@l = 'Error' or @l = 'Fatal' or @l = 'Warning'" 33 | } 34 | } 35 | ], 36 | "WriteTo": [ 37 | { 38 | "Name": "File", 39 | "Args": { 40 | "path": "Logs/Error/error_.log", 41 | "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}", 42 | "rollingInterval": "Day", 43 | "retainedFileCountLimit": 7 44 | } 45 | } 46 | ] 47 | } 48 | } 49 | }, 50 | { 51 | "Name": "Logger", 52 | "Args": { 53 | "configureLogger": { 54 | "Filter": [ 55 | { 56 | "Name": "ByIncludingOnly", 57 | "ApiRoles": null, 58 | "Args": { 59 | "expression": "@l = 'Information'" 60 | } 61 | } 62 | ], 63 | "WriteTo": [ 64 | { 65 | "Name": "File", 66 | "Args": { 67 | "path": "Logs/Info/info_.log", 68 | "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}", 69 | "rollingInterval": "Day", 70 | "retainedFileCountLimit": 7 71 | } 72 | } 73 | ] 74 | } 75 | } 76 | } 77 | ], 78 | "Properties": { 79 | "ApplicationName": "Serilog.TalentManagementAPI" 80 | } 81 | }, 82 | "MailSettings": { 83 | "EmailFrom": "info@janedoe.com", 84 | "SmtpHost": "smtp.janedoe.com", 85 | "SmtpPort": 587, 86 | "SmtpUser": "Jane.Doe@janedoe.email", 87 | "SmtpPass": "6X4wBQQYgU14F23VYc", 88 | "DisplayName": "Jane Doe" 89 | }, 90 | "Sts": { 91 | "ServerUrl": "https://localhost:44310", 92 | "Audience": "app.api.employeeprofile" 93 | }, 94 | "ApiRoles": { 95 | "EmployeeRole": "Employee", 96 | "ManagerRole": "Manager", 97 | "AdminRole": "HRAdmin" 98 | }, 99 | "AllowedHosts": "*" 100 | } --------------------------------------------------------------------------------