├── .gitattributes ├── .gitignore ├── TalentManagement.sln └── TalentManagement ├── TalentManagement.Application ├── Behaviours │ └── ValidationBehaviour.cs ├── DTOs │ └── Email │ │ └── EmailRequest.cs ├── Enums │ └── Roles.cs ├── Exceptions │ ├── ApiException.cs │ └── ValidationException.cs ├── Features │ ├── Employees │ │ └── Queries │ │ │ └── GetEmployees │ │ │ ├── GetEmployeesQuery.cs │ │ │ └── GetEmployeesViewModel.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 ├── 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 │ ├── PagingParameter.cs │ └── QueryParameter.cs ├── ServiceExtensions.cs ├── TalentManagement.Application.csproj └── Wrappers │ ├── PagedResponse.cs │ └── Response.cs ├── TalentManagement.Domain ├── Common │ ├── AuditableBaseEntity.cs │ └── BaseEntity.cs ├── Entities │ ├── Employee.cs │ ├── Entity.cs │ └── Position.cs ├── Enums │ └── Gender.cs ├── Settings │ ├── JWTSettings.cs │ └── MailSettings.cs └── TalentManagement.Domain.csproj ├── TalentManagement.Infrastructure.Persistence ├── Contexts │ └── ApplicationDbContext.cs ├── Migrations │ ├── 20210124215036_IntitialCreate.Designer.cs │ ├── 20210124215036_IntitialCreate.cs │ └── ApplicationDbContextModelSnapshot.cs ├── Repositories │ ├── EmployeeRepositoryAsync.cs │ ├── GenericRepositoryAsync.cs │ └── PositionRepositoryAsync.cs ├── ServiceRegistration.cs └── TalentManagement.Infrastructure.Persistence.csproj ├── TalentManagement.Infrastructure.Shared ├── Mock │ ├── EmployeeBogusConfig.cs │ ├── PositionInsertBogusConfig.cs │ └── PositionSeedBogusConfig.cs ├── ServiceRegistration.cs ├── Services │ ├── DateTimeService.cs │ ├── EmailService.cs │ └── MockService.cs └── TalentManagement.Infrastructure.Shared.csproj └── TalentManagement.WebApi ├── Controllers ├── BaseApiController.cs ├── MetaController.cs └── v1 │ ├── EmployeesController.cs │ └── PositionsController.cs ├── Extensions ├── AppExtensions.cs └── ServiceExtensions.cs ├── Middlewares └── ErrorHandlerMiddleware.cs ├── Models └── Metadata.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Startup.cs ├── TalentManagement.WebApi.csproj ├── TalentManagement.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 | -------------------------------------------------------------------------------- /.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 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /TalentManagement.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30717.126 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{F48D99CB-62B6-4971-AA91-2FC330E181F7}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TalentManagement.Application", "TalentManagement\TalentManagement.Application\TalentManagement.Application.csproj", "{3CBCAD78-44AA-44C1-B04D-F7CE75804CA5}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TalentManagement.Domain", "TalentManagement\TalentManagement.Domain\TalentManagement.Domain.csproj", "{C320B75A-2F50-496E-9954-3591A8031BEA}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{B0EA8256-DA31-497D-84CE-87C298461591}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TalentManagement.Infrastructure.Persistence", "TalentManagement\TalentManagement.Infrastructure.Persistence\TalentManagement.Infrastructure.Persistence.csproj", "{8CE43001-A522-4D95-8EF3-6C4B151D6B07}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TalentManagement.Infrastructure.Shared", "TalentManagement\TalentManagement.Infrastructure.Shared\TalentManagement.Infrastructure.Shared.csproj", "{29F9AE5B-2D97-4090-967D-DBB67766169B}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Presentation", "Presentation", "{7C45B327-B6ED-4FA8-A2A0-6F4A4166F2B9}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TalentManagement.WebApi", "TalentManagement\TalentManagement.WebApi\TalentManagement.WebApi.csproj", "{1B439744-A746-405C-B7DE-250206B3BE95}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {3CBCAD78-44AA-44C1-B04D-F7CE75804CA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {3CBCAD78-44AA-44C1-B04D-F7CE75804CA5}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {3CBCAD78-44AA-44C1-B04D-F7CE75804CA5}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {3CBCAD78-44AA-44C1-B04D-F7CE75804CA5}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {C320B75A-2F50-496E-9954-3591A8031BEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {C320B75A-2F50-496E-9954-3591A8031BEA}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {C320B75A-2F50-496E-9954-3591A8031BEA}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {C320B75A-2F50-496E-9954-3591A8031BEA}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {8CE43001-A522-4D95-8EF3-6C4B151D6B07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {8CE43001-A522-4D95-8EF3-6C4B151D6B07}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {8CE43001-A522-4D95-8EF3-6C4B151D6B07}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {8CE43001-A522-4D95-8EF3-6C4B151D6B07}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {29F9AE5B-2D97-4090-967D-DBB67766169B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {29F9AE5B-2D97-4090-967D-DBB67766169B}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {29F9AE5B-2D97-4090-967D-DBB67766169B}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {29F9AE5B-2D97-4090-967D-DBB67766169B}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {1B439744-A746-405C-B7DE-250206B3BE95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {1B439744-A746-405C-B7DE-250206B3BE95}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {1B439744-A746-405C-B7DE-250206B3BE95}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {1B439744-A746-405C-B7DE-250206B3BE95}.Release|Any CPU.Build.0 = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | GlobalSection(NestedProjects) = preSolution 53 | {3CBCAD78-44AA-44C1-B04D-F7CE75804CA5} = {F48D99CB-62B6-4971-AA91-2FC330E181F7} 54 | {C320B75A-2F50-496E-9954-3591A8031BEA} = {F48D99CB-62B6-4971-AA91-2FC330E181F7} 55 | {8CE43001-A522-4D95-8EF3-6C4B151D6B07} = {B0EA8256-DA31-497D-84CE-87C298461591} 56 | {29F9AE5B-2D97-4090-967D-DBB67766169B} = {B0EA8256-DA31-497D-84CE-87C298461591} 57 | {1B439744-A746-405C-B7DE-250206B3BE95} = {7C45B327-B6ED-4FA8-A2A0-6F4A4166F2B9} 58 | EndGlobalSection 59 | GlobalSection(ExtensibilityGlobals) = postSolution 60 | SolutionGuid = {9DF98D24-A254-449E-89B5-1210BB6DF844} 61 | EndGlobalSection 62 | EndGlobal 63 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.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, CancellationToken cancellationToken, RequestHandlerDelegate next) 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 | } 35 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/DTOs/Email/EmailRequest.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.DTOs.Email 3 | { 4 | public class EmailRequest 5 | { 6 | public string To { get; set; } 7 | public string Subject { get; set; } 8 | public string Body { get; set; } 9 | public string From { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Enums/Roles.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.Enums 3 | { 4 | public enum Roles 5 | { 6 | SuperAdmin, 7 | Admin, 8 | Moderator, 9 | Basic 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Exceptions/ApiException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | 4 | namespace TalentManagement.Application.Exceptions 5 | { 6 | public class ApiException : Exception 7 | { 8 | public ApiException() : base() { } 9 | 10 | public ApiException(string message) : base(message) { } 11 | 12 | public ApiException(string message, params object[] args) 13 | : base(String.Format(CultureInfo.CurrentCulture, message, args)) 14 | { 15 | } 16 | 17 | public ApiException(string message, Exception innerException) : base(message, innerException) 18 | { 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation.Results; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace TalentManagement.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 | public List Errors { get; } 14 | public ValidationException(IEnumerable failures) 15 | : this() 16 | { 17 | foreach (var failure in failures) 18 | { 19 | Errors.Add(failure.ErrorMessage); 20 | } 21 | } 22 | 23 | public ValidationException(string message) : base(message) 24 | { 25 | } 26 | 27 | public ValidationException(string message, Exception innerException) : base(message, innerException) 28 | { 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.Application.Filters; 7 | using TalentManagement.Application.Interfaces; 8 | using TalentManagement.Application.Interfaces.Repositories; 9 | using TalentManagement.Application.Wrappers; 10 | using TalentManagement.Domain.Entities; 11 | 12 | namespace TalentManagement.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 | } 25 | public class GetAllEmployeesQueryHandler : IRequestHandler>> 26 | { 27 | private readonly IEmployeeRepositoryAsync _employeeRepository; 28 | private readonly IMapper _mapper; 29 | private readonly IModelHelper _modelHelper; 30 | public GetAllEmployeesQueryHandler(IEmployeeRepositoryAsync employeeRepository, IMapper mapper, IModelHelper modelHelper) 31 | { 32 | _employeeRepository = employeeRepository; 33 | _mapper = mapper; 34 | _modelHelper = modelHelper; 35 | } 36 | 37 | public async Task>> Handle(GetEmployeesQuery request, CancellationToken cancellationToken) 38 | { 39 | var validFilter = request; 40 | //filtered fields security 41 | if (!string.IsNullOrEmpty(validFilter.Fields)) 42 | { 43 | //limit to fields in view model 44 | validFilter.Fields = _modelHelper.ValidateModelFields(validFilter.Fields); 45 | 46 | } 47 | if (string.IsNullOrEmpty(validFilter.Fields)) 48 | { 49 | //default fields from view model 50 | validFilter.Fields = _modelHelper.GetModelFields(); 51 | } 52 | // query based on filter 53 | var entityEmployees = await _employeeRepository.GetPagedEmployeeReponseAsync(validFilter); 54 | // response wrapper 55 | return new PagedResponse>(entityEmployees, validFilter.PageNumber, validFilter.PageSize); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Employees/Queries/GetEmployees/GetEmployeesViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using TalentManagement.Domain.Enums; 3 | 4 | namespace TalentManagement.Application.Features.Employees.Queries.GetEmployees 5 | { 6 | public class GetEmployeesViewModel 7 | { 8 | public Guid Id { get; set; } 9 | public string FirstName { get; set; } 10 | public string MiddleName { get; set; } 11 | public string LastName { get; set; } 12 | public string EmployeeTitle { get; set; } 13 | public DateTime DOB { get; set; } 14 | public string Email { get; set; } 15 | public Gender Gender { get; set; } 16 | public string EmployeeNumber { get; set; } 17 | public string Suffix { get; set; } 18 | public string Phone { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Commands/CreatePosition/CreatePositionCommand.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using TalentManagement.Application.Interfaces.Repositories; 6 | using TalentManagement.Application.Wrappers; 7 | using TalentManagement.Domain.Entities; 8 | 9 | namespace TalentManagement.Application.Features.Positions.Commands.CreatePosition 10 | { 11 | public partial class CreatePositionCommand : IRequest> 12 | { 13 | public string PositionTitle { get; set; } 14 | public string PositionNumber { get; set; } 15 | public string PositionDescription { get; set; } 16 | public decimal PositionSalary { get; set; } 17 | } 18 | public class CreatePositionCommandHandler : IRequestHandler> 19 | { 20 | private readonly IPositionRepositoryAsync _positionRepository; 21 | private readonly IMapper _mapper; 22 | public CreatePositionCommandHandler(IPositionRepositoryAsync positionRepository, IMapper mapper) 23 | { 24 | _positionRepository = positionRepository; 25 | _mapper = mapper; 26 | } 27 | 28 | public async Task> Handle(CreatePositionCommand request, CancellationToken cancellationToken) 29 | { 30 | var position = _mapper.Map(request); 31 | await _positionRepository.AddAsync(position); 32 | return new Response(position.Id); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Commands/CreatePosition/CreatePositionCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagement.Application.Interfaces.Repositories; 5 | 6 | namespace TalentManagement.Application.Features.Positions.Commands.CreatePosition 7 | { 8 | public class CreatePositionCommandValidator : AbstractValidator 9 | { 10 | private readonly IPositionRepositoryAsync positionRepository; 11 | 12 | public CreatePositionCommandValidator(IPositionRepositoryAsync positionRepository) 13 | { 14 | this.positionRepository = positionRepository; 15 | 16 | RuleFor(p => p.PositionNumber) 17 | .NotEmpty().WithMessage("{PropertyName} is required.") 18 | .NotNull() 19 | .MaximumLength(50).WithMessage("{PropertyName} must not exceed 50 characters.") 20 | .MustAsync(IsUniquePositionNumber).WithMessage("{PropertyName} already exists."); 21 | 22 | RuleFor(p => p.PositionTitle) 23 | .NotEmpty().WithMessage("{PropertyName} is required.") 24 | .NotNull() 25 | .MaximumLength(50).WithMessage("{PropertyName} must not exceed 50 characters."); 26 | 27 | } 28 | 29 | private async Task IsUniquePositionNumber(string positionNumber, CancellationToken cancellationToken) 30 | { 31 | return await positionRepository.IsUniquePositionNumberAsync(positionNumber); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Commands/CreatePosition/InsertMockPositionCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagement.Application.Interfaces.Repositories; 5 | using TalentManagement.Application.Wrappers; 6 | 7 | namespace TalentManagement.Application.Features.Positions.Commands.CreatePosition 8 | { 9 | public partial class InsertMockPositionCommand : IRequest> 10 | { 11 | public int RowCount { get; set; } 12 | } 13 | public class SeedPositionCommandHandler : IRequestHandler> 14 | { 15 | private readonly IPositionRepositoryAsync _positionRepository; 16 | public SeedPositionCommandHandler(IPositionRepositoryAsync positionRepository) 17 | { 18 | _positionRepository = positionRepository; 19 | } 20 | 21 | public async Task> Handle(InsertMockPositionCommand request, CancellationToken cancellationToken) 22 | { 23 | await _positionRepository.SeedDataAsync(request.RowCount); 24 | return new Response(request.RowCount); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Commands/DeletePositionById/DeleteProductByIdCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagement.Application.Exceptions; 5 | using TalentManagement.Application.Interfaces.Repositories; 6 | using TalentManagement.Application.Wrappers; 7 | 8 | namespace TalentManagement.Application.Features.Positions.Commands.DeletePositionById 9 | { 10 | public class DeletePositionByIdCommand : IRequest> 11 | { 12 | public int Id { get; set; } 13 | public class DeletePositionByIdCommandHandler : IRequestHandler> 14 | { 15 | private readonly IPositionRepositoryAsync _positionRepository; 16 | public DeletePositionByIdCommandHandler(IPositionRepositoryAsync positionRepository) 17 | { 18 | _positionRepository = positionRepository; 19 | } 20 | public async Task> Handle(DeletePositionByIdCommand command, CancellationToken cancellationToken) 21 | { 22 | var position = await _positionRepository.GetByIdAsync(command.Id); 23 | if (position == null) throw new ApiException($"Position Not Found."); 24 | await _positionRepository.DeleteAsync(position); 25 | return new Response(position.Id); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Commands/UpdatePosition/UpdatePositionCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagement.Application.Exceptions; 5 | using TalentManagement.Application.Interfaces.Repositories; 6 | using TalentManagement.Application.Wrappers; 7 | 8 | namespace TalentManagement.Application.Features.Positions.Commands.UpdatePosition 9 | { 10 | public class UpdatePositionCommand : IRequest> 11 | { 12 | public int Id { get; set; } 13 | public string Title { get; set; } 14 | public string Description { get; set; } 15 | public decimal Salary { get; set; } 16 | public class UpdatePositionCommandHandler : IRequestHandler> 17 | { 18 | private readonly IPositionRepositoryAsync _positionRepository; 19 | public UpdatePositionCommandHandler(IPositionRepositoryAsync positionRepository) 20 | { 21 | _positionRepository = positionRepository; 22 | } 23 | public async Task> Handle(UpdatePositionCommand command, CancellationToken cancellationToken) 24 | { 25 | var position = await _positionRepository.GetByIdAsync(command.Id); 26 | 27 | if (position == null) 28 | { 29 | throw new ApiException($"Position Not Found."); 30 | } 31 | else 32 | { 33 | position.PositionTitle = command.Title; 34 | position.PositionSalary = command.Salary; 35 | position.PositionDescription = command.Description; 36 | await _positionRepository.UpdateAsync(position); 37 | return new Response(position.Id); 38 | } 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Queries/GetPositionById/GetPositionByIdQuery.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using TalentManagement.Application.Exceptions; 5 | using TalentManagement.Application.Interfaces.Repositories; 6 | using TalentManagement.Application.Wrappers; 7 | using TalentManagement.Domain.Entities; 8 | 9 | namespace TalentManagement.Application.Features.Positions.Queries.GetPositionById 10 | { 11 | public class GetPositionByIdQuery : IRequest> 12 | { 13 | public int Id { get; set; } 14 | public class GetPositionByIdQueryHandler : IRequestHandler> 15 | { 16 | private readonly IPositionRepositoryAsync _positionRepository; 17 | public GetPositionByIdQueryHandler(IPositionRepositoryAsync positionRepository) 18 | { 19 | _positionRepository = positionRepository; 20 | } 21 | public async Task> Handle(GetPositionByIdQuery query, CancellationToken cancellationToken) 22 | { 23 | var position = await _positionRepository.GetByIdAsync(query.Id); 24 | if (position == null) throw new ApiException($"Position Not Found."); 25 | return new Response(position); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.Application.Filters; 7 | using TalentManagement.Application.Interfaces; 8 | using TalentManagement.Application.Interfaces.Repositories; 9 | using TalentManagement.Application.Wrappers; 10 | using TalentManagement.Domain.Entities; 11 | 12 | namespace TalentManagement.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 | 19 | } 20 | public class GetAllPositionsQueryHandler : IRequestHandler>> 21 | { 22 | private readonly IPositionRepositoryAsync _positionRepository; 23 | private readonly IMapper _mapper; 24 | private readonly IModelHelper _modelHelper; 25 | public GetAllPositionsQueryHandler(IPositionRepositoryAsync positionRepository, IMapper mapper, IModelHelper modelHelper) 26 | { 27 | _positionRepository = positionRepository; 28 | _mapper = mapper; 29 | _modelHelper = modelHelper; 30 | } 31 | 32 | public async Task>> Handle(GetPositionsQuery request, CancellationToken cancellationToken) 33 | { 34 | var validFilter = request; 35 | //filtered fields security 36 | if (!string.IsNullOrEmpty(validFilter.Fields)) 37 | { 38 | //limit to fields in view model 39 | validFilter.Fields = _modelHelper.ValidateModelFields(validFilter.Fields); 40 | 41 | } 42 | if (string.IsNullOrEmpty(validFilter.Fields)) 43 | { 44 | //default fields from view model 45 | validFilter.Fields = _modelHelper.GetModelFields(); 46 | } 47 | // query based on filter 48 | var entityPositions = await _positionRepository.GetPagedPositionReponseAsync(validFilter); 49 | // response wrapper 50 | return new PagedResponse>(entityPositions, validFilter.PageNumber, validFilter.PageSize); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Features/Positions/Queries/GetPositions/GetPositionsViewModel.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.Features.Positions.Queries.GetPositions 3 | { 4 | public class GetPositionsViewModel 5 | { 6 | public int Id { get; set; } 7 | public string PositionTitle { get; set; } 8 | public string PositionNumber { get; set; } 9 | public string PositionDescription { get; set; } 10 | public decimal PositionSalary { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.Application.Interfaces; 7 | using TalentManagement.Domain.Entities; 8 | 9 | namespace TalentManagement.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 | public async Task> ShapeDataAsync(IEnumerable entities, string fieldsString) 27 | { 28 | var requiredProperties = GetRequiredProperties(fieldsString); 29 | 30 | return await Task.Run(() => FetchData(entities, requiredProperties)); 31 | } 32 | 33 | public Entity ShapeData(T entity, string fieldsString) 34 | { 35 | var requiredProperties = GetRequiredProperties(fieldsString); 36 | 37 | return FetchDataForEntity(entity, requiredProperties); 38 | } 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 | } 94 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Helpers/ModelHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using TalentManagement.Application.Interfaces; 4 | 5 | namespace TalentManagement.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 | /// Get list of field names in the model class 33 | /// 34 | /// 35 | /// 36 | public string GetModelFields() 37 | { 38 | string retString = string.Empty; 39 | 40 | var bindingFlags = System.Reflection.BindingFlags.Instance | 41 | System.Reflection.BindingFlags.NonPublic | 42 | System.Reflection.BindingFlags.Public; 43 | var listFields = typeof(T).GetProperties(bindingFlags).Select(f => f.Name).ToList(); 44 | 45 | foreach (string field in listFields) 46 | { 47 | retString += field + ","; 48 | } 49 | 50 | return retString; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/IDataShapeHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using TalentManagement.Domain.Entities; 4 | 5 | namespace TalentManagement.Application.Interfaces 6 | { 7 | public interface IDataShapeHelper 8 | { 9 | IEnumerable ShapeData(IEnumerable entities, string fieldsString); 10 | Task> ShapeDataAsync(IEnumerable entities, string fieldsString); 11 | Entity ShapeData(T entity, string fieldsString); 12 | } 13 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/IDateTimeService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TalentManagement.Application.Interfaces 4 | { 5 | public interface IDateTimeService 6 | { 7 | DateTime NowUtc { get; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/IEmailService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using TalentManagement.Application.DTOs.Email; 3 | 4 | namespace TalentManagement.Application.Interfaces 5 | { 6 | public interface IEmailService 7 | { 8 | Task SendAsync(EmailRequest request); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/IGenericRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | 5 | namespace TalentManagement.Application.Interfaces 6 | { 7 | public interface IGenericRepositoryAsync where T : class 8 | { 9 | Task GetByIdAsync(int id); 10 | Task> GetAllAsync(); 11 | Task> GetPagedReponseAsync(int pageNumber, int pageSize); 12 | Task> GetPagedAdvancedReponseAsync(int pageNumber, int pageSize, string orderBy, string fields); 13 | Task AddAsync(T entity); 14 | Task UpdateAsync(T entity); 15 | Task DeleteAsync(T entity); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/IMockService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using TalentManagement.Domain.Entities; 3 | 4 | namespace TalentManagement.Application.Interfaces 5 | { 6 | public interface IMockService 7 | { 8 | List GetPositions(int rowCount); 9 | List GetEmployees(int rowCount); 10 | List SeedPositions(int rowCount); 11 | } 12 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/IModelHelper.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.Interfaces 3 | { 4 | public interface IModelHelper 5 | { 6 | string GetModelFields(); 7 | string ValidateModelFields(string fields); 8 | } 9 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/Repositories/IEmployeeRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using TalentManagement.Application.Features.Employees.Queries.GetEmployees; 4 | using TalentManagement.Domain.Entities; 5 | 6 | namespace TalentManagement.Application.Interfaces.Repositories 7 | { 8 | public interface IEmployeeRepositoryAsync : IGenericRepositoryAsync 9 | { 10 | Task> GetPagedEmployeeReponseAsync(GetEmployeesQuery requestParameter); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Interfaces/Repositories/IPositionRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using TalentManagement.Application.Features.Positions.Queries.GetPositions; 4 | using TalentManagement.Domain.Entities; 5 | 6 | namespace TalentManagement.Application.Interfaces.Repositories 7 | { 8 | public interface IPositionRepositoryAsync : IGenericRepositoryAsync 9 | { 10 | Task IsUniquePositionNumberAsync(string positionNumber); 11 | Task SeedDataAsync(int rowCount); 12 | Task> GetPagedPositionReponseAsync(GetPositionsQuery requestParameters); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Mappings/GeneralProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using TalentManagement.Application.Features.Employees.Queries.GetEmployees; 3 | using TalentManagement.Application.Features.Positions.Commands.CreatePosition; 4 | using TalentManagement.Application.Features.Positions.Queries.GetPositions; 5 | using TalentManagement.Domain.Entities; 6 | 7 | namespace TalentManagement.Application.Mappings 8 | { 9 | public class GeneralProfile : Profile 10 | { 11 | public GeneralProfile() 12 | { 13 | CreateMap().ReverseMap(); 14 | CreateMap().ReverseMap(); 15 | CreateMap(); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Parameters/PagingParameter.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.Filters 3 | { 4 | public class PagingParameter 5 | { 6 | const int maxPageSize = 200; 7 | public int PageNumber { get; set; } = 1; 8 | private int _pageSize = 10; 9 | public int PageSize 10 | { 11 | get 12 | { 13 | return _pageSize; 14 | } 15 | set 16 | { 17 | _pageSize = (value > maxPageSize) ? maxPageSize : value; 18 | } 19 | } 20 | public PagingParameter() 21 | { 22 | //this.PageNumber = 1; 23 | //this.PageSize = 10; 24 | } 25 | //public PagingParameter(int pageNumber, int pageSize) 26 | //{ 27 | // this.PageNumber = pageNumber < 1 ? 1 : pageNumber; 28 | // this.PageSize = pageSize > maxPageSize ? maxPageSize : pageSize; 29 | //} 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Parameters/QueryParameter.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.Filters 3 | { 4 | public class QueryParameter : PagingParameter 5 | { 6 | public virtual string OrderBy { get; set; } 7 | public virtual string Fields { get; set; } 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/ServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using FluentValidation; 3 | using MediatR; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System.Reflection; 6 | using TalentManagement.Application.Behaviours; 7 | using TalentManagement.Application.Helpers; 8 | using TalentManagement.Application.Interfaces; 9 | using TalentManagement.Domain.Entities; 10 | 11 | namespace TalentManagement.Application 12 | { 13 | public static class ServiceExtensions 14 | { 15 | public static void AddApplicationLayer(this IServiceCollection services) 16 | { 17 | services.AddAutoMapper(Assembly.GetExecutingAssembly()); 18 | services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); 19 | services.AddMediatR(Assembly.GetExecutingAssembly()); 20 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); 21 | services.AddScoped, DataShapeHelper>(); 22 | services.AddScoped, DataShapeHelper>(); 23 | services.AddScoped(); 24 | //services.AddScoped(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/TalentManagement.Application.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | 1.1.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Wrappers/PagedResponse.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Application.Wrappers 3 | { 4 | public class PagedResponse : Response 5 | { 6 | public int PageNumber { get; set; } 7 | public int PageSize { get; set; } 8 | 9 | public PagedResponse(T data, int pageNumber, int pageSize) 10 | { 11 | this.PageNumber = pageNumber; 12 | this.PageSize = pageSize; 13 | this.Data = data; 14 | this.Message = null; 15 | this.Succeeded = true; 16 | this.Errors = null; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Application/Wrappers/Response.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace TalentManagement.Application.Wrappers 4 | { 5 | public class Response 6 | { 7 | public Response() 8 | { 9 | } 10 | public Response(T data, string message = null) 11 | { 12 | Succeeded = true; 13 | Message = message; 14 | Data = data; 15 | } 16 | public Response(string message) 17 | { 18 | Succeeded = false; 19 | Message = message; 20 | } 21 | public bool Succeeded { get; set; } 22 | public string Message { get; set; } 23 | public List Errors { get; set; } 24 | public T Data { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Common/AuditableBaseEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TalentManagement.Domain.Common 4 | { 5 | public abstract class AuditableBaseEntity 6 | { 7 | public virtual int Id { get; set; } 8 | public string CreatedBy { get; set; } 9 | public DateTime Created { get; set; } 10 | public string LastModifiedBy { get; set; } 11 | public DateTime? LastModified { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Common/BaseEntity.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Domain.Common 3 | { 4 | public abstract class BaseEntity 5 | { 6 | public virtual int Id { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Entities/Employee.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using TalentManagement.Domain.Enums; 3 | 4 | namespace TalentManagement.Domain.Entities 5 | { 6 | public class Employee 7 | { 8 | public Guid Id { get; set; } 9 | public string FirstName { get; set; } 10 | public string MiddleName { get; set; } 11 | public string LastName { get; set; } 12 | public string EmployeeTitle { get; set; } 13 | public DateTime DOB { get; set; } 14 | public string Email { get; set; } 15 | public Gender Gender { get; set; } 16 | public string EmployeeNumber { get; set; } 17 | public string Suffix { get; set; } 18 | public string Phone { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.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 | } 166 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Entities/Position.cs: -------------------------------------------------------------------------------- 1 | using TalentManagement.Domain.Common; 2 | 3 | namespace TalentManagement.Domain.Entities 4 | { 5 | public class Position : AuditableBaseEntity 6 | { 7 | public string PositionTitle { get; set; } 8 | public string PositionNumber { get; set; } 9 | public string PositionDescription { get; set; } 10 | public string PostionArea { get; set; } 11 | public string PostionType { get; set; } 12 | public decimal PositionSalary { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Enums/Gender.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Domain.Enums 3 | { 4 | public enum Gender 5 | { 6 | Male, 7 | Female 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Settings/JWTSettings.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Domain.Settings 3 | { 4 | public class JWTSettings 5 | { 6 | public string Key { get; set; } 7 | public string Issuer { get; set; } 8 | public string Audience { get; set; } 9 | public double DurationInMinutes { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/Settings/MailSettings.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.Domain.Settings 3 | { 4 | public class MailSettings 5 | { 6 | public string EmailFrom { get; set; } 7 | public string SmtpHost { get; set; } 8 | public int SmtpPort { get; set; } 9 | public string SmtpUser { get; set; } 10 | public string SmtpPass { get; set; } 11 | public string DisplayName { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Domain/TalentManagement.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 1.1.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.Application.Interfaces; 7 | using TalentManagement.Domain.Common; 8 | using TalentManagement.Domain.Entities; 9 | 10 | namespace TalentManagement.Infrastructure.Persistence.Contexts 11 | { 12 | public class ApplicationDbContext : DbContext 13 | { 14 | private readonly IDateTimeService _dateTime; 15 | private readonly ILoggerFactory _loggerFactory; 16 | 17 | public ApplicationDbContext(DbContextOptions options, 18 | IDateTimeService dateTime, 19 | ILoggerFactory loggerFactory 20 | ) : base(options) 21 | { 22 | ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 23 | _dateTime = dateTime; 24 | _loggerFactory = loggerFactory; 25 | } 26 | public DbSet Positions { get; set; } 27 | 28 | public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) 29 | { 30 | foreach (var entry in ChangeTracker.Entries()) 31 | { 32 | switch (entry.State) 33 | { 34 | case EntityState.Added: 35 | entry.Entity.Created = _dateTime.NowUtc; 36 | break; 37 | case EntityState.Modified: 38 | entry.Entity.LastModified = _dateTime.NowUtc; 39 | break; 40 | } 41 | } 42 | return base.SaveChangesAsync(cancellationToken); 43 | } 44 | protected override void OnModelCreating(ModelBuilder builder) 45 | { 46 | var _mockData = this.Database.GetService(); 47 | var seedPositions = _mockData.SeedPositions(1000); 48 | builder.Entity().HasData(seedPositions); 49 | 50 | base.OnModelCreating(builder); 51 | 52 | 53 | } 54 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 55 | { 56 | optionsBuilder.UseLoggerFactory(_loggerFactory); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Persistence/Repositories/EmployeeRepositoryAsync.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 TalentManagement.Application.Features.Employees.Queries.GetEmployees; 8 | using TalentManagement.Application.Interfaces; 9 | using TalentManagement.Application.Interfaces.Repositories; 10 | using TalentManagement.Domain.Entities; 11 | using TalentManagement.Infrastructure.Persistence.Contexts; 12 | using TalentManagement.Infrastructure.Persistence.Repository; 13 | 14 | namespace TalentManagement.Infrastructure.Persistence.Repositories 15 | { 16 | public class EmployeeRepositoryAsync : GenericRepositoryAsync, IEmployeeRepositoryAsync 17 | { 18 | private readonly ApplicationDbContext _dbContext; 19 | private readonly DbSet _employee; 20 | private IDataShapeHelper _dataShaper; 21 | private readonly IMockService _mockData; 22 | public EmployeeRepositoryAsync(ApplicationDbContext dbContext, 23 | IDataShapeHelper dataShaper, 24 | IMockService mockData) : base(dbContext) 25 | { 26 | _dbContext = dbContext; 27 | _employee = dbContext.Set(); 28 | _dataShaper = dataShaper; 29 | _mockData = mockData; 30 | } 31 | 32 | public async Task> GetPagedEmployeeReponseAsync(GetEmployeesQuery requestParameter) 33 | { 34 | 35 | IQueryable result; 36 | 37 | var employeeNumber = requestParameter.EmployeeNumber; 38 | var employeeTitle = requestParameter.EmployeeTitle; 39 | var orderBy = requestParameter.OrderBy; 40 | var fields = requestParameter.Fields; 41 | var pageNumber = requestParameter.PageNumber; 42 | var pageSize = requestParameter.PageSize; 43 | 44 | result = _mockData.GetEmployees(1000) 45 | .AsQueryable() 46 | .Skip((pageNumber - 1) * pageSize) 47 | .Take(pageSize); 48 | 49 | //filter 50 | FilterByColumn(ref result, employeeNumber, employeeTitle); 51 | if (!string.IsNullOrWhiteSpace(orderBy)) 52 | { 53 | result = result.OrderBy(orderBy); 54 | } 55 | 56 | //limit query fields 57 | if (!string.IsNullOrWhiteSpace(fields)) 58 | { 59 | result = result.Select("new(" + fields + ")"); 60 | } 61 | // retrieve data to list 62 | // var resultData = await result.ToListAsync(); 63 | // Note: Bogus library does not support await for AsQueryable. 64 | // Workaround: fake await with Task.Run and use regular ToList 65 | var resultData = await Task.Run(() => result.ToList()); 66 | 67 | // shape data 68 | return _dataShaper.ShapeData(resultData, fields); 69 | 70 | } 71 | private void FilterByColumn(ref IQueryable positions, string employeeNumber, string employeeTitle) 72 | { 73 | if (!positions.Any()) 74 | return; 75 | 76 | if (string.IsNullOrEmpty(employeeTitle) && string.IsNullOrEmpty(employeeNumber)) 77 | return; 78 | 79 | var predicate = PredicateBuilder.New(); 80 | 81 | if (!string.IsNullOrEmpty(employeeNumber)) 82 | predicate = predicate.And(p => p.EmployeeNumber.Contains(employeeNumber.Trim())); 83 | 84 | if (!string.IsNullOrEmpty(employeeTitle)) 85 | predicate = predicate.And(p => p.EmployeeTitle.Contains(employeeTitle.Trim())); 86 | 87 | positions = positions.Where(predicate); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Persistence/Repositories/GenericRepositoryAsync.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Dynamic.Core; 5 | using System.Threading.Tasks; 6 | using TalentManagement.Application.Interfaces; 7 | using TalentManagement.Infrastructure.Persistence.Contexts; 8 | 9 | namespace TalentManagement.Infrastructure.Persistence.Repository 10 | { 11 | public class GenericRepositoryAsync : IGenericRepositoryAsync where T : class 12 | { 13 | private readonly ApplicationDbContext _dbContext; 14 | 15 | public GenericRepositoryAsync(ApplicationDbContext dbContext) 16 | { 17 | _dbContext = dbContext; 18 | } 19 | 20 | public virtual async Task GetByIdAsync(int id) 21 | { 22 | return await _dbContext.Set().FindAsync(id); 23 | } 24 | 25 | public async Task> GetPagedReponseAsync(int pageNumber, int pageSize) 26 | { 27 | return await _dbContext 28 | .Set() 29 | .Skip((pageNumber - 1) * pageSize) 30 | .Take(pageSize) 31 | .AsNoTracking() 32 | .ToListAsync(); 33 | } 34 | 35 | public async Task> GetPagedAdvancedReponseAsync(int pageNumber, int pageSize, string orderBy, string fields) 36 | { 37 | return await _dbContext 38 | .Set() 39 | .Skip((pageNumber - 1) * pageSize) 40 | .Take(pageSize) 41 | .Select("new(" + fields + ")") 42 | .OrderBy(orderBy) 43 | .AsNoTracking() 44 | .ToListAsync(); 45 | } 46 | 47 | public async Task AddAsync(T entity) 48 | { 49 | await _dbContext.Set().AddAsync(entity); 50 | await _dbContext.SaveChangesAsync(); 51 | return entity; 52 | } 53 | 54 | 55 | public async Task UpdateAsync(T entity) 56 | { 57 | _dbContext.Entry(entity).State = EntityState.Modified; 58 | await _dbContext.SaveChangesAsync(); 59 | } 60 | 61 | public async Task DeleteAsync(T entity) 62 | { 63 | _dbContext.Set().Remove(entity); 64 | await _dbContext.SaveChangesAsync(); 65 | } 66 | 67 | public async Task> GetAllAsync() 68 | { 69 | return await _dbContext 70 | .Set() 71 | .ToListAsync(); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.Application.Features.Positions.Queries.GetPositions; 8 | using TalentManagement.Application.Interfaces; 9 | using TalentManagement.Application.Interfaces.Repositories; 10 | using TalentManagement.Domain.Entities; 11 | using TalentManagement.Infrastructure.Persistence.Contexts; 12 | using TalentManagement.Infrastructure.Persistence.Repository; 13 | 14 | namespace TalentManagement.Infrastructure.Persistence.Repositories 15 | { 16 | public class PositionRepositoryAsync : GenericRepositoryAsync, IPositionRepositoryAsync 17 | { 18 | private readonly ApplicationDbContext _dbContext; 19 | private readonly DbSet _positions; 20 | private IDataShapeHelper _dataShaper; 21 | private readonly IMockService _mockData; 22 | 23 | 24 | 25 | public PositionRepositoryAsync(ApplicationDbContext dbContext, 26 | IDataShapeHelper dataShaper, IMockService mockData) : base(dbContext) 27 | { 28 | _dbContext = dbContext; 29 | _positions = dbContext.Set(); 30 | _dataShaper = dataShaper; 31 | _mockData = mockData; 32 | } 33 | 34 | public async Task IsUniquePositionNumberAsync(string positionNumber) 35 | { 36 | return await _positions 37 | .AllAsync(p => p.PositionNumber != positionNumber); 38 | } 39 | public async Task SeedDataAsync(int rowCount) 40 | { 41 | 42 | foreach (Position position in _mockData.GetPositions(rowCount)) 43 | { 44 | await this.AddAsync(position); 45 | 46 | } 47 | return true; 48 | } 49 | 50 | public async Task> GetPagedPositionReponseAsync(GetPositionsQuery requestParameter) 51 | { 52 | var positionNumber = requestParameter.PositionNumber; 53 | var positionTitle = requestParameter.PositionTitle; 54 | 55 | var pageNumber = requestParameter.PageNumber; 56 | var pageSize = requestParameter.PageSize; 57 | var orderBy = requestParameter.OrderBy; 58 | var fields = requestParameter.Fields; 59 | 60 | var result = _positions 61 | .AsNoTracking() 62 | .AsExpandable() 63 | .Skip((pageNumber - 1) * pageSize) 64 | .Take(pageSize); 65 | 66 | // filter 67 | FilterByColumn(ref result, positionNumber, positionTitle); 68 | // order by 69 | if (!string.IsNullOrWhiteSpace(orderBy)) 70 | { 71 | result = result.OrderBy(orderBy); 72 | } 73 | // query field limit 74 | if (!string.IsNullOrWhiteSpace(fields)) 75 | { 76 | result = result.Select("new(" + fields + ")"); 77 | } 78 | // retrieve data to list 79 | var resultData = await result.ToListAsync(); 80 | // shape data 81 | return _dataShaper.ShapeData(resultData, fields); 82 | 83 | } 84 | private void FilterByColumn(ref IQueryable positions, string positionNumber, string positionTitle) 85 | { 86 | if (!positions.Any()) 87 | return; 88 | 89 | if (string.IsNullOrEmpty(positionTitle) && string.IsNullOrEmpty(positionNumber)) 90 | return; 91 | 92 | var predicate = PredicateBuilder.New(); 93 | 94 | if (!string.IsNullOrEmpty(positionNumber)) 95 | predicate = predicate.And(p => p.PositionNumber.Contains(positionNumber.Trim())); 96 | 97 | if (!string.IsNullOrEmpty(positionTitle)) 98 | predicate = predicate.And(p => p.PositionTitle.Contains(positionTitle.Trim())); 99 | 100 | positions = positions.Where(predicate); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Persistence/ServiceRegistration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using TalentManagement.Application.Interfaces; 5 | using TalentManagement.Application.Interfaces.Repositories; 6 | using TalentManagement.Infrastructure.Persistence.Contexts; 7 | using TalentManagement.Infrastructure.Persistence.Repositories; 8 | using TalentManagement.Infrastructure.Persistence.Repository; 9 | 10 | namespace TalentManagement.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 | #region Repositories 29 | services.AddTransient(typeof(IGenericRepositoryAsync<>), typeof(GenericRepositoryAsync<>)); 30 | services.AddTransient(); 31 | services.AddTransient(); 32 | #endregion 33 | 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Persistence/TalentManagement.Infrastructure.Persistence.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | 1.1.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/Mock/EmployeeBogusConfig.cs: -------------------------------------------------------------------------------- 1 | using AutoBogus; 2 | using Bogus; 3 | using System; 4 | using TalentManagement.Domain.Entities; 5 | using TalentManagement.Domain.Enums; 6 | 7 | namespace TalentManagement.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, 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 | } 28 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/Mock/PositionInsertBogusConfig.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using TalentManagement.Domain.Entities; 3 | 4 | 5 | namespace TalentManagement.Infrastructure.Shared.Mock 6 | { 7 | public class PositionInsertBogusConfig : Faker 8 | { 9 | public PositionInsertBogusConfig() 10 | { 11 | RuleFor(o => o.PositionTitle, f => f.Name.JobTitle()); 12 | RuleFor(o => o.PositionNumber, f => f.Commerce.Ean13()); 13 | RuleFor(o => o.PositionDescription, f => f.Name.JobDescriptor()); 14 | RuleFor(o => o.CreatedBy, f => f.Name.FullName()); 15 | RuleFor(o => o.PositionSalary, f => f.Finance.Amount()); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/Mock/PositionSeedBogusConfig.cs: -------------------------------------------------------------------------------- 1 | using AutoBogus; 2 | using Bogus; 3 | using System; 4 | using TalentManagement.Domain.Entities; 5 | 6 | namespace TalentManagement.Infrastructure.Shared.Mock 7 | { 8 | public class PositionSeedBogusConfig : AutoFaker 9 | { 10 | public PositionSeedBogusConfig() 11 | { 12 | Randomizer.Seed = new Random(8675309); 13 | var id = 1; 14 | RuleFor(m => m.Id, f => id++); 15 | RuleFor(o => o.PositionTitle, f => f.Name.JobTitle()); 16 | RuleFor(o => o.PositionNumber, f => f.Commerce.Ean13()); 17 | RuleFor(o => o.PositionDescription, f => f.Name.JobDescriptor()); 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 | RuleFor(o => o.PositionSalary, f => f.Finance.Amount()); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/ServiceRegistration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TalentManagement.Application.Interfaces; 4 | using TalentManagement.Domain.Settings; 5 | using TalentManagement.Infrastructure.Shared.Services; 6 | 7 | namespace TalentManagement.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 | } 20 | } 21 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/Services/DateTimeService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using TalentManagement.Application.Interfaces; 3 | 4 | namespace TalentManagement.Infrastructure.Shared.Services 5 | { 6 | public class DateTimeService : IDateTimeService 7 | { 8 | public DateTime NowUtc => DateTime.UtcNow; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 TalentManagement.Application.DTOs.Email; 8 | using TalentManagement.Application.Exceptions; 9 | using TalentManagement.Application.Interfaces; 10 | using TalentManagement.Domain.Settings; 11 | 12 | namespace TalentManagement.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 | } 44 | catch (System.Exception ex) 45 | { 46 | _logger.LogError(ex.Message, ex); 47 | throw new ApiException(ex.Message); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/Services/MockService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using TalentManagement.Application.Interfaces; 3 | using TalentManagement.Domain.Entities; 4 | using TalentManagement.Infrastructure.Shared.Mock; 5 | 6 | namespace TalentManagement.Infrastructure.Shared.Services 7 | { 8 | public class MockService : IMockService 9 | { 10 | public List GetPositions(int rowCount) 11 | { 12 | var positionFaker = new PositionInsertBogusConfig(); 13 | return positionFaker.Generate(rowCount); 14 | } 15 | public List GetEmployees(int rowCount) 16 | { 17 | var positionFaker = new EmployeeBogusConfig(); 18 | return positionFaker.Generate(rowCount); 19 | } 20 | public List SeedPositions(int rowCount) 21 | { 22 | var seedPositionFaker = new PositionSeedBogusConfig(); 23 | return seedPositionFaker.Generate(rowCount); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.Infrastructure.Shared/TalentManagement.Infrastructure.Shared.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 1.1.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Controllers/BaseApiController.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | 6 | namespace TalentManagement.WebApi.Controllers 7 | { 8 | [ApiController] 9 | [Route("api/v{version:apiVersion}/[controller]")] 10 | public abstract class BaseApiController : ControllerBase 11 | { 12 | private IMediator _mediator; 13 | protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Controllers/MetaController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Diagnostics; 3 | 4 | namespace TalentManagement.WebApi.Controllers 5 | { 6 | public class MetaController : BaseApiController 7 | { 8 | [HttpGet("/info")] 9 | public ActionResult Info() 10 | { 11 | var assembly = typeof(Startup).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 | } 20 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Controllers/v1/EmployeesController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System.Threading.Tasks; 3 | using TalentManagement.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 TalentManagement.WebApi.Controllers.v1 8 | { 9 | [ApiVersion("1.0")] 10 | public class EmployeesController : BaseApiController 11 | { 12 | /// 13 | /// GET: api/controller 14 | /// 15 | /// 16 | /// 17 | [HttpGet] 18 | 19 | public async Task Get([FromQuery] GetEmployeesQuery filter) 20 | { 21 | return Ok(await Mediator.Send(filter)); 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Controllers/v1/PositionsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System.Threading.Tasks; 4 | using TalentManagement.Application.Features.Positions.Commands.CreatePosition; 5 | using TalentManagement.Application.Features.Positions.Commands.DeletePositionById; 6 | using TalentManagement.Application.Features.Positions.Commands.UpdatePosition; 7 | using TalentManagement.Application.Features.Positions.Queries.GetPositionById; 8 | using TalentManagement.Application.Features.Positions.Queries.GetPositions; 9 | 10 | // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 11 | 12 | namespace TalentManagement.WebApi.Controllers.v1 13 | { 14 | [ApiVersion("1.0")] 15 | public class PositionsController : BaseApiController 16 | { 17 | /// 18 | /// GET: api/controller 19 | /// 20 | /// 21 | /// 22 | [HttpGet] 23 | public async Task Get([FromQuery] GetPositionsQuery filter) 24 | { 25 | return Ok(await Mediator.Send(filter)); 26 | } 27 | 28 | /// 29 | /// GET api/controller/5 30 | /// 31 | /// 32 | /// 33 | [HttpGet("{id}")] 34 | public async Task Get(int id) 35 | { 36 | return Ok(await Mediator.Send(new GetPositionByIdQuery { Id = id })); 37 | } 38 | 39 | /// 40 | /// POST api/controller 41 | /// 42 | /// 43 | /// 44 | [HttpPost] 45 | // [Authorize] 46 | public async Task Post(CreatePositionCommand command) 47 | { 48 | return Ok(await Mediator.Send(command)); 49 | } 50 | 51 | /// 52 | /// Bulk insert fake data by specifying number of rows 53 | /// 54 | /// 55 | /// 56 | [HttpPost] 57 | [Route("AddMock")] 58 | // [Authorize] 59 | public async Task AddMock(InsertMockPositionCommand command) 60 | { 61 | return Ok(await Mediator.Send(command)); 62 | } 63 | 64 | 65 | /// 66 | /// PUT api/controller/5 67 | /// 68 | /// 69 | /// 70 | /// 71 | [HttpPut("{id}")] 72 | [Authorize] 73 | public async Task Put(int id, UpdatePositionCommand command) 74 | { 75 | if (id != command.Id) 76 | { 77 | return BadRequest(); 78 | } 79 | return Ok(await Mediator.Send(command)); 80 | } 81 | 82 | /// 83 | /// DELETE api/controller/5 84 | /// 85 | /// 86 | /// 87 | [HttpDelete("{id}")] 88 | [Authorize] 89 | public async Task Delete(int id) 90 | { 91 | return Ok(await Mediator.Send(new DeletePositionByIdCommand { Id = id })); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Extensions/AppExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using TalentManagement.WebApi.Middlewares; 3 | 4 | namespace TalentManagement.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.TalentManagement.WebApi"); 14 | }); 15 | } 16 | public static void UseErrorHandlingMiddleware(this IApplicationBuilder app) 17 | { 18 | app.UseMiddleware(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Extensions/ServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.PlatformAbstractions; 4 | using Microsoft.OpenApi.Models; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Reflection; 9 | 10 | namespace TalentManagement.WebApi.Extensions 11 | { 12 | public static class ServiceExtensions 13 | { 14 | public static void AddSwaggerExtension(this IServiceCollection services) 15 | { 16 | services.AddSwaggerGen(c => 17 | { 18 | c.IncludeXmlComments(XmlCommentsFilePath); 19 | c.SwaggerDoc("v1", new OpenApiInfo 20 | { 21 | Version = "v1", 22 | Title = "Clean Architecture - TalentManagement.WebApi", 23 | Description = "This Api will be responsible for overall data distribution and authorization.", 24 | Contact = new OpenApiContact 25 | { 26 | Name = "Jane Doe", 27 | Email = "jdoe@janedoe.com", 28 | Url = new Uri("https://janedoe.com/contact"), 29 | } 30 | }); 31 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 32 | { 33 | Name = "Authorization", 34 | In = ParameterLocation.Header, 35 | Type = SecuritySchemeType.ApiKey, 36 | Scheme = "Bearer", 37 | BearerFormat = "JWT", 38 | Description = "Input your Bearer token in this format - Bearer {your token here} to access this API", 39 | }); 40 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 41 | { 42 | { 43 | new OpenApiSecurityScheme 44 | { 45 | Reference = new OpenApiReference 46 | { 47 | Type = ReferenceType.SecurityScheme, 48 | Id = "Bearer", 49 | }, 50 | Scheme = "Bearer", 51 | Name = "Bearer", 52 | In = ParameterLocation.Header, 53 | }, new List() 54 | }, 55 | }); 56 | }); 57 | } 58 | public static void AddApiVersioningExtension(this IServiceCollection services) 59 | { 60 | services.AddApiVersioning(config => 61 | { 62 | // Specify the default API Version as 1.0 63 | config.DefaultApiVersion = new ApiVersion(1, 0); 64 | // If the client hasn't specified the API version in the request, use the default API version number 65 | config.AssumeDefaultVersionWhenUnspecified = true; 66 | // Advertise the API versions supported for the particular endpoint 67 | config.ReportApiVersions = true; 68 | }); 69 | } 70 | static string XmlCommentsFilePath 71 | { 72 | get 73 | { 74 | var basePath = PlatformServices.Default.Application.ApplicationBasePath; 75 | var fileName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml"; 76 | return Path.Combine(basePath, fileName); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Middlewares/ErrorHandlerMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net; 5 | using System.Text.Json; 6 | using System.Threading.Tasks; 7 | using TalentManagement.Application.Exceptions; 8 | using TalentManagement.Application.Wrappers; 9 | 10 | namespace TalentManagement.WebApi.Middlewares 11 | { 12 | public class ErrorHandlerMiddleware 13 | { 14 | private readonly RequestDelegate _next; 15 | 16 | public ErrorHandlerMiddleware(RequestDelegate next) 17 | { 18 | _next = next; 19 | } 20 | 21 | public async Task Invoke(HttpContext context) 22 | { 23 | try 24 | { 25 | await _next(context); 26 | } 27 | catch (Exception error) 28 | { 29 | var response = context.Response; 30 | response.ContentType = "application/json"; 31 | var responseModel = new Response() { Succeeded = false, Message = error?.Message }; 32 | 33 | switch (error) 34 | { 35 | case Application.Exceptions.ApiException e: 36 | // custom application error 37 | response.StatusCode = (int)HttpStatusCode.BadRequest; 38 | break; 39 | case ValidationException e: 40 | // custom application error 41 | response.StatusCode = (int)HttpStatusCode.BadRequest; 42 | responseModel.Errors = e.Errors; 43 | break; 44 | case KeyNotFoundException e: 45 | // not found error 46 | response.StatusCode = (int)HttpStatusCode.NotFound; 47 | break; 48 | default: 49 | // unhandled error 50 | response.StatusCode = (int)HttpStatusCode.InternalServerError; 51 | break; 52 | } 53 | var result = JsonSerializer.Serialize(responseModel); 54 | 55 | await response.WriteAsync(result); 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Models/Metadata.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TalentManagement.WebApi.Models 3 | { 4 | public class Metadata 5 | { 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Logging; 6 | using Serilog; 7 | using System; 8 | 9 | namespace TalentManagement.WebApi 10 | { 11 | public static class Program 12 | { 13 | public static void Main(string[] args) 14 | { 15 | //Read Configuration from appSettings 16 | var config = new ConfigurationBuilder() 17 | .AddJsonFile("appsettings.json") 18 | .Build(); 19 | 20 | //Initialize Logger 21 | Log.Logger = new LoggerConfiguration() 22 | .ReadFrom.Configuration(config) 23 | .WriteTo.Console() 24 | .CreateLogger(); 25 | 26 | var host = CreateHostBuilder(args).Build(); 27 | using (var scope = host.Services.CreateScope()) 28 | { 29 | var services = scope.ServiceProvider; 30 | var loggerFactory = services.GetRequiredService(); 31 | try 32 | { 33 | Log.Information("Application Starting"); 34 | } 35 | catch (Exception ex) 36 | { 37 | Log.Warning(ex, "An error occurred starting the application"); 38 | } 39 | finally 40 | { 41 | Log.CloseAndFlush(); 42 | } 43 | } 44 | host.Run(); 45 | } 46 | public static IHostBuilder CreateHostBuilder(string[] args) => 47 | Host.CreateDefaultBuilder(args) 48 | .UseSerilog() //Uses Serilog instead of default .NET Logger 49 | .ConfigureWebHostDefaults(webBuilder => 50 | { 51 | webBuilder.UseStartup(); 52 | }); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 | "TalentManagement.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 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/Startup.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 Microsoft.Extensions.Logging; 7 | using Serilog; 8 | using System.Text.Json; 9 | using TalentManagement.Application; 10 | using TalentManagement.Infrastructure.Persistence; 11 | using TalentManagement.Infrastructure.Persistence.Contexts; 12 | using TalentManagement.Infrastructure.Shared; 13 | using TalentManagement.WebApi.Extensions; 14 | 15 | namespace TalentManagement.WebApi 16 | { 17 | public class Startup 18 | { 19 | public IConfiguration _config { get; } 20 | public Startup(IConfiguration configuration) 21 | { 22 | _config = configuration; 23 | 24 | } 25 | public void ConfigureServices(IServiceCollection services) 26 | { 27 | services.AddApplicationLayer(); 28 | services.AddPersistenceInfrastructure(_config); 29 | services.AddSharedInfrastructure(_config); 30 | services.AddSwaggerExtension(); 31 | services.AddControllers() 32 | .AddJsonOptions(options => 33 | { 34 | options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase; 35 | options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; 36 | }) 37 | ; 38 | services.AddApiVersioningExtension(); 39 | services.AddHealthChecks(); 40 | //testing 41 | services.AddMvcCore() 42 | .AddApiExplorer(); 43 | services.AddVersionedApiExplorer(o => 44 | { 45 | o.GroupNameFormat = "'v'VVV"; 46 | o.SubstituteApiVersionInUrl = true; 47 | }); 48 | } 49 | 50 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext dbContext) 51 | { 52 | if (env.IsDevelopment()) 53 | { 54 | app.UseDeveloperExceptionPage(); 55 | } 56 | else 57 | { 58 | app.UseExceptionHandler("/Error"); 59 | app.UseHsts(); 60 | } 61 | 62 | dbContext.Database.EnsureCreated(); 63 | 64 | // Add this line; you'll need `using Serilog;` up the top, too 65 | app.UseSerilogRequestLogging(); 66 | loggerFactory.AddSerilog(); 67 | app.UseHttpsRedirection(); 68 | app.UseRouting(); 69 | app.UseAuthentication(); 70 | app.UseAuthorization(); 71 | app.UseSwaggerExtension(); 72 | app.UseErrorHandlingMiddleware(); 73 | app.UseHealthChecks("/health"); 74 | 75 | app.UseEndpoints(endpoints => 76 | { 77 | endpoints.MapControllers(); 78 | }); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/TalentManagement.WebApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | Mukesh Murugan 6 | codewithmukesh 7 | https://github.com/iammukeshm/CleanArchitecture.WebApi 8 | Public 9 | https://www.codewithmukesh.com/project/aspnet-core-webapi-clean-architecture/ 10 | 1.1.0 11 | 12 | 13 | 14 | TalentManagement.WebApi.xml 15 | 1701;1702;1591 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | all 29 | runtime; build; native; contentfiles; analyzers; buildtransitive 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.WebApi/TalentManagement.WebApi.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TalentManagement.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 | PUT api/controller/5 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | DELETE api/controller/5 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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 | } -------------------------------------------------------------------------------- /TalentManagement/TalentManagement.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=TalentManagementDb;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": "@Level = 'Error' or @Level = 'Fatal' or @Level = '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 | "Args": { 58 | "expression": "@Level = 'Information'" 59 | } 60 | } 61 | ], 62 | "WriteTo": [ 63 | { 64 | "Name": "File", 65 | "Args": { 66 | "path": "Logs/Info/info_.log", 67 | "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}", 68 | "rollingInterval": "Day", 69 | "retainedFileCountLimit": 7 70 | } 71 | } 72 | ] 73 | } 74 | } 75 | } 76 | ], 77 | "Enrich": [ 78 | "FromLogContext", 79 | "WithMachineName", 80 | "WithProcessId", 81 | "WithThreadId" 82 | ], 83 | "Properties": { 84 | "ApplicationName": "Serilog.WebApplication" 85 | } 86 | }, 87 | "MailSettings": { 88 | "EmailFrom": "info@codewithmukesh.com", 89 | "SmtpHost": "smtp.ethereal.email", 90 | "SmtpPort": 587, 91 | "SmtpUser": "doyle.sauer@ethereal.email", 92 | "SmtpPass": "6X4wBQQYgU14F23VYc", 93 | "DisplayName": "Mukesh Murugan" 94 | }, 95 | "JWTSettings": { 96 | "Key": "C1CF4B7DC4C4175B6618DE4F55CA4", 97 | "Issuer": "CoreIdentity", 98 | "Audience": "CoreIdentityUser", 99 | "DurationInMinutes": 60 100 | }, 101 | "AllowedHosts": "*" 102 | } 103 | --------------------------------------------------------------------------------