├── .gitattributes ├── .gitignore ├── ASP.NETCore5.0WebAPI.pdf ├── CompanyEmployee.API ├── CompanyEmployee.API.csproj ├── CompanyEmployee.API.xml ├── Controllers │ ├── AuthenticationController.cs │ ├── CompaniesController.cs │ ├── CompaniesV2Controller.cs │ ├── EmployeesController.cs │ └── WeatherForecastController.cs ├── Infrastructure │ ├── ActionFilters │ │ ├── ValidateCompanyExistsAttribute.cs │ │ ├── ValidateEmployeeForCompanyExistsAttribute.cs │ │ └── ValidationFilterAttribute.cs │ ├── CsvOutputFormatter.cs │ ├── Extensions │ │ ├── ExceptionMiddlewareExtensions.cs │ │ └── ServiceExtensions.cs │ ├── MappingProfile.cs │ └── ModelBinders │ │ └── ArrayModelBinder.cs ├── Migrations │ ├── 20210109115024_Init.Designer.cs │ ├── 20210109115024_Init.cs │ ├── 20210109120245_SeedData.Designer.cs │ ├── 20210109120245_SeedData.cs │ ├── 20210204060838_CreatingIdentityTables.Designer.cs │ ├── 20210204060838_CreatingIdentityTables.cs │ ├── 20210204062338_AddedRolesToDb.Designer.cs │ ├── 20210204062338_AddedRolesToDb.cs │ └── CompanyEmployeeDbContextModelSnapshot.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json ├── appsettings.json └── nlog.config ├── CompanyEmployee.sln ├── Contracts ├── Contracts.csproj └── IServices │ ├── IAuthenticationManager.cs │ ├── ICompanyRepository.cs │ ├── IDataShaper.cs │ ├── IEmployeeRepository.cs │ ├── ILoggerManager.cs │ ├── IRepositoryBase.cs │ └── IRepositoryManager.cs ├── Entities ├── CompanyEmployeeDbContext.cs ├── Configuration │ ├── CompanyConfiguration.cs │ ├── EmployeeConfiguration.cs │ ├── IdentityUserLoginConfiquration.cs │ └── RoleConfiguration.cs ├── DataTransferObjects │ ├── CompanyDto.cs │ ├── CompanyForCreationDto.cs │ ├── CompanyForUpdateDto.cs │ ├── EmployeeDto.cs │ ├── EmployeeForCreationDto.cs │ ├── EmployeeForManipulationDto.cs │ ├── EmployeeForUpdateDto.cs │ ├── UserForAuthenticationDto.cs │ └── UserForRegistrationDto.cs ├── Entities.csproj ├── ErrorModel │ └── ErrorDetails.cs ├── Models │ ├── Company.cs │ ├── Employee.cs │ └── User.cs └── RequestFeatures │ ├── MetaData.cs │ ├── PagedList.cs │ └── RequestParameters.cs ├── LoggerService ├── LoggerManager.cs └── LoggerService.csproj ├── README.md ├── Repository ├── AuthenticationManager.cs ├── DataShaping │ └── DataShaper.cs ├── Extensions │ └── RepositoryEmployeeExtensions.cs ├── Repositories │ ├── CompanyRepository.cs │ ├── EmployeeRepository.cs │ ├── RepositoryBase.cs │ └── RepositoryManager.cs └── Repository.csproj └── img └── ASPNETCore5.0WebAPI.jpg /.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 -------------------------------------------------------------------------------- /ASP.NETCore5.0WebAPI.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZahraBayatgh/ASP.NET-Core-5.0-Web-API/94535af56e7664b66eb04449fdced86f0a75a959/ASP.NETCore5.0WebAPI.pdf -------------------------------------------------------------------------------- /CompanyEmployee.API/CompanyEmployee.API.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | D:\Projects\CompanyEmployee\CompanyEmployee.API\CompanyEmployee.API.xml 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | all 24 | runtime; build; native; contentfiles; analyzers; buildtransitive 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /CompanyEmployee.API/CompanyEmployee.API.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CompanyEmployee.API 5 | 6 | 7 | 8 | 9 | Gets the list of all companies 10 | 11 | The companies list 12 | 13 | 14 | 15 | Creates a newly created company 16 | 17 | 18 | A newly created company 19 | Returns the newly created item 20 | If the item is null 21 | If the model is invalid 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Controllers/AuthenticationController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CompanyEmployee.API.Infrastructure.ActionFilters; 3 | using Contracts.IServices; 4 | using Entities.DataTransferObjects; 5 | using Entities.Models; 6 | using Microsoft.AspNetCore.Identity; 7 | using Microsoft.AspNetCore.Mvc; 8 | using System.Threading.Tasks; 9 | 10 | namespace CompanyEmployee.API.Controllers 11 | { 12 | [Route("api/authentication")] 13 | [ApiController] 14 | public class AuthenticationController : ControllerBase 15 | { 16 | private readonly ILoggerManager _logger; 17 | private readonly IMapper _mapper; 18 | private readonly UserManager _userManager; 19 | private readonly IAuthenticationManager _authManager; 20 | 21 | public AuthenticationController(ILoggerManager logger, IMapper mapper, UserManager userManager, IAuthenticationManager authManager) 22 | { 23 | _logger = logger; 24 | _mapper = mapper; 25 | _userManager = userManager; 26 | _authManager = authManager; 27 | } 28 | 29 | [HttpPost("login")] 30 | [ServiceFilter(typeof(ValidationFilterAttribute))] 31 | public async Task AuthenticateAsync([FromBody] UserForAuthenticationDto user) 32 | { 33 | if (!await _authManager.ValidateUserAsync(user)) 34 | { 35 | _logger.LogWarn($"{nameof(AuthenticateAsync)}: Authentication failed. Wrong user name or password."); 36 | 37 | return Unauthorized(); 38 | } 39 | 40 | return Ok(new { Token = await _authManager.CreateTokenAsync() }); 41 | } 42 | 43 | [HttpPost] 44 | [ServiceFilter(typeof(ValidationFilterAttribute))] 45 | public async Task RegisterUserAsync([FromBody] UserForRegistrationDto userForRegistration) 46 | { 47 | var user = _mapper.Map(userForRegistration); 48 | var result = await _userManager.CreateAsync(user, userForRegistration.Password); 49 | 50 | if (!result.Succeeded) 51 | { 52 | foreach (var error in result.Errors) 53 | { 54 | ModelState.TryAddModelError(error.Code, error.Description); 55 | } 56 | 57 | return BadRequest(ModelState); 58 | } 59 | 60 | await _userManager.AddToRolesAsync(user, userForRegistration.Roles); 61 | 62 | return StatusCode(201); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Controllers/CompaniesController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CompanyEmployee.API.Infrastructure.ActionFilters; 3 | using CompanyEmployee.API.Infrastructure.ModelBinders; 4 | using Contracts.IServices; 5 | using Entities.DataTransferObjects; 6 | using Entities.Models; 7 | using Microsoft.AspNetCore.Mvc; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Threading.Tasks; 12 | using Marvin.Cache.Headers; 13 | using Microsoft.AspNetCore.Authorization; 14 | 15 | namespace CompanyEmployee.API.Controllers 16 | { 17 | [Route("api/companies")] 18 | [ResponseCache(CacheProfileName = "120SecondsDuration")] 19 | [ApiController] 20 | [ApiExplorerSettings(GroupName = "v1")] 21 | public class CompaniesController : ControllerBase 22 | { 23 | private readonly IRepositoryManager _repository; 24 | private readonly ILoggerManager _logger; 25 | private readonly IMapper _mapper; 26 | 27 | public CompaniesController(IRepositoryManager repository, ILoggerManager logger, 28 | IMapper mapper) 29 | { 30 | _repository = repository; 31 | _logger = logger; 32 | _mapper = mapper; 33 | } 34 | 35 | /// 36 | /// Gets the list of all companies 37 | /// 38 | /// The companies list 39 | [HttpGet(Name = "GetCompanies"), Authorize(Roles = "Manager")] 40 | public async Task GetCompaniesAsync() 41 | { 42 | var companies = await _repository.Company.GetAllCompaniesAsync(trackChanges: 43 | false); 44 | 45 | var companiesDto = _mapper.Map>(companies); 46 | 47 | return Ok(companiesDto); 48 | } 49 | 50 | [HttpGet("{id}", Name = "CompanyById")] 51 | [HttpCacheExpiration(CacheLocation = CacheLocation.Public, MaxAge = 60)] 52 | [HttpCacheValidation(MustRevalidate = false)] 53 | public async Task GetCompanyAsync(Guid id) 54 | { 55 | var company = await _repository.Company.GetCompanyAsync(id, trackChanges: false); 56 | 57 | if (company == null) 58 | { 59 | _logger.LogInfo($"Company with id: {id} doesn't exist in the database."); 60 | 61 | return NotFound(); 62 | } 63 | else 64 | { 65 | var companyDto = _mapper.Map(company); 66 | 67 | return Ok(companyDto); 68 | } 69 | } 70 | 71 | [HttpGet("collection/({ids})", Name = "CompanyCollection")] 72 | public async Task GetCompanyCollectionAsync([ModelBinder(BinderType = 73 | typeof(ArrayModelBinder))]IEnumerable ids) 74 | { 75 | if (ids == null) 76 | { 77 | _logger.LogError("Parameter ids is null"); 78 | 79 | return BadRequest("Parameter ids is null"); 80 | } 81 | 82 | var companyEntities = await _repository.Company.GetByIdsAsync(ids, trackChanges: 83 | false); 84 | 85 | if (ids.Count() != companyEntities.Count()) 86 | { 87 | _logger.LogError("Some ids are not valid in a collection"); 88 | 89 | return NotFound(); 90 | } 91 | 92 | var companiesToReturn = _mapper.Map>(companyEntities); 93 | 94 | return Ok(companiesToReturn); 95 | } 96 | 97 | /// 98 | /// Creates a newly created company 99 | /// 100 | /// 101 | /// A newly created company 102 | /// Returns the newly created item 103 | /// If the item is null 104 | /// If the model is invalid 105 | [HttpPost] 106 | [ProducesResponseType(201)] 107 | [ProducesResponseType(400)] 108 | [ProducesResponseType(422)] 109 | [ServiceFilter(typeof(ValidationFilterAttribute))] 110 | public async Task CreateCompanyAsync([FromBody]CompanyForCreationDto 111 | company) 112 | { 113 | var companyEntity = _mapper.Map(company); 114 | _repository.Company.CreateCompany(companyEntity); 115 | 116 | await _repository.SaveAsync(); 117 | 118 | var companyToReturn = _mapper.Map(companyEntity); 119 | 120 | return CreatedAtRoute("CompanyById", new { id = companyToReturn.Id }, 121 | companyToReturn); 122 | } 123 | 124 | [HttpPost("collection")] 125 | public async Task CreateCompanyCollectionAsync([FromBody] 126 | IEnumerable companyCollection) 127 | { 128 | if (companyCollection == null) 129 | { 130 | _logger.LogError("Company collection sent from client is null."); 131 | 132 | return BadRequest("Company collection is null"); 133 | } 134 | 135 | var companyEntities = _mapper.Map>(companyCollection); 136 | 137 | foreach (var company in companyEntities) 138 | { 139 | _repository.Company.CreateCompany(company); 140 | } 141 | 142 | await _repository.SaveAsync(); 143 | var companyCollectionToReturn = 144 | _mapper.Map>(companyEntities); 145 | var ids = string.Join(",", companyCollectionToReturn.Select(c => c.Id)); 146 | 147 | return CreatedAtRoute("CompanyCollection", new { ids }, 148 | companyCollectionToReturn); 149 | } 150 | 151 | [HttpDelete("{id}")] 152 | public async Task DeleteCompanyAsync(Guid id) 153 | { 154 | var company = await _repository.Company.GetCompanyAsync(id, trackChanges: false); 155 | 156 | if (company == null) 157 | { 158 | _logger.LogInfo($"Company with id: {id} doesn't exist in the database."); 159 | 160 | return NotFound(); 161 | } 162 | 163 | _repository.Company.DeleteCompany(company); 164 | await _repository.SaveAsync(); 165 | 166 | return NoContent(); 167 | } 168 | 169 | [HttpPut("{id}")] 170 | [ServiceFilter(typeof(ValidationFilterAttribute))] 171 | public async Task UpdateCompanyAsync(Guid id, [FromBody] CompanyForUpdateDto 172 | company) 173 | { 174 | var companyEntity = await _repository.Company.GetCompanyAsync(id, trackChanges: 175 | true); 176 | 177 | if (companyEntity == null) 178 | { 179 | _logger.LogInfo($"Company with id: {id} doesn't exist in the database."); 180 | 181 | return NotFound(); 182 | } 183 | 184 | _mapper.Map(company, companyEntity); 185 | await _repository.SaveAsync(); 186 | 187 | return NoContent(); 188 | } 189 | 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Controllers/CompaniesV2Controller.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System.Threading.Tasks; 4 | 5 | namespace CompanyEmployee.API.Controllers 6 | { 7 | [Route("api/companies")] 8 | [ApiController] 9 | [ApiExplorerSettings(GroupName = "v2")] 10 | public class CompaniesV2Controller : ControllerBase 11 | { 12 | private readonly IRepositoryManager _repository; 13 | 14 | public CompaniesV2Controller(IRepositoryManager repository) 15 | { 16 | _repository = repository; 17 | } 18 | 19 | [HttpGet] 20 | public async Task GetCompanies() 21 | { 22 | var companies = await _repository.Company.GetAllCompaniesAsync(trackChanges: 23 | false); 24 | 25 | return Ok(companies); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Controllers/EmployeesController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Contracts.IServices; 3 | using CompanyEmployee.API.Infrastructure.ActionFilters; 4 | using Entities.DataTransferObjects; 5 | using Entities.Models; 6 | using Microsoft.AspNetCore.JsonPatch; 7 | using Microsoft.AspNetCore.Mvc; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Threading.Tasks; 11 | using Entities.RequestFeatures; 12 | using Newtonsoft.Json; 13 | 14 | namespace CompanyEmployee.API.Controllers 15 | { 16 | [Route("api/companies/{companyId}/employees")] 17 | [ApiController] 18 | public class EmployeesController : ControllerBase 19 | { 20 | private readonly IRepositoryManager _repository; 21 | private readonly ILoggerManager _logger; 22 | private readonly IMapper _mapper; 23 | private readonly IDataShaper _dataShaper; 24 | public EmployeesController(IRepositoryManager repository, ILoggerManager logger, IMapper mapper, IDataShaper dataShaper) 25 | { 26 | _repository = repository; 27 | _logger = logger; 28 | _mapper = mapper; 29 | _dataShaper = dataShaper; 30 | } 31 | 32 | [HttpGet(Name = "GetEmployeeForCompany")] 33 | public async Task GetEmployeesForCompanyAsync(Guid companyId, [FromQuery] EmployeeParameters employeeParameters) 34 | { 35 | var company = await _repository.Company.GetCompanyAsync(companyId, trackChanges: false); 36 | 37 | if (!employeeParameters.ValidAgeRange) 38 | return BadRequest("Max age can't be less than min age."); 39 | 40 | if (company == null) 41 | { 42 | _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database."); 43 | 44 | return NotFound(); 45 | } 46 | 47 | var employeesFromDb = await _repository.Employee.GetEmployeesAsync(companyId, 48 | employeeParameters, trackChanges: false); 49 | 50 | Response.Headers.Add("X-Pagination", 51 | JsonConvert.SerializeObject(employeesFromDb.MetaData)); 52 | 53 | var employeesDto = _mapper.Map>(employeesFromDb); 54 | 55 | return Ok(_dataShaper.ShapeData(employeesDto, employeeParameters.Fields)); 56 | 57 | } 58 | 59 | [HttpGet("{id}")] 60 | public async Task GetEmployeeForCompanyAsync(Guid companyId, Guid id) 61 | { 62 | var company = await _repository.Company.GetCompanyAsync(companyId, trackChanges: false); 63 | 64 | if (company == null) 65 | { 66 | _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database."); 67 | 68 | return NotFound(); 69 | } 70 | 71 | var employeeDb = await _repository.Employee.GetEmployeeAsync(companyId, id, trackChanges: false); 72 | 73 | if (employeeDb == null) 74 | { 75 | _logger.LogInfo($"Employee with id: {id} doesn't exist in the database."); 76 | 77 | return NotFound(); 78 | } 79 | 80 | var employee = _mapper.Map(employeeDb); 81 | 82 | return Ok(employee); 83 | } 84 | 85 | [HttpPost] 86 | public async Task CreateEmployeeForCompanyAsync(Guid companyId, [FromBody] 87 | EmployeeForCreationDto employee) 88 | { 89 | if (employee == null) 90 | { 91 | _logger.LogError("EmployeeForCreationDto object sent from client is null."); 92 | 93 | return BadRequest("EmployeeForCreationDto object is null"); 94 | } 95 | 96 | if (!ModelState.IsValid) 97 | { 98 | _logger.LogError("Invalid model state for the EmployeeForCreationDto object"); 99 | 100 | return UnprocessableEntity(ModelState); 101 | } 102 | 103 | var company = await _repository.Company.GetCompanyAsync(companyId, trackChanges: false); 104 | 105 | if (company == null) 106 | { 107 | _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database."); 108 | 109 | return NotFound(); 110 | } 111 | 112 | var employeeEntity = _mapper.Map(employee); 113 | _repository.Employee.CreateEmployeeForCompany(companyId, employeeEntity); 114 | 115 | await _repository.SaveAsync(); 116 | 117 | var employeeToReturn = _mapper.Map(employeeEntity); 118 | 119 | return 120 | CreatedAtRoute("GetEmployeeForCompany", 121 | new 122 | { 123 | companyId, 124 | id = employeeToReturn.Id 125 | }, 126 | employeeToReturn); 127 | } 128 | 129 | [HttpDelete("{id}")] 130 | [ServiceFilter(typeof(ValidateEmployeeForCompanyExistsAttribute))] 131 | public async Task DeleteEmployeeForCompanyAsync(Guid companyId, Guid id) 132 | { 133 | var employeeForCompany = HttpContext.Items["employee"] as Employee; 134 | _repository.Employee.DeleteEmployee(employeeForCompany); 135 | 136 | await _repository.SaveAsync(); 137 | 138 | return NoContent(); 139 | } 140 | 141 | [HttpPut("{id}")] 142 | [ServiceFilter(typeof(ValidationFilterAttribute))] 143 | [ServiceFilter(typeof(ValidateEmployeeForCompanyExistsAttribute))] 144 | public async Task UpdateEmployeeForCompanyAsync(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee) 145 | { 146 | var employeeEntity = HttpContext.Items["employee"] as Employee; 147 | _mapper.Map(employee, employeeEntity); 148 | 149 | await _repository.SaveAsync(); 150 | 151 | return NoContent(); 152 | } 153 | 154 | [HttpPatch("{id}")] 155 | [ServiceFilter(typeof(ValidateEmployeeForCompanyExistsAttribute))] 156 | public async Task PartiallyUpdateEmployeeForCompanyAsync(Guid companyId, Guid id, [FromBody] JsonPatchDocument patchDoc) 157 | { 158 | if (patchDoc == null) 159 | { 160 | _logger.LogError("patchDoc object sent from client is null."); 161 | 162 | return BadRequest("patchDoc object is null"); 163 | } 164 | 165 | var employeeEntity = HttpContext.Items["employee"] as Employee; 166 | var employeeToPatch = _mapper.Map(employeeEntity); 167 | 168 | patchDoc.ApplyTo(employeeToPatch, ModelState); 169 | TryValidateModel(employeeToPatch); 170 | 171 | if (!ModelState.IsValid) 172 | { 173 | _logger.LogError("Invalid model state for the patch document"); 174 | 175 | return UnprocessableEntity(ModelState); 176 | } 177 | 178 | _mapper.Map(employeeToPatch, employeeEntity); 179 | await _repository.SaveAsync(); 180 | 181 | return NoContent(); 182 | } 183 | 184 | } 185 | 186 | } 187 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System.Collections.Generic; 4 | 5 | namespace CompanyEmployee.API.Controllers 6 | { 7 | [Route("[controller]")] 8 | [ApiController] 9 | public class WeatherForecastController : ControllerBase 10 | { 11 | private ILoggerManager _logger; 12 | public WeatherForecastController(ILoggerManager logger) 13 | { 14 | _logger = logger; 15 | } 16 | [HttpGet] 17 | public IEnumerable Get() 18 | { 19 | _logger.LogInfo("Here is info message from our values controller."); 20 | _logger.LogDebug("Here is debug message from our values controller."); 21 | _logger.LogWarn("Here is warn message from our values controller."); 22 | _logger.LogError("Here is an error message from our values controller."); 23 | 24 | return new string[] { "value1", "value2" }; 25 | } 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/ActionFilters/ValidateCompanyExistsAttribute.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace CompanyEmployee.API.Infrastructure.ActionFilters 8 | { 9 | public class ValidateCompanyExistsAttribute : IAsyncActionFilter 10 | { 11 | private readonly IRepositoryManager _repository; 12 | private readonly ILoggerManager _logger; 13 | 14 | public ValidateCompanyExistsAttribute(IRepositoryManager repository, 15 | ILoggerManager logger) 16 | { 17 | _repository = repository; 18 | _logger = logger; 19 | } 20 | 21 | public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 22 | { 23 | var trackChanges = context.HttpContext.Request.Method.Equals("PUT"); 24 | var id = (Guid)context.ActionArguments["id"]; 25 | 26 | var company = await _repository.Company.GetCompanyAsync(id, trackChanges); 27 | 28 | if (company == null) 29 | { 30 | _logger.LogInfo($"Company with id: {id} doesn't exist in the database."); 31 | context.Result = new NotFoundResult(); 32 | } 33 | else 34 | { 35 | context.HttpContext.Items.Add("company", company); 36 | await next(); 37 | } 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/ActionFilters/ValidateEmployeeForCompanyExistsAttribute.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace CompanyEmployee.API.Infrastructure.ActionFilters 8 | { 9 | public class ValidateEmployeeForCompanyExistsAttribute : IAsyncActionFilter 10 | { 11 | private readonly IRepositoryManager _repository; 12 | private readonly ILoggerManager _logger; 13 | 14 | public ValidateEmployeeForCompanyExistsAttribute(IRepositoryManager repository, ILoggerManager logger) 15 | { 16 | _repository = repository; 17 | _logger = logger; 18 | } 19 | 20 | public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 21 | { 22 | var method = context.HttpContext.Request.Method; 23 | var trackChanges = (method.Equals("PUT") || method.Equals("PATCH")) ? true : false; 24 | 25 | var companyId = (Guid)context.ActionArguments["companyId"]; 26 | var company = await _repository.Company.GetCompanyAsync(companyId, false); 27 | 28 | if (company == null) 29 | { 30 | _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database."); 31 | context.Result = new NotFoundResult(); 32 | 33 | return; 34 | } 35 | 36 | var id = (Guid)context.ActionArguments["id"]; 37 | var employee = await _repository.Employee.GetEmployeeAsync(companyId, id, 38 | trackChanges); 39 | 40 | if (employee == null) 41 | { 42 | _logger.LogInfo($"Employee with id: {id} doesn't exist in the database."); 43 | context.Result = new NotFoundResult(); 44 | } 45 | else 46 | { 47 | context.HttpContext.Items.Add("employee", employee); 48 | await next(); 49 | } 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/ActionFilters/ValidationFilterAttribute.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | using System.Linq; 5 | 6 | namespace CompanyEmployee.API.Infrastructure.ActionFilters 7 | { 8 | public class ValidationFilterAttribute : IActionFilter 9 | { 10 | private readonly ILoggerManager _logger; 11 | public ValidationFilterAttribute(ILoggerManager logger) 12 | { 13 | _logger = logger; 14 | } 15 | 16 | public void OnActionExecuting(ActionExecutingContext context) 17 | { 18 | var action = context.RouteData.Values["action"]; 19 | var controller = context.RouteData.Values["controller"]; 20 | var param = context.ActionArguments 21 | .SingleOrDefault(x => x.Value.ToString().Contains("Dto")).Value; 22 | 23 | if (param == null) 24 | { 25 | _logger.LogError($"Object sent from client is null. Controller: {controller}, action: {action} "); 26 | 27 | context.Result = new BadRequestObjectResult($"Object is null. Controller:{ controller}, action: {action} "); 28 | 29 | return; 30 | } 31 | 32 | if (!context.ModelState.IsValid) 33 | { 34 | _logger.LogError($"Invalid model state for the object. Controller: {controller}, action: {action} "); 35 | 36 | context.Result = new UnprocessableEntityObjectResult(context.ModelState); 37 | } 38 | } 39 | 40 | public void OnActionExecuted(ActionExecutedContext context) { } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/CsvOutputFormatter.cs: -------------------------------------------------------------------------------- 1 | using Entities.DataTransferObjects; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc.Formatters; 4 | using Microsoft.Net.Http.Headers; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace CompanyEmployee.API.Infrastructure 11 | { 12 | public class CsvOutputFormatter : TextOutputFormatter 13 | { 14 | public CsvOutputFormatter() 15 | { 16 | SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/csv")); 17 | SupportedEncodings.Add(Encoding.UTF8); 18 | SupportedEncodings.Add(Encoding.Unicode); 19 | } 20 | protected override bool CanWriteType(Type type) 21 | { 22 | if (typeof(CompanyDto).IsAssignableFrom(type) || 23 | typeof(IEnumerable).IsAssignableFrom(type)) 24 | { 25 | return base.CanWriteType(type); 26 | } 27 | 28 | return false; 29 | } 30 | 31 | public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext 32 | context, Encoding selectedEncoding) 33 | { 34 | var response = context.HttpContext.Response; 35 | var buffer = new StringBuilder(); 36 | 37 | if (context.Object is IEnumerable) 38 | { 39 | foreach (var company in (IEnumerable)context.Object) 40 | { 41 | FormatCsv(buffer, company); 42 | } 43 | } 44 | else 45 | { 46 | FormatCsv(buffer, (CompanyDto)context.Object); 47 | } 48 | 49 | await response.WriteAsync(buffer.ToString()); 50 | } 51 | private static void FormatCsv(StringBuilder buffer, CompanyDto company) 52 | { 53 | buffer.AppendLine($"{company.Id},\"{company.Name},\"{company.FullAddress}\""); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/Extensions/ExceptionMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Entities.ErrorModel; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Diagnostics; 5 | using Microsoft.AspNetCore.Http; 6 | using System.Net; 7 | 8 | namespace CompanyEmployee.API.Infrastructure.Extensions 9 | { 10 | public static class ExceptionMiddlewareExtensions 11 | { 12 | public static void ConfigureExceptionHandler(this IApplicationBuilder app, 13 | ILoggerManager logger) 14 | { 15 | app.UseExceptionHandler(appError => 16 | { 17 | appError.Run(async context => 18 | { 19 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 20 | context.Response.ContentType = "application/json"; 21 | var contextFeature = context.Features.Get(); 22 | if (contextFeature != null) 23 | { 24 | logger.LogError($"Something went wrong: {contextFeature.Error}"); 25 | await context.Response.WriteAsync(new ErrorDetails() 26 | { 27 | StatusCode = context.Response.StatusCode, 28 | Message = "Internal Server Error." 29 | }.ToString()); 30 | } 31 | }); 32 | }); 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/Extensions/ServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using CompanyEmployee.API.Controllers; 2 | using Contracts.IServices; 3 | using Entities; 4 | using LoggerService; 5 | using Marvin.Cache.Headers; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using AspNetCoreRateLimit; 12 | using System.Collections.Generic; 13 | using Repository.Repositories; 14 | using Entities.Models; 15 | using Microsoft.AspNetCore.Identity; 16 | using System; 17 | using Microsoft.AspNetCore.Authentication.JwtBearer; 18 | using Microsoft.IdentityModel.Tokens; 19 | using System.Text; 20 | using Microsoft.OpenApi.Models; 21 | using System.IO; 22 | using System.Reflection; 23 | 24 | 25 | namespace CompanyEmployee.API.Infrastructure.Extensions 26 | { 27 | public static class ServiceExtensions 28 | { 29 | public static void ConfigureCors(this IServiceCollection services) => 30 | services.AddCors(options => 31 | { 32 | options.AddPolicy("CorsPolicy", builder => 33 | builder.AllowAnyOrigin() 34 | .AllowAnyMethod() 35 | .AllowAnyHeader()); 36 | }); 37 | 38 | public static void ConfigureIISIntegration(this IServiceCollection services) => 39 | services.Configure(options => 40 | { 41 | }); 42 | public static void ConfigureLoggerService(this IServiceCollection services) => services.AddScoped(); 43 | 44 | public static void ConfigureSqlContext(this IServiceCollection services, 45 | IConfiguration configuration) => 46 | services.AddDbContext(opts => opts.UseSqlServer(configuration.GetConnectionString("sqlConnection"), b => 47 | b.MigrationsAssembly("CompanyEmployee.API"))); 48 | 49 | public static void ConfigureRepositoryManager(this IServiceCollection services) => 50 | services.AddScoped(); 51 | 52 | public static IMvcBuilder AddCustomCSVFormatter(this IMvcBuilder builder) => 53 | builder.AddMvcOptions(config => config.OutputFormatters.Add(new 54 | CsvOutputFormatter())); 55 | 56 | public static void ConfigureVersioning(this IServiceCollection services) 57 | { 58 | services.AddApiVersioning(opt => 59 | { 60 | opt.ReportApiVersions = true; 61 | opt.AssumeDefaultVersionWhenUnspecified = true; 62 | opt.DefaultApiVersion = new ApiVersion(1, 0); 63 | opt.Conventions.Controller().HasApiVersion(new ApiVersion(1, 0)); 64 | opt.Conventions.Controller().HasDeprecatedApiVersion(new ApiVersion(2, 0)); 65 | }); 66 | } 67 | 68 | public static void ConfigureResponseCaching(this IServiceCollection services) => services.AddResponseCaching(); 69 | 70 | public static void ConfigureHttpCacheHeaders(this IServiceCollection services) => 71 | services.AddHttpCacheHeaders( 72 | (expirationOpt) => 73 | { 74 | expirationOpt.MaxAge = 65; 75 | expirationOpt.CacheLocation = CacheLocation.Private; 76 | }, 77 | (validationOpt) => 78 | { 79 | validationOpt.MustRevalidate = true; 80 | }); 81 | 82 | public static void ConfigureRateLimitingOptions(this IServiceCollection services) 83 | { 84 | var rateLimitRules = new List 85 | { 86 | new RateLimitRule 87 | { 88 | Endpoint = "*", 89 | Limit= 30, 90 | Period = "5m" 91 | } 92 | }; 93 | services.Configure(opt => 94 | { 95 | opt.GeneralRules = rateLimitRules; 96 | }); 97 | services.AddSingleton(); 98 | 99 | services.AddSingleton(); 100 | 101 | services.AddSingleton(); 102 | } 103 | 104 | public static void ConfigureIdentity(this IServiceCollection services) 105 | { 106 | var builder = services.AddIdentityCore(o => 107 | { 108 | o.Password.RequireDigit = true; 109 | o.Password.RequireLowercase = false; 110 | o.Password.RequireUppercase = false; 111 | o.Password.RequireNonAlphanumeric = false; 112 | o.Password.RequiredLength = 10; 113 | o.User.RequireUniqueEmail = true; 114 | }); 115 | 116 | builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), 117 | builder.Services); 118 | builder.AddEntityFrameworkStores() 119 | .AddDefaultTokenProviders(); 120 | } 121 | 122 | public static void ConfigureJWT(this IServiceCollection services, IConfiguration configuration) 123 | { 124 | var jwtSettings = configuration.GetSection("JwtSettings"); 125 | var secretKey = Environment.GetEnvironmentVariable("SECRET"); 126 | services.AddAuthentication(opt => 127 | { 128 | opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 129 | opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 130 | }) 131 | .AddJwtBearer(options => 132 | { 133 | options.TokenValidationParameters = new TokenValidationParameters 134 | { 135 | ValidateIssuer = true, 136 | ValidateAudience = true, 137 | ValidateLifetime = true, 138 | ValidateIssuerSigningKey = true, 139 | ValidIssuer = jwtSettings.GetSection("validIssuer").Value, 140 | ValidAudience = jwtSettings.GetSection("validAudience").Value, 141 | IssuerSigningKey = new 142 | SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)) 143 | }; 144 | }); 145 | } 146 | public static void ConfigureSwagger(this IServiceCollection services) 147 | { 148 | services.AddSwaggerGen(s => 149 | { 150 | s.SwaggerDoc("v1", new OpenApiInfo 151 | { 152 | Title = "CompanyEmployee.API", 153 | Version = "v1", 154 | Description = "CompanyEmployees API by Zahra Bayat", 155 | Contact = new OpenApiContact 156 | { 157 | Name = "Zahra Bayat", 158 | Email = "BytZahra@gmail.com", 159 | Url = new Uri("https://www.linkedin.com/in/zahrabayat"), 160 | }, 161 | License = new OpenApiLicense 162 | { 163 | Name = "CompanyEmployees API ", 164 | } 165 | }); 166 | s.SwaggerDoc("v2", new OpenApiInfo 167 | { 168 | Title = "CompanyEmployee.API", 169 | Version = "v2" 170 | }); 171 | var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; 172 | var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); 173 | s.IncludeXmlComments(xmlPath); 174 | s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 175 | { 176 | In = ParameterLocation.Header, 177 | Description = "Place to add JWT with Bearer", 178 | Name = "Authorization", 179 | Type = SecuritySchemeType.ApiKey, 180 | Scheme = "Bearer" 181 | }); 182 | s.AddSecurityRequirement(new OpenApiSecurityRequirement() 183 | { 184 | { 185 | new OpenApiSecurityScheme 186 | { 187 | Reference = new OpenApiReference 188 | { 189 | Type = ReferenceType.SecurityScheme, 190 | Id = "Bearer" 191 | }, 192 | Name = "Bearer", 193 | }, 194 | new List() 195 | } 196 | }); 197 | }); 198 | } 199 | 200 | 201 | } 202 | 203 | } 204 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Entities.DataTransferObjects; 3 | using Entities.Models; 4 | 5 | namespace CompanyEmployee.API.Infrastructure 6 | { 7 | public class MappingProfile : Profile 8 | { 9 | public MappingProfile() 10 | { 11 | CreateMap() 12 | .ForMember(c => c.FullAddress, 13 | opt => opt.MapFrom(x => string.Join(' ', x.Address, x.Country))); 14 | 15 | CreateMap(); 16 | 17 | CreateMap(); 18 | CreateMap(); 19 | CreateMap().ReverseMap(); 20 | CreateMap(); 21 | CreateMap(); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Infrastructure/ModelBinders/ArrayModelBinder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.ModelBinding; 2 | using System; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | 8 | namespace CompanyEmployee.API.Infrastructure.ModelBinders 9 | { 10 | public class ArrayModelBinder : IModelBinder 11 | { 12 | public Task BindModelAsync(ModelBindingContext bindingContext) 13 | { 14 | if (!bindingContext.ModelMetadata.IsEnumerableType) 15 | { 16 | bindingContext.Result = ModelBindingResult.Failed(); 17 | 18 | return Task.CompletedTask; 19 | } 20 | 21 | var providedValue = bindingContext.ValueProvider 22 | .GetValue(bindingContext.ModelName) 23 | .ToString(); 24 | 25 | if (string.IsNullOrEmpty(providedValue)) 26 | { 27 | bindingContext.Result = ModelBindingResult.Success(null); 28 | 29 | return Task.CompletedTask; 30 | } 31 | 32 | var genericType = 33 | bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; 34 | 35 | var converter = TypeDescriptor.GetConverter(genericType); 36 | var objectArray = providedValue.Split(new[] { "," }, 37 | StringSplitOptions.RemoveEmptyEntries) 38 | .Select(x => converter.ConvertFromString(x.Trim())) 39 | .ToArray(); 40 | 41 | var guidArray = Array.CreateInstance(genericType, objectArray.Length); 42 | objectArray.CopyTo(guidArray, 0); 43 | bindingContext.Model = guidArray; 44 | 45 | bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); 46 | 47 | return Task.CompletedTask; 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210109115024_Init.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Entities; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace CompanyEmployee.API.Migrations 11 | { 12 | [DbContext(typeof(CompanyEmployeeDbContext))] 13 | [Migration("20210109115024_Init")] 14 | partial class Init 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.1"); 23 | 24 | modelBuilder.Entity("Entities.Models.Company", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("uniqueidentifier") 29 | .HasColumnName("CompanyId"); 30 | 31 | b.Property("Address") 32 | .IsRequired() 33 | .HasMaxLength(60) 34 | .HasColumnType("nvarchar(60)"); 35 | 36 | b.Property("Country") 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("Name") 40 | .IsRequired() 41 | .HasMaxLength(60) 42 | .HasColumnType("nvarchar(60)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.ToTable("Companies"); 47 | }); 48 | 49 | modelBuilder.Entity("Entities.Models.Employee", b => 50 | { 51 | b.Property("Id") 52 | .ValueGeneratedOnAdd() 53 | .HasColumnType("uniqueidentifier") 54 | .HasColumnName("EmployeeId"); 55 | 56 | b.Property("Age") 57 | .HasColumnType("int"); 58 | 59 | b.Property("CompanyId") 60 | .HasColumnType("uniqueidentifier"); 61 | 62 | b.Property("Name") 63 | .IsRequired() 64 | .HasMaxLength(30) 65 | .HasColumnType("nvarchar(30)"); 66 | 67 | b.Property("Position") 68 | .IsRequired() 69 | .HasMaxLength(20) 70 | .HasColumnType("nvarchar(20)"); 71 | 72 | b.HasKey("Id"); 73 | 74 | b.HasIndex("CompanyId"); 75 | 76 | b.ToTable("Employees"); 77 | }); 78 | 79 | modelBuilder.Entity("Entities.Models.Employee", b => 80 | { 81 | b.HasOne("Entities.Models.Company", "Company") 82 | .WithMany("Employees") 83 | .HasForeignKey("CompanyId") 84 | .OnDelete(DeleteBehavior.Cascade) 85 | .IsRequired(); 86 | 87 | b.Navigation("Company"); 88 | }); 89 | 90 | modelBuilder.Entity("Entities.Models.Company", b => 91 | { 92 | b.Navigation("Employees"); 93 | }); 94 | #pragma warning restore 612, 618 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210109115024_Init.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CompanyEmployee.API.Migrations 5 | { 6 | public partial class Init : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Companies", 12 | columns: table => new 13 | { 14 | CompanyId = table.Column(type: "uniqueidentifier", nullable: false), 15 | Name = table.Column(type: "nvarchar(60)", maxLength: 60, nullable: false), 16 | Address = table.Column(type: "nvarchar(60)", maxLength: 60, nullable: false), 17 | Country = table.Column(type: "nvarchar(max)", nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_Companies", x => x.CompanyId); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "Employees", 26 | columns: table => new 27 | { 28 | EmployeeId = table.Column(type: "uniqueidentifier", nullable: false), 29 | Name = table.Column(type: "nvarchar(30)", maxLength: 30, nullable: false), 30 | Age = table.Column(type: "int", nullable: false), 31 | Position = table.Column(type: "nvarchar(20)", maxLength: 20, nullable: false), 32 | CompanyId = table.Column(type: "uniqueidentifier", nullable: false) 33 | }, 34 | constraints: table => 35 | { 36 | table.PrimaryKey("PK_Employees", x => x.EmployeeId); 37 | table.ForeignKey( 38 | name: "FK_Employees_Companies_CompanyId", 39 | column: x => x.CompanyId, 40 | principalTable: "Companies", 41 | principalColumn: "CompanyId", 42 | onDelete: ReferentialAction.Cascade); 43 | }); 44 | 45 | migrationBuilder.CreateIndex( 46 | name: "IX_Employees_CompanyId", 47 | table: "Employees", 48 | column: "CompanyId"); 49 | } 50 | 51 | protected override void Down(MigrationBuilder migrationBuilder) 52 | { 53 | migrationBuilder.DropTable( 54 | name: "Employees"); 55 | 56 | migrationBuilder.DropTable( 57 | name: "Companies"); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210109120245_SeedData.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Entities; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace CompanyEmployee.API.Migrations 11 | { 12 | [DbContext(typeof(CompanyEmployeeDbContext))] 13 | [Migration("20210109120245_SeedData")] 14 | partial class SeedData 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.1"); 23 | 24 | modelBuilder.Entity("Entities.Models.Company", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("uniqueidentifier") 29 | .HasColumnName("CompanyId"); 30 | 31 | b.Property("Address") 32 | .IsRequired() 33 | .HasMaxLength(60) 34 | .HasColumnType("nvarchar(60)"); 35 | 36 | b.Property("Country") 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("Name") 40 | .IsRequired() 41 | .HasMaxLength(60) 42 | .HasColumnType("nvarchar(60)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.ToTable("Companies"); 47 | 48 | b.HasData( 49 | new 50 | { 51 | Id = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 52 | Address = "Tehran,Tajrish", 53 | Country = "Iran", 54 | Name = "Raveshmand_Ltd" 55 | }, 56 | new 57 | { 58 | Id = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 59 | Address = "London", 60 | Country = "English", 61 | Name = "Geeks_Ltd" 62 | }); 63 | }); 64 | 65 | modelBuilder.Entity("Entities.Models.Employee", b => 66 | { 67 | b.Property("Id") 68 | .ValueGeneratedOnAdd() 69 | .HasColumnType("uniqueidentifier") 70 | .HasColumnName("EmployeeId"); 71 | 72 | b.Property("Age") 73 | .HasColumnType("int"); 74 | 75 | b.Property("CompanyId") 76 | .HasColumnType("uniqueidentifier"); 77 | 78 | b.Property("Name") 79 | .IsRequired() 80 | .HasMaxLength(30) 81 | .HasColumnType("nvarchar(30)"); 82 | 83 | b.Property("Position") 84 | .IsRequired() 85 | .HasMaxLength(20) 86 | .HasColumnType("nvarchar(20)"); 87 | 88 | b.HasKey("Id"); 89 | 90 | b.HasIndex("CompanyId"); 91 | 92 | b.ToTable("Employees"); 93 | 94 | b.HasData( 95 | new 96 | { 97 | Id = new Guid("80abbca8-664d-4b20-b5de-024705497d4a"), 98 | Age = 26, 99 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 100 | Name = "Zahra Bayat", 101 | Position = "Backend developer" 102 | }, 103 | new 104 | { 105 | Id = new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a"), 106 | Age = 30, 107 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 108 | Name = "Ali Bayat", 109 | Position = "Backend developer" 110 | }, 111 | new 112 | { 113 | Id = new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811"), 114 | Age = 35, 115 | CompanyId = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 116 | Name = "Sara Bayat", 117 | Position = "Frontend developer" 118 | }); 119 | }); 120 | 121 | modelBuilder.Entity("Entities.Models.Employee", b => 122 | { 123 | b.HasOne("Entities.Models.Company", "Company") 124 | .WithMany("Employees") 125 | .HasForeignKey("CompanyId") 126 | .OnDelete(DeleteBehavior.Cascade) 127 | .IsRequired(); 128 | 129 | b.Navigation("Company"); 130 | }); 131 | 132 | modelBuilder.Entity("Entities.Models.Company", b => 133 | { 134 | b.Navigation("Employees"); 135 | }); 136 | #pragma warning restore 612, 618 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210109120245_SeedData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CompanyEmployee.API.Migrations 5 | { 6 | public partial class SeedData : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.InsertData( 11 | table: "Companies", 12 | columns: new[] { "CompanyId", "Address", "Country", "Name" }, 13 | values: new object[] { new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), "Tehran,Tajrish", "Iran", "Raveshmand_Ltd" }); 14 | 15 | migrationBuilder.InsertData( 16 | table: "Companies", 17 | columns: new[] { "CompanyId", "Address", "Country", "Name" }, 18 | values: new object[] { new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), "London", "English", "Geeks_Ltd" }); 19 | 20 | migrationBuilder.InsertData( 21 | table: "Employees", 22 | columns: new[] { "EmployeeId", "Age", "CompanyId", "Name", "Position" }, 23 | values: new object[] { new Guid("80abbca8-664d-4b20-b5de-024705497d4a"), 26, new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), "Zahra Bayat", "Backend developer" }); 24 | 25 | migrationBuilder.InsertData( 26 | table: "Employees", 27 | columns: new[] { "EmployeeId", "Age", "CompanyId", "Name", "Position" }, 28 | values: new object[] { new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a"), 30, new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), "Ali Bayat", "Backend developer" }); 29 | 30 | migrationBuilder.InsertData( 31 | table: "Employees", 32 | columns: new[] { "EmployeeId", "Age", "CompanyId", "Name", "Position" }, 33 | values: new object[] { new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811"), 35, new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), "Sara Bayat", "Frontend developer" }); 34 | } 35 | 36 | protected override void Down(MigrationBuilder migrationBuilder) 37 | { 38 | migrationBuilder.DeleteData( 39 | table: "Employees", 40 | keyColumn: "EmployeeId", 41 | keyValue: new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811")); 42 | 43 | migrationBuilder.DeleteData( 44 | table: "Employees", 45 | keyColumn: "EmployeeId", 46 | keyValue: new Guid("80abbca8-664d-4b20-b5de-024705497d4a")); 47 | 48 | migrationBuilder.DeleteData( 49 | table: "Employees", 50 | keyColumn: "EmployeeId", 51 | keyValue: new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a")); 52 | 53 | migrationBuilder.DeleteData( 54 | table: "Companies", 55 | keyColumn: "CompanyId", 56 | keyValue: new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3")); 57 | 58 | migrationBuilder.DeleteData( 59 | table: "Companies", 60 | keyColumn: "CompanyId", 61 | keyValue: new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870")); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210204060838_CreatingIdentityTables.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Entities; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace CompanyEmployee.API.Migrations 11 | { 12 | [DbContext(typeof(CompanyEmployeeDbContext))] 13 | [Migration("20210204060838_CreatingIdentityTables")] 14 | partial class CreatingIdentityTables 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("Entities.Models.Company", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("uniqueidentifier") 29 | .HasColumnName("CompanyId"); 30 | 31 | b.Property("Address") 32 | .IsRequired() 33 | .HasMaxLength(60) 34 | .HasColumnType("nvarchar(60)"); 35 | 36 | b.Property("Country") 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("Name") 40 | .IsRequired() 41 | .HasMaxLength(60) 42 | .HasColumnType("nvarchar(60)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.ToTable("Companies"); 47 | 48 | b.HasData( 49 | new 50 | { 51 | Id = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 52 | Address = "Tehran,Tajrish", 53 | Country = "Iran", 54 | Name = "Raveshmand_Ltd" 55 | }, 56 | new 57 | { 58 | Id = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 59 | Address = "London", 60 | Country = "English", 61 | Name = "Geeks_Ltd" 62 | }); 63 | }); 64 | 65 | modelBuilder.Entity("Entities.Models.Employee", b => 66 | { 67 | b.Property("Id") 68 | .ValueGeneratedOnAdd() 69 | .HasColumnType("uniqueidentifier") 70 | .HasColumnName("EmployeeId"); 71 | 72 | b.Property("Age") 73 | .HasColumnType("int"); 74 | 75 | b.Property("CompanyId") 76 | .HasColumnType("uniqueidentifier"); 77 | 78 | b.Property("Name") 79 | .IsRequired() 80 | .HasMaxLength(30) 81 | .HasColumnType("nvarchar(30)"); 82 | 83 | b.Property("Position") 84 | .IsRequired() 85 | .HasMaxLength(20) 86 | .HasColumnType("nvarchar(20)"); 87 | 88 | b.HasKey("Id"); 89 | 90 | b.HasIndex("CompanyId"); 91 | 92 | b.ToTable("Employees"); 93 | 94 | b.HasData( 95 | new 96 | { 97 | Id = new Guid("80abbca8-664d-4b20-b5de-024705497d4a"), 98 | Age = 26, 99 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 100 | Name = "Zahra Bayat", 101 | Position = "Backend developer" 102 | }, 103 | new 104 | { 105 | Id = new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a"), 106 | Age = 30, 107 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 108 | Name = "Ali Bayat", 109 | Position = "Backend developer" 110 | }, 111 | new 112 | { 113 | Id = new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811"), 114 | Age = 35, 115 | CompanyId = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 116 | Name = "Sara Bayat", 117 | Position = "Frontend developer" 118 | }); 119 | }); 120 | 121 | modelBuilder.Entity("Entities.Models.User", b => 122 | { 123 | b.Property("Id") 124 | .HasColumnType("nvarchar(450)"); 125 | 126 | b.Property("AccessFailedCount") 127 | .HasColumnType("int"); 128 | 129 | b.Property("ConcurrencyStamp") 130 | .IsConcurrencyToken() 131 | .HasColumnType("nvarchar(max)"); 132 | 133 | b.Property("Email") 134 | .HasMaxLength(256) 135 | .HasColumnType("nvarchar(256)"); 136 | 137 | b.Property("EmailConfirmed") 138 | .HasColumnType("bit"); 139 | 140 | b.Property("FirstName") 141 | .HasColumnType("nvarchar(max)"); 142 | 143 | b.Property("LastName") 144 | .HasColumnType("nvarchar(max)"); 145 | 146 | b.Property("LockoutEnabled") 147 | .HasColumnType("bit"); 148 | 149 | b.Property("LockoutEnd") 150 | .HasColumnType("datetimeoffset"); 151 | 152 | b.Property("NormalizedEmail") 153 | .HasMaxLength(256) 154 | .HasColumnType("nvarchar(256)"); 155 | 156 | b.Property("NormalizedUserName") 157 | .HasMaxLength(256) 158 | .HasColumnType("nvarchar(256)"); 159 | 160 | b.Property("PasswordHash") 161 | .HasColumnType("nvarchar(max)"); 162 | 163 | b.Property("PhoneNumber") 164 | .HasColumnType("nvarchar(max)"); 165 | 166 | b.Property("PhoneNumberConfirmed") 167 | .HasColumnType("bit"); 168 | 169 | b.Property("SecurityStamp") 170 | .HasColumnType("nvarchar(max)"); 171 | 172 | b.Property("TwoFactorEnabled") 173 | .HasColumnType("bit"); 174 | 175 | b.Property("UserName") 176 | .HasMaxLength(256) 177 | .HasColumnType("nvarchar(256)"); 178 | 179 | b.HasKey("Id"); 180 | 181 | b.HasIndex("NormalizedEmail") 182 | .HasDatabaseName("EmailIndex"); 183 | 184 | b.HasIndex("NormalizedUserName") 185 | .IsUnique() 186 | .HasDatabaseName("UserNameIndex") 187 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 188 | 189 | b.ToTable("AspNetUsers"); 190 | }); 191 | 192 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 193 | { 194 | b.Property("Id") 195 | .HasColumnType("nvarchar(450)"); 196 | 197 | b.Property("ConcurrencyStamp") 198 | .IsConcurrencyToken() 199 | .HasColumnType("nvarchar(max)"); 200 | 201 | b.Property("Name") 202 | .HasMaxLength(256) 203 | .HasColumnType("nvarchar(256)"); 204 | 205 | b.Property("NormalizedName") 206 | .HasMaxLength(256) 207 | .HasColumnType("nvarchar(256)"); 208 | 209 | b.HasKey("Id"); 210 | 211 | b.HasIndex("NormalizedName") 212 | .IsUnique() 213 | .HasDatabaseName("RoleNameIndex") 214 | .HasFilter("[NormalizedName] IS NOT NULL"); 215 | 216 | b.ToTable("AspNetRoles"); 217 | }); 218 | 219 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 220 | { 221 | b.Property("Id") 222 | .ValueGeneratedOnAdd() 223 | .HasColumnType("int") 224 | .UseIdentityColumn(); 225 | 226 | b.Property("ClaimType") 227 | .HasColumnType("nvarchar(max)"); 228 | 229 | b.Property("ClaimValue") 230 | .HasColumnType("nvarchar(max)"); 231 | 232 | b.Property("RoleId") 233 | .IsRequired() 234 | .HasColumnType("nvarchar(450)"); 235 | 236 | b.HasKey("Id"); 237 | 238 | b.HasIndex("RoleId"); 239 | 240 | b.ToTable("AspNetRoleClaims"); 241 | }); 242 | 243 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 244 | { 245 | b.Property("Id") 246 | .ValueGeneratedOnAdd() 247 | .HasColumnType("int") 248 | .UseIdentityColumn(); 249 | 250 | b.Property("ClaimType") 251 | .HasColumnType("nvarchar(max)"); 252 | 253 | b.Property("ClaimValue") 254 | .HasColumnType("nvarchar(max)"); 255 | 256 | b.Property("UserId") 257 | .IsRequired() 258 | .HasColumnType("nvarchar(450)"); 259 | 260 | b.HasKey("Id"); 261 | 262 | b.HasIndex("UserId"); 263 | 264 | b.ToTable("AspNetUserClaims"); 265 | }); 266 | 267 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 268 | { 269 | b.Property("LoginProvider") 270 | .HasColumnType("nvarchar(max)"); 271 | 272 | b.Property("ProviderDisplayName") 273 | .HasColumnType("nvarchar(max)"); 274 | 275 | b.Property("ProviderKey") 276 | .HasColumnType("nvarchar(max)"); 277 | 278 | b.Property("UserId") 279 | .HasColumnType("int"); 280 | 281 | b.ToTable("IdentityUserLogin"); 282 | }); 283 | 284 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 285 | { 286 | b.Property("LoginProvider") 287 | .HasColumnType("nvarchar(450)"); 288 | 289 | b.Property("ProviderKey") 290 | .HasColumnType("nvarchar(450)"); 291 | 292 | b.Property("ProviderDisplayName") 293 | .HasColumnType("nvarchar(max)"); 294 | 295 | b.Property("UserId") 296 | .IsRequired() 297 | .HasColumnType("nvarchar(450)"); 298 | 299 | b.HasKey("LoginProvider", "ProviderKey"); 300 | 301 | b.HasIndex("UserId"); 302 | 303 | b.ToTable("AspNetUserLogins"); 304 | }); 305 | 306 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 307 | { 308 | b.Property("UserId") 309 | .HasColumnType("nvarchar(450)"); 310 | 311 | b.Property("RoleId") 312 | .HasColumnType("nvarchar(450)"); 313 | 314 | b.HasKey("UserId", "RoleId"); 315 | 316 | b.HasIndex("RoleId"); 317 | 318 | b.ToTable("AspNetUserRoles"); 319 | }); 320 | 321 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 322 | { 323 | b.Property("UserId") 324 | .HasColumnType("nvarchar(450)"); 325 | 326 | b.Property("LoginProvider") 327 | .HasColumnType("nvarchar(450)"); 328 | 329 | b.Property("Name") 330 | .HasColumnType("nvarchar(450)"); 331 | 332 | b.Property("Value") 333 | .HasColumnType("nvarchar(max)"); 334 | 335 | b.HasKey("UserId", "LoginProvider", "Name"); 336 | 337 | b.ToTable("AspNetUserTokens"); 338 | }); 339 | 340 | modelBuilder.Entity("Entities.Models.Employee", b => 341 | { 342 | b.HasOne("Entities.Models.Company", "Company") 343 | .WithMany("Employees") 344 | .HasForeignKey("CompanyId") 345 | .OnDelete(DeleteBehavior.Cascade) 346 | .IsRequired(); 347 | 348 | b.Navigation("Company"); 349 | }); 350 | 351 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 352 | { 353 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 354 | .WithMany() 355 | .HasForeignKey("RoleId") 356 | .OnDelete(DeleteBehavior.Cascade) 357 | .IsRequired(); 358 | }); 359 | 360 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 361 | { 362 | b.HasOne("Entities.Models.User", null) 363 | .WithMany() 364 | .HasForeignKey("UserId") 365 | .OnDelete(DeleteBehavior.Cascade) 366 | .IsRequired(); 367 | }); 368 | 369 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 370 | { 371 | b.HasOne("Entities.Models.User", null) 372 | .WithMany() 373 | .HasForeignKey("UserId") 374 | .OnDelete(DeleteBehavior.Cascade) 375 | .IsRequired(); 376 | }); 377 | 378 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 379 | { 380 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 381 | .WithMany() 382 | .HasForeignKey("RoleId") 383 | .OnDelete(DeleteBehavior.Cascade) 384 | .IsRequired(); 385 | 386 | b.HasOne("Entities.Models.User", null) 387 | .WithMany() 388 | .HasForeignKey("UserId") 389 | .OnDelete(DeleteBehavior.Cascade) 390 | .IsRequired(); 391 | }); 392 | 393 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 394 | { 395 | b.HasOne("Entities.Models.User", null) 396 | .WithMany() 397 | .HasForeignKey("UserId") 398 | .OnDelete(DeleteBehavior.Cascade) 399 | .IsRequired(); 400 | }); 401 | 402 | modelBuilder.Entity("Entities.Models.Company", b => 403 | { 404 | b.Navigation("Employees"); 405 | }); 406 | #pragma warning restore 612, 618 407 | } 408 | } 409 | } 410 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210204060838_CreatingIdentityTables.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CompanyEmployee.API.Migrations 5 | { 6 | public partial class CreatingIdentityTables : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "AspNetRoles", 12 | columns: table => new 13 | { 14 | Id = table.Column(type: "nvarchar(450)", nullable: false), 15 | Name = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 16 | NormalizedName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 17 | ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(type: "nvarchar(450)", nullable: false), 29 | FirstName = table.Column(type: "nvarchar(max)", nullable: true), 30 | LastName = table.Column(type: "nvarchar(max)", nullable: true), 31 | UserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 32 | NormalizedUserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 33 | Email = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 34 | NormalizedEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 35 | EmailConfirmed = table.Column(type: "bit", nullable: false), 36 | PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), 37 | SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true), 38 | ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), 39 | PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true), 40 | PhoneNumberConfirmed = table.Column(type: "bit", nullable: false), 41 | TwoFactorEnabled = table.Column(type: "bit", nullable: false), 42 | LockoutEnd = table.Column(type: "datetimeoffset", nullable: true), 43 | LockoutEnabled = table.Column(type: "bit", nullable: false), 44 | AccessFailedCount = table.Column(type: "int", nullable: false) 45 | }, 46 | constraints: table => 47 | { 48 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 49 | }); 50 | 51 | migrationBuilder.CreateTable( 52 | name: "IdentityUserLogin", 53 | columns: table => new 54 | { 55 | LoginProvider = table.Column(type: "nvarchar(max)", nullable: true), 56 | ProviderKey = table.Column(type: "nvarchar(max)", nullable: true), 57 | ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), 58 | UserId = table.Column(type: "int", nullable: false) 59 | }, 60 | constraints: table => 61 | { 62 | }); 63 | 64 | migrationBuilder.CreateTable( 65 | name: "AspNetRoleClaims", 66 | columns: table => new 67 | { 68 | Id = table.Column(type: "int", nullable: false) 69 | .Annotation("SqlServer:Identity", "1, 1"), 70 | RoleId = table.Column(type: "nvarchar(450)", nullable: false), 71 | ClaimType = table.Column(type: "nvarchar(max)", nullable: true), 72 | ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) 73 | }, 74 | constraints: table => 75 | { 76 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 77 | table.ForeignKey( 78 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 79 | column: x => x.RoleId, 80 | principalTable: "AspNetRoles", 81 | principalColumn: "Id", 82 | onDelete: ReferentialAction.Cascade); 83 | }); 84 | 85 | migrationBuilder.CreateTable( 86 | name: "AspNetUserClaims", 87 | columns: table => new 88 | { 89 | Id = table.Column(type: "int", nullable: false) 90 | .Annotation("SqlServer:Identity", "1, 1"), 91 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 92 | ClaimType = table.Column(type: "nvarchar(max)", nullable: true), 93 | ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) 94 | }, 95 | constraints: table => 96 | { 97 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 98 | table.ForeignKey( 99 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 100 | column: x => x.UserId, 101 | principalTable: "AspNetUsers", 102 | principalColumn: "Id", 103 | onDelete: ReferentialAction.Cascade); 104 | }); 105 | 106 | migrationBuilder.CreateTable( 107 | name: "AspNetUserLogins", 108 | columns: table => new 109 | { 110 | LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), 111 | ProviderKey = table.Column(type: "nvarchar(450)", nullable: false), 112 | ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), 113 | UserId = table.Column(type: "nvarchar(450)", nullable: false) 114 | }, 115 | constraints: table => 116 | { 117 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 118 | table.ForeignKey( 119 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 120 | column: x => x.UserId, 121 | principalTable: "AspNetUsers", 122 | principalColumn: "Id", 123 | onDelete: ReferentialAction.Cascade); 124 | }); 125 | 126 | migrationBuilder.CreateTable( 127 | name: "AspNetUserRoles", 128 | columns: table => new 129 | { 130 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 131 | RoleId = table.Column(type: "nvarchar(450)", nullable: false) 132 | }, 133 | constraints: table => 134 | { 135 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 136 | table.ForeignKey( 137 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 138 | column: x => x.RoleId, 139 | principalTable: "AspNetRoles", 140 | principalColumn: "Id", 141 | onDelete: ReferentialAction.Cascade); 142 | table.ForeignKey( 143 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 144 | column: x => x.UserId, 145 | principalTable: "AspNetUsers", 146 | principalColumn: "Id", 147 | onDelete: ReferentialAction.Cascade); 148 | }); 149 | 150 | migrationBuilder.CreateTable( 151 | name: "AspNetUserTokens", 152 | columns: table => new 153 | { 154 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 155 | LoginProvider = table.Column(type: "nvarchar(450)", nullable: false), 156 | Name = table.Column(type: "nvarchar(450)", nullable: false), 157 | Value = table.Column(type: "nvarchar(max)", nullable: true) 158 | }, 159 | constraints: table => 160 | { 161 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 162 | table.ForeignKey( 163 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 164 | column: x => x.UserId, 165 | principalTable: "AspNetUsers", 166 | principalColumn: "Id", 167 | onDelete: ReferentialAction.Cascade); 168 | }); 169 | 170 | migrationBuilder.CreateIndex( 171 | name: "IX_AspNetRoleClaims_RoleId", 172 | table: "AspNetRoleClaims", 173 | column: "RoleId"); 174 | 175 | migrationBuilder.CreateIndex( 176 | name: "RoleNameIndex", 177 | table: "AspNetRoles", 178 | column: "NormalizedName", 179 | unique: true, 180 | filter: "[NormalizedName] IS NOT NULL"); 181 | 182 | migrationBuilder.CreateIndex( 183 | name: "IX_AspNetUserClaims_UserId", 184 | table: "AspNetUserClaims", 185 | column: "UserId"); 186 | 187 | migrationBuilder.CreateIndex( 188 | name: "IX_AspNetUserLogins_UserId", 189 | table: "AspNetUserLogins", 190 | column: "UserId"); 191 | 192 | migrationBuilder.CreateIndex( 193 | name: "IX_AspNetUserRoles_RoleId", 194 | table: "AspNetUserRoles", 195 | column: "RoleId"); 196 | 197 | migrationBuilder.CreateIndex( 198 | name: "EmailIndex", 199 | table: "AspNetUsers", 200 | column: "NormalizedEmail"); 201 | 202 | migrationBuilder.CreateIndex( 203 | name: "UserNameIndex", 204 | table: "AspNetUsers", 205 | column: "NormalizedUserName", 206 | unique: true, 207 | filter: "[NormalizedUserName] IS NOT NULL"); 208 | } 209 | 210 | protected override void Down(MigrationBuilder migrationBuilder) 211 | { 212 | migrationBuilder.DropTable( 213 | name: "AspNetRoleClaims"); 214 | 215 | migrationBuilder.DropTable( 216 | name: "AspNetUserClaims"); 217 | 218 | migrationBuilder.DropTable( 219 | name: "AspNetUserLogins"); 220 | 221 | migrationBuilder.DropTable( 222 | name: "AspNetUserRoles"); 223 | 224 | migrationBuilder.DropTable( 225 | name: "AspNetUserTokens"); 226 | 227 | migrationBuilder.DropTable( 228 | name: "IdentityUserLogin"); 229 | 230 | migrationBuilder.DropTable( 231 | name: "AspNetRoles"); 232 | 233 | migrationBuilder.DropTable( 234 | name: "AspNetUsers"); 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210204062338_AddedRolesToDb.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Entities; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | namespace CompanyEmployee.API.Migrations 11 | { 12 | [DbContext(typeof(CompanyEmployeeDbContext))] 13 | [Migration("20210204062338_AddedRolesToDb")] 14 | partial class AddedRolesToDb 15 | { 16 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .UseIdentityColumns() 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 22 | .HasAnnotation("ProductVersion", "5.0.2"); 23 | 24 | modelBuilder.Entity("Entities.Models.Company", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("uniqueidentifier") 29 | .HasColumnName("CompanyId"); 30 | 31 | b.Property("Address") 32 | .IsRequired() 33 | .HasMaxLength(60) 34 | .HasColumnType("nvarchar(60)"); 35 | 36 | b.Property("Country") 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("Name") 40 | .IsRequired() 41 | .HasMaxLength(60) 42 | .HasColumnType("nvarchar(60)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.ToTable("Companies"); 47 | 48 | b.HasData( 49 | new 50 | { 51 | Id = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 52 | Address = "Tehran,Tajrish", 53 | Country = "Iran", 54 | Name = "Raveshmand_Ltd" 55 | }, 56 | new 57 | { 58 | Id = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 59 | Address = "London", 60 | Country = "English", 61 | Name = "Geeks_Ltd" 62 | }); 63 | }); 64 | 65 | modelBuilder.Entity("Entities.Models.Employee", b => 66 | { 67 | b.Property("Id") 68 | .ValueGeneratedOnAdd() 69 | .HasColumnType("uniqueidentifier") 70 | .HasColumnName("EmployeeId"); 71 | 72 | b.Property("Age") 73 | .HasColumnType("int"); 74 | 75 | b.Property("CompanyId") 76 | .HasColumnType("uniqueidentifier"); 77 | 78 | b.Property("Name") 79 | .IsRequired() 80 | .HasMaxLength(30) 81 | .HasColumnType("nvarchar(30)"); 82 | 83 | b.Property("Position") 84 | .IsRequired() 85 | .HasMaxLength(20) 86 | .HasColumnType("nvarchar(20)"); 87 | 88 | b.HasKey("Id"); 89 | 90 | b.HasIndex("CompanyId"); 91 | 92 | b.ToTable("Employees"); 93 | 94 | b.HasData( 95 | new 96 | { 97 | Id = new Guid("80abbca8-664d-4b20-b5de-024705497d4a"), 98 | Age = 26, 99 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 100 | Name = "Zahra Bayat", 101 | Position = "Backend developer" 102 | }, 103 | new 104 | { 105 | Id = new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a"), 106 | Age = 30, 107 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 108 | Name = "Ali Bayat", 109 | Position = "Backend developer" 110 | }, 111 | new 112 | { 113 | Id = new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811"), 114 | Age = 35, 115 | CompanyId = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 116 | Name = "Sara Bayat", 117 | Position = "Frontend developer" 118 | }); 119 | }); 120 | 121 | modelBuilder.Entity("Entities.Models.User", b => 122 | { 123 | b.Property("Id") 124 | .HasColumnType("nvarchar(450)"); 125 | 126 | b.Property("AccessFailedCount") 127 | .HasColumnType("int"); 128 | 129 | b.Property("ConcurrencyStamp") 130 | .IsConcurrencyToken() 131 | .HasColumnType("nvarchar(max)"); 132 | 133 | b.Property("Email") 134 | .HasMaxLength(256) 135 | .HasColumnType("nvarchar(256)"); 136 | 137 | b.Property("EmailConfirmed") 138 | .HasColumnType("bit"); 139 | 140 | b.Property("FirstName") 141 | .HasColumnType("nvarchar(max)"); 142 | 143 | b.Property("LastName") 144 | .HasColumnType("nvarchar(max)"); 145 | 146 | b.Property("LockoutEnabled") 147 | .HasColumnType("bit"); 148 | 149 | b.Property("LockoutEnd") 150 | .HasColumnType("datetimeoffset"); 151 | 152 | b.Property("NormalizedEmail") 153 | .HasMaxLength(256) 154 | .HasColumnType("nvarchar(256)"); 155 | 156 | b.Property("NormalizedUserName") 157 | .HasMaxLength(256) 158 | .HasColumnType("nvarchar(256)"); 159 | 160 | b.Property("PasswordHash") 161 | .HasColumnType("nvarchar(max)"); 162 | 163 | b.Property("PhoneNumber") 164 | .HasColumnType("nvarchar(max)"); 165 | 166 | b.Property("PhoneNumberConfirmed") 167 | .HasColumnType("bit"); 168 | 169 | b.Property("SecurityStamp") 170 | .HasColumnType("nvarchar(max)"); 171 | 172 | b.Property("TwoFactorEnabled") 173 | .HasColumnType("bit"); 174 | 175 | b.Property("UserName") 176 | .HasMaxLength(256) 177 | .HasColumnType("nvarchar(256)"); 178 | 179 | b.HasKey("Id"); 180 | 181 | b.HasIndex("NormalizedEmail") 182 | .HasDatabaseName("EmailIndex"); 183 | 184 | b.HasIndex("NormalizedUserName") 185 | .IsUnique() 186 | .HasDatabaseName("UserNameIndex") 187 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 188 | 189 | b.ToTable("AspNetUsers"); 190 | }); 191 | 192 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 193 | { 194 | b.Property("Id") 195 | .HasColumnType("nvarchar(450)"); 196 | 197 | b.Property("ConcurrencyStamp") 198 | .IsConcurrencyToken() 199 | .HasColumnType("nvarchar(max)"); 200 | 201 | b.Property("Name") 202 | .HasMaxLength(256) 203 | .HasColumnType("nvarchar(256)"); 204 | 205 | b.Property("NormalizedName") 206 | .HasMaxLength(256) 207 | .HasColumnType("nvarchar(256)"); 208 | 209 | b.HasKey("Id"); 210 | 211 | b.HasIndex("NormalizedName") 212 | .IsUnique() 213 | .HasDatabaseName("RoleNameIndex") 214 | .HasFilter("[NormalizedName] IS NOT NULL"); 215 | 216 | b.ToTable("AspNetRoles"); 217 | 218 | b.HasData( 219 | new 220 | { 221 | Id = "c81c47b3-088e-4940-ab94-e0297e7a84fb", 222 | ConcurrencyStamp = "0d9a1a18-fb30-49ec-846f-fdb04f41c89a", 223 | Name = "Manager", 224 | NormalizedName = "MANAGER" 225 | }, 226 | new 227 | { 228 | Id = "9d9e45fd-50e5-4016-860a-5d15e605b527", 229 | ConcurrencyStamp = "0ec324a1-dba2-4786-a9b6-38285b4a9b4c", 230 | Name = "Administrator", 231 | NormalizedName = "ADMINISTRATOR" 232 | }); 233 | }); 234 | 235 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 236 | { 237 | b.Property("Id") 238 | .ValueGeneratedOnAdd() 239 | .HasColumnType("int") 240 | .UseIdentityColumn(); 241 | 242 | b.Property("ClaimType") 243 | .HasColumnType("nvarchar(max)"); 244 | 245 | b.Property("ClaimValue") 246 | .HasColumnType("nvarchar(max)"); 247 | 248 | b.Property("RoleId") 249 | .IsRequired() 250 | .HasColumnType("nvarchar(450)"); 251 | 252 | b.HasKey("Id"); 253 | 254 | b.HasIndex("RoleId"); 255 | 256 | b.ToTable("AspNetRoleClaims"); 257 | }); 258 | 259 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 260 | { 261 | b.Property("Id") 262 | .ValueGeneratedOnAdd() 263 | .HasColumnType("int") 264 | .UseIdentityColumn(); 265 | 266 | b.Property("ClaimType") 267 | .HasColumnType("nvarchar(max)"); 268 | 269 | b.Property("ClaimValue") 270 | .HasColumnType("nvarchar(max)"); 271 | 272 | b.Property("UserId") 273 | .IsRequired() 274 | .HasColumnType("nvarchar(450)"); 275 | 276 | b.HasKey("Id"); 277 | 278 | b.HasIndex("UserId"); 279 | 280 | b.ToTable("AspNetUserClaims"); 281 | }); 282 | 283 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 284 | { 285 | b.Property("LoginProvider") 286 | .HasColumnType("nvarchar(max)"); 287 | 288 | b.Property("ProviderDisplayName") 289 | .HasColumnType("nvarchar(max)"); 290 | 291 | b.Property("ProviderKey") 292 | .HasColumnType("nvarchar(max)"); 293 | 294 | b.Property("UserId") 295 | .HasColumnType("int"); 296 | 297 | b.ToTable("IdentityUserLogin"); 298 | }); 299 | 300 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 301 | { 302 | b.Property("LoginProvider") 303 | .HasColumnType("nvarchar(450)"); 304 | 305 | b.Property("ProviderKey") 306 | .HasColumnType("nvarchar(450)"); 307 | 308 | b.Property("ProviderDisplayName") 309 | .HasColumnType("nvarchar(max)"); 310 | 311 | b.Property("UserId") 312 | .IsRequired() 313 | .HasColumnType("nvarchar(450)"); 314 | 315 | b.HasKey("LoginProvider", "ProviderKey"); 316 | 317 | b.HasIndex("UserId"); 318 | 319 | b.ToTable("AspNetUserLogins"); 320 | }); 321 | 322 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 323 | { 324 | b.Property("UserId") 325 | .HasColumnType("nvarchar(450)"); 326 | 327 | b.Property("RoleId") 328 | .HasColumnType("nvarchar(450)"); 329 | 330 | b.HasKey("UserId", "RoleId"); 331 | 332 | b.HasIndex("RoleId"); 333 | 334 | b.ToTable("AspNetUserRoles"); 335 | }); 336 | 337 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 338 | { 339 | b.Property("UserId") 340 | .HasColumnType("nvarchar(450)"); 341 | 342 | b.Property("LoginProvider") 343 | .HasColumnType("nvarchar(450)"); 344 | 345 | b.Property("Name") 346 | .HasColumnType("nvarchar(450)"); 347 | 348 | b.Property("Value") 349 | .HasColumnType("nvarchar(max)"); 350 | 351 | b.HasKey("UserId", "LoginProvider", "Name"); 352 | 353 | b.ToTable("AspNetUserTokens"); 354 | }); 355 | 356 | modelBuilder.Entity("Entities.Models.Employee", b => 357 | { 358 | b.HasOne("Entities.Models.Company", "Company") 359 | .WithMany("Employees") 360 | .HasForeignKey("CompanyId") 361 | .OnDelete(DeleteBehavior.Cascade) 362 | .IsRequired(); 363 | 364 | b.Navigation("Company"); 365 | }); 366 | 367 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 368 | { 369 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 370 | .WithMany() 371 | .HasForeignKey("RoleId") 372 | .OnDelete(DeleteBehavior.Cascade) 373 | .IsRequired(); 374 | }); 375 | 376 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 377 | { 378 | b.HasOne("Entities.Models.User", null) 379 | .WithMany() 380 | .HasForeignKey("UserId") 381 | .OnDelete(DeleteBehavior.Cascade) 382 | .IsRequired(); 383 | }); 384 | 385 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 386 | { 387 | b.HasOne("Entities.Models.User", null) 388 | .WithMany() 389 | .HasForeignKey("UserId") 390 | .OnDelete(DeleteBehavior.Cascade) 391 | .IsRequired(); 392 | }); 393 | 394 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 395 | { 396 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 397 | .WithMany() 398 | .HasForeignKey("RoleId") 399 | .OnDelete(DeleteBehavior.Cascade) 400 | .IsRequired(); 401 | 402 | b.HasOne("Entities.Models.User", null) 403 | .WithMany() 404 | .HasForeignKey("UserId") 405 | .OnDelete(DeleteBehavior.Cascade) 406 | .IsRequired(); 407 | }); 408 | 409 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 410 | { 411 | b.HasOne("Entities.Models.User", null) 412 | .WithMany() 413 | .HasForeignKey("UserId") 414 | .OnDelete(DeleteBehavior.Cascade) 415 | .IsRequired(); 416 | }); 417 | 418 | modelBuilder.Entity("Entities.Models.Company", b => 419 | { 420 | b.Navigation("Employees"); 421 | }); 422 | #pragma warning restore 612, 618 423 | } 424 | } 425 | } 426 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/20210204062338_AddedRolesToDb.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace CompanyEmployee.API.Migrations 4 | { 5 | public partial class AddedRolesToDb : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.InsertData( 10 | table: "AspNetRoles", 11 | columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, 12 | values: new object[] { "c81c47b3-088e-4940-ab94-e0297e7a84fb", "0d9a1a18-fb30-49ec-846f-fdb04f41c89a", "Manager", "MANAGER" }); 13 | 14 | migrationBuilder.InsertData( 15 | table: "AspNetRoles", 16 | columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" }, 17 | values: new object[] { "9d9e45fd-50e5-4016-860a-5d15e605b527", "0ec324a1-dba2-4786-a9b6-38285b4a9b4c", "Administrator", "ADMINISTRATOR" }); 18 | } 19 | 20 | protected override void Down(MigrationBuilder migrationBuilder) 21 | { 22 | migrationBuilder.DeleteData( 23 | table: "AspNetRoles", 24 | keyColumn: "Id", 25 | keyValue: "9d9e45fd-50e5-4016-860a-5d15e605b527"); 26 | 27 | migrationBuilder.DeleteData( 28 | table: "AspNetRoles", 29 | keyColumn: "Id", 30 | keyValue: "c81c47b3-088e-4940-ab94-e0297e7a84fb"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Migrations/CompanyEmployeeDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Entities; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace CompanyEmployee.API.Migrations 10 | { 11 | [DbContext(typeof(CompanyEmployeeDbContext))] 12 | partial class CompanyEmployeeDbContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder 18 | .UseIdentityColumns() 19 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 20 | .HasAnnotation("ProductVersion", "5.0.2"); 21 | 22 | modelBuilder.Entity("Entities.Models.Company", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("uniqueidentifier") 27 | .HasColumnName("CompanyId"); 28 | 29 | b.Property("Address") 30 | .IsRequired() 31 | .HasMaxLength(60) 32 | .HasColumnType("nvarchar(60)"); 33 | 34 | b.Property("Country") 35 | .HasColumnType("nvarchar(max)"); 36 | 37 | b.Property("Name") 38 | .IsRequired() 39 | .HasMaxLength(60) 40 | .HasColumnType("nvarchar(60)"); 41 | 42 | b.HasKey("Id"); 43 | 44 | b.ToTable("Companies"); 45 | 46 | b.HasData( 47 | new 48 | { 49 | Id = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 50 | Address = "Tehran,Tajrish", 51 | Country = "Iran", 52 | Name = "Raveshmand_Ltd" 53 | }, 54 | new 55 | { 56 | Id = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 57 | Address = "London", 58 | Country = "English", 59 | Name = "Geeks_Ltd" 60 | }); 61 | }); 62 | 63 | modelBuilder.Entity("Entities.Models.Employee", b => 64 | { 65 | b.Property("Id") 66 | .ValueGeneratedOnAdd() 67 | .HasColumnType("uniqueidentifier") 68 | .HasColumnName("EmployeeId"); 69 | 70 | b.Property("Age") 71 | .HasColumnType("int"); 72 | 73 | b.Property("CompanyId") 74 | .HasColumnType("uniqueidentifier"); 75 | 76 | b.Property("Name") 77 | .IsRequired() 78 | .HasMaxLength(30) 79 | .HasColumnType("nvarchar(30)"); 80 | 81 | b.Property("Position") 82 | .IsRequired() 83 | .HasMaxLength(20) 84 | .HasColumnType("nvarchar(20)"); 85 | 86 | b.HasKey("Id"); 87 | 88 | b.HasIndex("CompanyId"); 89 | 90 | b.ToTable("Employees"); 91 | 92 | b.HasData( 93 | new 94 | { 95 | Id = new Guid("80abbca8-664d-4b20-b5de-024705497d4a"), 96 | Age = 26, 97 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 98 | Name = "Zahra Bayat", 99 | Position = "Backend developer" 100 | }, 101 | new 102 | { 103 | Id = new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a"), 104 | Age = 30, 105 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 106 | Name = "Ali Bayat", 107 | Position = "Backend developer" 108 | }, 109 | new 110 | { 111 | Id = new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811"), 112 | Age = 35, 113 | CompanyId = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 114 | Name = "Sara Bayat", 115 | Position = "Frontend developer" 116 | }); 117 | }); 118 | 119 | modelBuilder.Entity("Entities.Models.User", b => 120 | { 121 | b.Property("Id") 122 | .HasColumnType("nvarchar(450)"); 123 | 124 | b.Property("AccessFailedCount") 125 | .HasColumnType("int"); 126 | 127 | b.Property("ConcurrencyStamp") 128 | .IsConcurrencyToken() 129 | .HasColumnType("nvarchar(max)"); 130 | 131 | b.Property("Email") 132 | .HasMaxLength(256) 133 | .HasColumnType("nvarchar(256)"); 134 | 135 | b.Property("EmailConfirmed") 136 | .HasColumnType("bit"); 137 | 138 | b.Property("FirstName") 139 | .HasColumnType("nvarchar(max)"); 140 | 141 | b.Property("LastName") 142 | .HasColumnType("nvarchar(max)"); 143 | 144 | b.Property("LockoutEnabled") 145 | .HasColumnType("bit"); 146 | 147 | b.Property("LockoutEnd") 148 | .HasColumnType("datetimeoffset"); 149 | 150 | b.Property("NormalizedEmail") 151 | .HasMaxLength(256) 152 | .HasColumnType("nvarchar(256)"); 153 | 154 | b.Property("NormalizedUserName") 155 | .HasMaxLength(256) 156 | .HasColumnType("nvarchar(256)"); 157 | 158 | b.Property("PasswordHash") 159 | .HasColumnType("nvarchar(max)"); 160 | 161 | b.Property("PhoneNumber") 162 | .HasColumnType("nvarchar(max)"); 163 | 164 | b.Property("PhoneNumberConfirmed") 165 | .HasColumnType("bit"); 166 | 167 | b.Property("SecurityStamp") 168 | .HasColumnType("nvarchar(max)"); 169 | 170 | b.Property("TwoFactorEnabled") 171 | .HasColumnType("bit"); 172 | 173 | b.Property("UserName") 174 | .HasMaxLength(256) 175 | .HasColumnType("nvarchar(256)"); 176 | 177 | b.HasKey("Id"); 178 | 179 | b.HasIndex("NormalizedEmail") 180 | .HasDatabaseName("EmailIndex"); 181 | 182 | b.HasIndex("NormalizedUserName") 183 | .IsUnique() 184 | .HasDatabaseName("UserNameIndex") 185 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 186 | 187 | b.ToTable("AspNetUsers"); 188 | }); 189 | 190 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 191 | { 192 | b.Property("Id") 193 | .HasColumnType("nvarchar(450)"); 194 | 195 | b.Property("ConcurrencyStamp") 196 | .IsConcurrencyToken() 197 | .HasColumnType("nvarchar(max)"); 198 | 199 | b.Property("Name") 200 | .HasMaxLength(256) 201 | .HasColumnType("nvarchar(256)"); 202 | 203 | b.Property("NormalizedName") 204 | .HasMaxLength(256) 205 | .HasColumnType("nvarchar(256)"); 206 | 207 | b.HasKey("Id"); 208 | 209 | b.HasIndex("NormalizedName") 210 | .IsUnique() 211 | .HasDatabaseName("RoleNameIndex") 212 | .HasFilter("[NormalizedName] IS NOT NULL"); 213 | 214 | b.ToTable("AspNetRoles"); 215 | 216 | b.HasData( 217 | new 218 | { 219 | Id = "c81c47b3-088e-4940-ab94-e0297e7a84fb", 220 | ConcurrencyStamp = "0d9a1a18-fb30-49ec-846f-fdb04f41c89a", 221 | Name = "Manager", 222 | NormalizedName = "MANAGER" 223 | }, 224 | new 225 | { 226 | Id = "9d9e45fd-50e5-4016-860a-5d15e605b527", 227 | ConcurrencyStamp = "0ec324a1-dba2-4786-a9b6-38285b4a9b4c", 228 | Name = "Administrator", 229 | NormalizedName = "ADMINISTRATOR" 230 | }); 231 | }); 232 | 233 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 234 | { 235 | b.Property("Id") 236 | .ValueGeneratedOnAdd() 237 | .HasColumnType("int") 238 | .UseIdentityColumn(); 239 | 240 | b.Property("ClaimType") 241 | .HasColumnType("nvarchar(max)"); 242 | 243 | b.Property("ClaimValue") 244 | .HasColumnType("nvarchar(max)"); 245 | 246 | b.Property("RoleId") 247 | .IsRequired() 248 | .HasColumnType("nvarchar(450)"); 249 | 250 | b.HasKey("Id"); 251 | 252 | b.HasIndex("RoleId"); 253 | 254 | b.ToTable("AspNetRoleClaims"); 255 | }); 256 | 257 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 258 | { 259 | b.Property("Id") 260 | .ValueGeneratedOnAdd() 261 | .HasColumnType("int") 262 | .UseIdentityColumn(); 263 | 264 | b.Property("ClaimType") 265 | .HasColumnType("nvarchar(max)"); 266 | 267 | b.Property("ClaimValue") 268 | .HasColumnType("nvarchar(max)"); 269 | 270 | b.Property("UserId") 271 | .IsRequired() 272 | .HasColumnType("nvarchar(450)"); 273 | 274 | b.HasKey("Id"); 275 | 276 | b.HasIndex("UserId"); 277 | 278 | b.ToTable("AspNetUserClaims"); 279 | }); 280 | 281 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 282 | { 283 | b.Property("LoginProvider") 284 | .HasColumnType("nvarchar(max)"); 285 | 286 | b.Property("ProviderDisplayName") 287 | .HasColumnType("nvarchar(max)"); 288 | 289 | b.Property("ProviderKey") 290 | .HasColumnType("nvarchar(max)"); 291 | 292 | b.Property("UserId") 293 | .HasColumnType("int"); 294 | 295 | b.ToTable("IdentityUserLogin"); 296 | }); 297 | 298 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 299 | { 300 | b.Property("LoginProvider") 301 | .HasColumnType("nvarchar(450)"); 302 | 303 | b.Property("ProviderKey") 304 | .HasColumnType("nvarchar(450)"); 305 | 306 | b.Property("ProviderDisplayName") 307 | .HasColumnType("nvarchar(max)"); 308 | 309 | b.Property("UserId") 310 | .IsRequired() 311 | .HasColumnType("nvarchar(450)"); 312 | 313 | b.HasKey("LoginProvider", "ProviderKey"); 314 | 315 | b.HasIndex("UserId"); 316 | 317 | b.ToTable("AspNetUserLogins"); 318 | }); 319 | 320 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 321 | { 322 | b.Property("UserId") 323 | .HasColumnType("nvarchar(450)"); 324 | 325 | b.Property("RoleId") 326 | .HasColumnType("nvarchar(450)"); 327 | 328 | b.HasKey("UserId", "RoleId"); 329 | 330 | b.HasIndex("RoleId"); 331 | 332 | b.ToTable("AspNetUserRoles"); 333 | }); 334 | 335 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 336 | { 337 | b.Property("UserId") 338 | .HasColumnType("nvarchar(450)"); 339 | 340 | b.Property("LoginProvider") 341 | .HasColumnType("nvarchar(450)"); 342 | 343 | b.Property("Name") 344 | .HasColumnType("nvarchar(450)"); 345 | 346 | b.Property("Value") 347 | .HasColumnType("nvarchar(max)"); 348 | 349 | b.HasKey("UserId", "LoginProvider", "Name"); 350 | 351 | b.ToTable("AspNetUserTokens"); 352 | }); 353 | 354 | modelBuilder.Entity("Entities.Models.Employee", b => 355 | { 356 | b.HasOne("Entities.Models.Company", "Company") 357 | .WithMany("Employees") 358 | .HasForeignKey("CompanyId") 359 | .OnDelete(DeleteBehavior.Cascade) 360 | .IsRequired(); 361 | 362 | b.Navigation("Company"); 363 | }); 364 | 365 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 366 | { 367 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 368 | .WithMany() 369 | .HasForeignKey("RoleId") 370 | .OnDelete(DeleteBehavior.Cascade) 371 | .IsRequired(); 372 | }); 373 | 374 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 375 | { 376 | b.HasOne("Entities.Models.User", null) 377 | .WithMany() 378 | .HasForeignKey("UserId") 379 | .OnDelete(DeleteBehavior.Cascade) 380 | .IsRequired(); 381 | }); 382 | 383 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 384 | { 385 | b.HasOne("Entities.Models.User", null) 386 | .WithMany() 387 | .HasForeignKey("UserId") 388 | .OnDelete(DeleteBehavior.Cascade) 389 | .IsRequired(); 390 | }); 391 | 392 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 393 | { 394 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 395 | .WithMany() 396 | .HasForeignKey("RoleId") 397 | .OnDelete(DeleteBehavior.Cascade) 398 | .IsRequired(); 399 | 400 | b.HasOne("Entities.Models.User", null) 401 | .WithMany() 402 | .HasForeignKey("UserId") 403 | .OnDelete(DeleteBehavior.Cascade) 404 | .IsRequired(); 405 | }); 406 | 407 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 408 | { 409 | b.HasOne("Entities.Models.User", null) 410 | .WithMany() 411 | .HasForeignKey("UserId") 412 | .OnDelete(DeleteBehavior.Cascade) 413 | .IsRequired(); 414 | }); 415 | 416 | modelBuilder.Entity("Entities.Models.Company", b => 417 | { 418 | b.Navigation("Employees"); 419 | }); 420 | #pragma warning restore 612, 618 421 | } 422 | } 423 | } 424 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace CompanyEmployee.API 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:58753", 8 | "sslPort": 44370 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "CompanyEmployees": { 21 | "commandName": "Project", 22 | "launchBrowser": false, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CompanyEmployee.API/Startup.cs: -------------------------------------------------------------------------------- 1 | using CompanyEmployee.API.Infrastructure.Extensions; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.HttpOverrides; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using CompanyEmployee.API.Infrastructure.ActionFilters; 8 | using Microsoft.Extensions.Hosting; 9 | using Contracts.IServices; 10 | using Microsoft.OpenApi.Models; 11 | using Repository.DataShaping; 12 | using Entities.DataTransferObjects; 13 | using NLog; 14 | using System.IO; 15 | using AutoMapper; 16 | using Microsoft.AspNetCore.Mvc; 17 | using AspNetCoreRateLimit; 18 | using Repository; 19 | 20 | namespace CompanyEmployee.API 21 | { 22 | public class Startup 23 | { 24 | public Startup(IConfiguration configuration) 25 | { 26 | LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/nlog.config")); 27 | Configuration = configuration; 28 | } 29 | 30 | public IConfiguration Configuration { get; } 31 | 32 | public void ConfigureServices(IServiceCollection services) 33 | { 34 | services.ConfigureCors(); 35 | 36 | services.ConfigureIISIntegration(); 37 | services.ConfigureLoggerService(); 38 | services.ConfigureSqlContext(Configuration); 39 | services.ConfigureRepositoryManager(); 40 | services.AddAutoMapper(typeof(Startup)); 41 | services.Configure(options => 42 | { 43 | options.SuppressModelStateInvalidFilter = true; 44 | }); 45 | services.AddScoped(); 46 | services.AddScoped(); 47 | services.AddScoped(); 48 | services.AddScoped, DataShaper>(); 49 | services.AddScoped(); 50 | services.ConfigureVersioning(); 51 | services.ConfigureResponseCaching(); 52 | services.ConfigureHttpCacheHeaders(); 53 | services.AddMemoryCache(); 54 | services.ConfigureRateLimitingOptions(); 55 | services.AddHttpContextAccessor(); 56 | services.AddAuthentication(); 57 | services.ConfigureIdentity(); 58 | services.ConfigureJWT(Configuration); 59 | services.AddControllers(config => { 60 | config.RespectBrowserAcceptHeader = true; 61 | config.ReturnHttpNotAcceptable = true; 62 | config.CacheProfiles.Add("120SecondsDuration", new CacheProfile 63 | { 64 | Duration = 120 65 | }); 66 | }).AddNewtonsoftJson() 67 | .AddXmlDataContractSerializerFormatters() 68 | .AddCustomCSVFormatter(); 69 | 70 | services.ConfigureSwagger(); 71 | 72 | } 73 | 74 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger) 75 | { 76 | if (env.IsDevelopment()) 77 | { 78 | app.UseDeveloperExceptionPage(); 79 | app.UseSwagger(); 80 | app.UseSwaggerUI(c => 81 | { 82 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "CompanyEmployee.API v1"); 83 | c.SwaggerEndpoint("/swagger/v2/swagger.json", "CompanyEmployee.API v2"); 84 | }); 85 | 86 | } 87 | 88 | app.ConfigureExceptionHandler(logger); 89 | 90 | app.UseHttpsRedirection(); 91 | 92 | app.UseStaticFiles(); 93 | 94 | app.UseCors("CorsPolicy"); 95 | 96 | app.UseForwardedHeaders(new ForwardedHeadersOptions 97 | { 98 | ForwardedHeaders = ForwardedHeaders.All 99 | }); 100 | 101 | app.UseResponseCaching(); 102 | app.UseHttpCacheHeaders(); 103 | 104 | app.UseIpRateLimiting(); 105 | app.UseRouting(); 106 | 107 | 108 | app.UseAuthentication(); 109 | app.UseAuthorization(); 110 | 111 | app.UseEndpoints(endpoints => 112 | { 113 | endpoints.MapControllers(); 114 | }); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /CompanyEmployee.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CompanyEmployee.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "sqlConnection": "server=.; database=CompanyEmployee; Integrated Security=true" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft": "Warning", 9 | "Microsoft.Hosting.Lifetime": "Information" 10 | } 11 | }, 12 | 13 | "JwtSettings": { 14 | "validIssuer": "MicrodevAPI", 15 | "validAudience": "https://localhost:5001", 16 | "expires": 5 17 | }, 18 | "AllowedHosts": "*" 19 | } 20 | -------------------------------------------------------------------------------- /CompanyEmployee.API/nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 7 | 8 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /CompanyEmployee.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30804.86 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompanyEmployee.API", "CompanyEmployee.API\CompanyEmployee.API.csproj", "{6E70B651-2DB4-4C49-8828-09FF1989D4D6}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Contracts", "Contracts\Contracts.csproj", "{B7553F10-2ED5-4B26-B19B-FEC9ADB2C0D4}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggerService", "LoggerService\LoggerService.csproj", "{93999F51-9591-401A-BEF6-947DFE3E8279}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Entities", "Entities\Entities.csproj", "{37511F73-66B4-4A52-8063-68FA32B4E512}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repository", "Repository\Repository.csproj", "{AD5967D6-7E1B-46EF-AD62-AC795C1BF0DA}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {6E70B651-2DB4-4C49-8828-09FF1989D4D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {6E70B651-2DB4-4C49-8828-09FF1989D4D6}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {6E70B651-2DB4-4C49-8828-09FF1989D4D6}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {6E70B651-2DB4-4C49-8828-09FF1989D4D6}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {B7553F10-2ED5-4B26-B19B-FEC9ADB2C0D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {B7553F10-2ED5-4B26-B19B-FEC9ADB2C0D4}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {B7553F10-2ED5-4B26-B19B-FEC9ADB2C0D4}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {B7553F10-2ED5-4B26-B19B-FEC9ADB2C0D4}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {93999F51-9591-401A-BEF6-947DFE3E8279}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {93999F51-9591-401A-BEF6-947DFE3E8279}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {93999F51-9591-401A-BEF6-947DFE3E8279}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {93999F51-9591-401A-BEF6-947DFE3E8279}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {37511F73-66B4-4A52-8063-68FA32B4E512}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {37511F73-66B4-4A52-8063-68FA32B4E512}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {37511F73-66B4-4A52-8063-68FA32B4E512}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {37511F73-66B4-4A52-8063-68FA32B4E512}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {AD5967D6-7E1B-46EF-AD62-AC795C1BF0DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {AD5967D6-7E1B-46EF-AD62-AC795C1BF0DA}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {AD5967D6-7E1B-46EF-AD62-AC795C1BF0DA}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {AD5967D6-7E1B-46EF-AD62-AC795C1BF0DA}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {CEAD0E64-2524-4C02-83A6-2DB2218DE7B9} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /Contracts/Contracts.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Contracts/IServices/IAuthenticationManager.cs: -------------------------------------------------------------------------------- 1 | using Entities.DataTransferObjects; 2 | using System.Threading.Tasks; 3 | 4 | namespace Contracts.IServices 5 | { 6 | public interface IAuthenticationManager 7 | { 8 | Task ValidateUserAsync(UserForAuthenticationDto userForAuth); 9 | Task CreateTokenAsync(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Contracts/IServices/ICompanyRepository.cs: -------------------------------------------------------------------------------- 1 | using Entities.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | namespace Contracts.IServices 7 | { 8 | public interface ICompanyRepository 9 | { 10 | Task> GetAllCompaniesAsync(bool trackChanges); 11 | Task GetCompanyAsync(Guid companyId, bool trackChanges); 12 | void CreateCompany(Company company); 13 | Task> GetByIdsAsync(IEnumerable ids, bool trackChanges); 14 | void DeleteCompany(Company company); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Contracts/IServices/IDataShaper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Dynamic; 3 | 4 | namespace Contracts.IServices 5 | { 6 | public interface IDataShaper 7 | { 8 | IEnumerable ShapeData(IEnumerable entities, string 9 | fieldsString); 10 | ExpandoObject ShapeData(T entity, string fieldsString); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Contracts/IServices/IEmployeeRepository.cs: -------------------------------------------------------------------------------- 1 | using Entities.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | using Entities.RequestFeatures; 6 | 7 | namespace Contracts.IServices 8 | { 9 | public interface IEmployeeRepository 10 | { 11 | Task> GetEmployeesAsync(Guid companyId, bool trackChanges); 12 | Task GetEmployeeAsync(Guid companyId, Guid id, bool trackChanges); 13 | Task> GetEmployeesAsync(Guid companyId, EmployeeParameters employeeParameters, bool trackChanges); 14 | void CreateEmployeeForCompany(Guid companyId, Employee employee); 15 | void DeleteEmployee(Employee employee); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Contracts/IServices/ILoggerManager.cs: -------------------------------------------------------------------------------- 1 | namespace Contracts.IServices 2 | { 3 | public interface ILoggerManager 4 | { 5 | void LogInfo(string message); 6 | void LogWarn(string message); 7 | void LogDebug(string message); 8 | void LogError(string message); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Contracts/IServices/IRepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | 5 | namespace Contracts.IServices 6 | { 7 | public interface IRepositoryBase where T : class 8 | { 9 | IQueryable FindAll(bool trackChanges); 10 | IQueryable FindByCondition(Expression> expression, 11 | bool trackChanges); 12 | void Create(T entity); 13 | void Update(T entity); 14 | void Delete(T entity); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Contracts/IServices/IRepositoryManager.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Contracts.IServices 4 | { 5 | public interface IRepositoryManager 6 | { 7 | ICompanyRepository Company { get; } 8 | IEmployeeRepository Employee { get; } 9 | Task SaveAsync(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Entities/CompanyEmployeeDbContext.cs: -------------------------------------------------------------------------------- 1 | using Entities.Configuration; 2 | using Entities.Models; 3 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace Entities 7 | { 8 | public class CompanyEmployeeDbContext : IdentityDbContext 9 | 10 | { 11 | 12 | public CompanyEmployeeDbContext(DbContextOptions options) : base(options) 13 | { 14 | } 15 | 16 | protected override void OnModelCreating(ModelBuilder modelBuilder) 17 | { 18 | modelBuilder.ApplyConfiguration(new CompanyConfiguration()); 19 | modelBuilder.ApplyConfiguration(new EmployeeConfiguration()); 20 | modelBuilder.ApplyConfiguration(new IdentityUserLoginConfiquration()); 21 | modelBuilder.ApplyConfiguration(new RoleConfiguration()); 22 | 23 | base.OnModelCreating(modelBuilder); 24 | } 25 | 26 | public DbSet Companies { get; set; } 27 | public DbSet Employees { get; set; } 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Entities/Configuration/CompanyConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Entities.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | using System; 5 | 6 | namespace Entities.Configuration 7 | { 8 | public class CompanyConfiguration : IEntityTypeConfiguration 9 | { 10 | public void Configure(EntityTypeBuilder builder) 11 | { 12 | builder.HasData 13 | ( 14 | new Company 15 | { 16 | Id = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870"), 17 | Name = "Raveshmand_Ltd", 18 | Address = "Tehran,Tajrish", 19 | Country = "Iran" 20 | }, 21 | new Company 22 | { 23 | Id = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3"), 24 | Name = "Geeks_Ltd", 25 | Address = "London", 26 | Country = "English" 27 | } 28 | ); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Entities/Configuration/EmployeeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Entities.Models; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | using System; 5 | 6 | namespace Entities.Configuration 7 | { 8 | public class EmployeeConfiguration : IEntityTypeConfiguration 9 | { 10 | public void Configure(EntityTypeBuilder builder) 11 | { 12 | builder.HasOne("Entities.Models.Company", "Company") 13 | .WithMany("Employees") 14 | .HasForeignKey("CompanyId") 15 | .OnDelete(DeleteBehavior.Cascade) 16 | .IsRequired(); 17 | 18 | builder.HasData 19 | ( 20 | new Employee 21 | { 22 | Id = new Guid("80abbca8-664d-4b20-b5de-024705497d4a"), 23 | Name = "Zahra Bayat", 24 | Age = 26, 25 | Position = "Backend developer", 26 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870") 27 | }, 28 | new Employee 29 | { 30 | Id = new Guid("86dba8c0-d178-41e7-938c-ed49778fb52a"), 31 | Name = "Ali Bayat", 32 | Age = 30, 33 | Position = "Backend developer", 34 | CompanyId = new Guid("c9d4c053-49b6-410c-bc78-2d54a9991870") 35 | }, 36 | new Employee 37 | { 38 | Id = new Guid("021ca3c1-0deb-4afd-ae94-2159a8479811"), 39 | Name = "Sara Bayat", 40 | Age = 35, 41 | Position = "Frontend developer", 42 | CompanyId = new Guid("3d490a70-94ce-4d15-9494-5248280c2ce3") 43 | } 44 | ); 45 | } 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Entities/Configuration/IdentityUserLoginConfiquration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace Entities.Configuration 6 | { 7 | public class IdentityUserLoginConfiquration : IEntityTypeConfiguration> 8 | { 9 | public void Configure(EntityTypeBuilder> builder) 10 | { 11 | builder.HasNoKey(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Entities/Configuration/RoleConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace Entities.Configuration 6 | { 7 | public class RoleConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasData( 12 | new IdentityRole 13 | { 14 | Name = "Manager", 15 | NormalizedName = "MANAGER" 16 | }, 17 | new IdentityRole 18 | { 19 | Name = "Administrator", 20 | NormalizedName = "ADMINISTRATOR" 21 | } 22 | ); 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/CompanyDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public class CompanyDto 6 | { 7 | public Guid Id { get; set; } 8 | public string Name { get; set; } 9 | public string FullAddress { get; set; } 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/CompanyForCreationDto.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace Entities.DataTransferObjects 5 | { 6 | public class CompanyForCreationDto 7 | { 8 | [Required(ErrorMessage = "Company name is a required field.")] 9 | [MaxLength(30, ErrorMessage = "Maximum length for the name is 30 characters.")] 10 | public string Name { get; set; } 11 | 12 | [Required(ErrorMessage = "Company address is a required field.")] 13 | [MaxLength(100, ErrorMessage = "Maximum length for the address is 100 characters.")] 14 | public string Address { get; set; } 15 | 16 | [Required(ErrorMessage = "Company country is a required field.")] 17 | [MaxLength(50, ErrorMessage = "Maximum length for the country is 50 characters.")] 18 | public string Country { get; set; } 19 | 20 | public IEnumerable Employees { get; set; } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/CompanyForUpdateDto.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public class CompanyForUpdateDto 6 | { 7 | public string Name { get; set; } 8 | public string Address { get; set; } 9 | public string Country { get; set; } 10 | public IEnumerable Employees { get; set; } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/EmployeeDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public class EmployeeDto 6 | { 7 | public Guid Id { get; set; } 8 | public string Name { get; set; } 9 | public int Age { get; set; } 10 | public string Position { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/EmployeeForCreationDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public class EmployeeForCreationDto: EmployeeForManipulationDto 6 | { 7 | 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/EmployeeForManipulationDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public abstract class EmployeeForManipulationDto 6 | { 7 | [Required(ErrorMessage = "Employee name is a required field.")] 8 | [MaxLength(30, ErrorMessage = "Maximum length for the Name is 30 characters.")] 9 | public string Name { get; set; } 10 | 11 | [Range(18, int.MaxValue, ErrorMessage = "Age is required and it can't be lower than 18")] 12 | public int Age { get; set; } 13 | 14 | [Required(ErrorMessage = "Position is a required field.")] 15 | [MaxLength(20, ErrorMessage = "Maximum length for the Position is 20 characters.")] 16 | public string Position { get; set; } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/EmployeeForUpdateDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public class EmployeeForUpdateDto: EmployeeForManipulationDto 6 | { 7 | 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/UserForAuthenticationDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Entities.DataTransferObjects 4 | { 5 | public class UserForAuthenticationDto 6 | { 7 | [Required(ErrorMessage = "User name is required")] 8 | public string UserName { get; set; } 9 | [Required(ErrorMessage = "Password name is required")] 10 | public string Password { get; set; } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Entities/DataTransferObjects/UserForRegistrationDto.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace Entities.DataTransferObjects 5 | { 6 | public class UserForRegistrationDto 7 | { 8 | public string FirstName { get; set; } 9 | public string LastName { get; set; } 10 | [Required(ErrorMessage = "Username is required")] 11 | public string UserName { get; set; } 12 | [Required(ErrorMessage = "Password is required")] 13 | public string Password { get; set; } 14 | public string Email { get; set; } 15 | public string PhoneNumber { get; set; } 16 | public ICollection Roles { get; set; } 17 | } 18 | 19 | } 20 | 21 | -------------------------------------------------------------------------------- /Entities/Entities.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Entities/ErrorModel/ErrorDetails.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Entities.ErrorModel 4 | { 5 | public class ErrorDetails 6 | { 7 | public int StatusCode { get; set; } 8 | public string Message { get; set; } 9 | public override string ToString() => JsonConvert.SerializeObject(this); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Entities/Models/Company.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | 6 | namespace Entities.Models 7 | { 8 | public class Company 9 | { 10 | [Column("CompanyId")] 11 | public Guid Id { get; set; } 12 | 13 | [Required(ErrorMessage = "Company name is a required field.")] 14 | [MaxLength(60, ErrorMessage = "Maximum length for the Name is 60 characters.")] 15 | public string Name { get; set; } 16 | 17 | [Required(ErrorMessage = "Company address is a required field.")] 18 | [MaxLength(60, ErrorMessage = "Maximum length for the Address is 60 characte")] 19 | public string Address { get; set; } 20 | 21 | public string Country { get; set; } 22 | 23 | public ICollection Employees { get; set; } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Entities/Models/Employee.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace Entities.Models 6 | { 7 | public class Employee 8 | { 9 | [Column("EmployeeId")] 10 | public Guid Id { get; set; } 11 | 12 | [Required(ErrorMessage = "Employee name is a required field.")] 13 | [MaxLength(30, ErrorMessage = "Maximum length for the Name is 30 characters.")] 14 | public string Name { get; set; } 15 | 16 | [Required(ErrorMessage = "Age is a required field.")] 17 | public int Age { get; set; } 18 | 19 | [Required(ErrorMessage = "Position is a required field.")] 20 | [MaxLength(20, ErrorMessage = "Maximum length for the Position is 20 characters.")] 21 | public string Position { get; set; } 22 | 23 | [ForeignKey(nameof(Company))] 24 | public Guid CompanyId { get; set; } 25 | 26 | public Company Company { get; set; } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Entities/Models/User.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace Entities.Models 4 | { 5 | public class User : IdentityUser 6 | { 7 | public string FirstName { get; set; } 8 | public string LastName { get; set; } 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Entities/RequestFeatures/MetaData.cs: -------------------------------------------------------------------------------- 1 | namespace Entities.RequestFeatures 2 | { 3 | public class MetaData 4 | { 5 | public int CurrentPage { get; set; } 6 | public int TotalPages { get; set; } 7 | public int PageSize { get; set; } 8 | public int TotalCount { get; set; } 9 | public bool HasPrevious => CurrentPage > 1; 10 | public bool HasNext => CurrentPage < TotalPages; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Entities/RequestFeatures/PagedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Entities.RequestFeatures 6 | { 7 | public class PagedList : List 8 | { 9 | public MetaData MetaData { get; set; } 10 | public PagedList(List items, int count, int pageNumber, int pageSize) 11 | { 12 | MetaData = new MetaData 13 | { 14 | TotalCount = count, 15 | PageSize = pageSize, 16 | CurrentPage = pageNumber, 17 | TotalPages = (int)Math.Ceiling(count / (double)pageSize) 18 | }; 19 | 20 | AddRange(items); 21 | } 22 | 23 | public static PagedList ToPagedList(IEnumerable source, int pageNumber, int pageSize) 24 | { 25 | var count = source.Count(); 26 | 27 | var items = source 28 | .Skip((pageNumber - 1) * pageSize) 29 | .Take(pageSize).ToList(); 30 | 31 | return new PagedList(items, count, pageNumber, pageSize); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Entities/RequestFeatures/RequestParameters.cs: -------------------------------------------------------------------------------- 1 | namespace Entities.RequestFeatures 2 | { 3 | public abstract class RequestParameters 4 | { 5 | const int maxPageSize = 50; 6 | public int PageNumber { get; set; } = 1; 7 | private int _pageSize = 10; 8 | public int PageSize 9 | { 10 | get 11 | { 12 | return _pageSize; 13 | } 14 | set 15 | { 16 | _pageSize = (value > maxPageSize) ? maxPageSize : value; 17 | } 18 | } 19 | 20 | public string OrderBy { get; set; } 21 | public string Fields { get; set; } 22 | } 23 | 24 | public class EmployeeParameters : RequestParameters 25 | { 26 | public EmployeeParameters() 27 | { 28 | OrderBy = "name"; 29 | } 30 | public uint MinAge { get; set; } 31 | public uint MaxAge { get; set; } = int.MaxValue; 32 | public bool ValidAgeRange => MaxAge > MinAge; 33 | public string SearchTerm { get; set; } 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /LoggerService/LoggerManager.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using NLog; 3 | 4 | namespace LoggerService 5 | { 6 | public class LoggerManager : ILoggerManager 7 | { 8 | private static ILogger logger = LogManager.GetCurrentClassLogger(); 9 | public LoggerManager() 10 | { 11 | } 12 | 13 | public void LogDebug(string message) 14 | { 15 | logger.Debug(message); 16 | } 17 | 18 | public void LogError(string message) 19 | { 20 | logger.Error(message); 21 | } 22 | 23 | public void LogInfo(string message) 24 | { 25 | logger.Info(message); 26 | } 27 | 28 | public void LogWarn(string message) 29 | { 30 | logger.Warn(message); 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /LoggerService/LoggerService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Give a Star! :star: 2 | If you like this project, learn something or you are using it in your applications, please give it a star. Thanks! 3 | 4 | # ASP.NET Core 5.0 WebAPI 5 | 6 | Welcome to the Git repo that is associated with the book 7 | **[ASP.NET Core 5.0 WebAPI](https://github.com/ZahraBayatgh/)** 8 | published by [LinkedIn](https://www.linkedin.com/in/zahrabayat/). 9 | This book details how to use ASP.NET Core 5.0 WebAPI to Enterprise real world application in [.NET Core](https://www.microsoft.com/net) applications. 10 | 11 | This Git repo contains all the code in the book, plus an 12 | [free pdf book](https://github.com/ZahraBayatgh/ASP.NET-Core-5.0-Web-API/blob/master/ASP.NETCore5.0WebAPI.pdf) 13 | that I wrote, in persian. 14 | 15 | | ASP.NET Core 5.0 WebAPI | 16 | | ------------| 17 | | [![](img/ASPNETCore5.0WebAPI.jpg)](https://github.com/ZahraBayatgh/ASP.NET-Core-5.0-Web-API/blob/master/ASP.NETCore5.0WebAPI.pdf) | [![](img/ASPNETCore5.0WebAPI.jpg)](https://aka.ms/dockerlifecycleebook) | [![](img/ASPNETCore5.0WebAPI.jpg)](https://github.com/ZahraBayatgh/ASP.NET-Core-5.0-Web-API/blob/master/ASP.NETCore5.0WebAPI.pdf) | 18 | | **Download .PDF** 19 | -------------------------------------------------------------------------------- /Repository/AuthenticationManager.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Entities.DataTransferObjects; 3 | using Entities.Models; 4 | using Microsoft.AspNetCore.Identity; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.IdentityModel.Tokens; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.IdentityModel.Tokens.Jwt; 10 | using System.Security.Claims; 11 | using System.Text; 12 | using System.Threading.Tasks; 13 | 14 | namespace Repository 15 | { 16 | public class AuthenticationManager : IAuthenticationManager 17 | { 18 | private readonly UserManager _userManager; 19 | private readonly IConfiguration _configuration; 20 | private User _user; 21 | public AuthenticationManager(UserManager userManager, IConfiguration configuration) 22 | { 23 | _userManager = userManager; 24 | _configuration = configuration; 25 | } 26 | public async Task ValidateUserAsync(UserForAuthenticationDto userForAuth) 27 | { 28 | _user = await _userManager.FindByNameAsync(userForAuth.UserName); 29 | 30 | return (_user != null && await _userManager.CheckPasswordAsync(_user, 31 | userForAuth.Password)); 32 | } 33 | 34 | public async Task CreateTokenAsync() 35 | { 36 | var signingCredentials = GetSigningCredentials(); 37 | var claims = await GetClaims(); 38 | var tokenOptions = GenerateTokenOptions(signingCredentials, claims); 39 | 40 | return new JwtSecurityTokenHandler().WriteToken(tokenOptions); 41 | } 42 | 43 | private SigningCredentials GetSigningCredentials() 44 | { 45 | var key = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SECRET")); 46 | var secret = new SymmetricSecurityKey(key); 47 | 48 | return new SigningCredentials(secret, SecurityAlgorithms.HmacSha256); 49 | } 50 | 51 | private async Task> GetClaims() 52 | { 53 | var claims = new List 54 | { 55 | new Claim(ClaimTypes.Name, _user.UserName) 56 | }; 57 | var roles = await _userManager.GetRolesAsync(_user); 58 | 59 | foreach (var role in roles) 60 | { 61 | claims.Add(new Claim(ClaimTypes.Role, role)); 62 | } 63 | 64 | return claims; 65 | } 66 | 67 | private JwtSecurityToken GenerateTokenOptions(SigningCredentials 68 | signingCredentials, List claims) 69 | { 70 | var jwtSettings = _configuration.GetSection("JwtSettings"); 71 | var tokenOptions = new JwtSecurityToken 72 | ( 73 | issuer: jwtSettings.GetSection("validIssuer").Value, 74 | audience: jwtSettings.GetSection("validAudience").Value, 75 | claims: claims, 76 | expires: 77 | DateTime.Now.AddMinutes(Convert.ToDouble(jwtSettings.GetSection("expires").Value)), 78 | signingCredentials: signingCredentials 79 | ); 80 | 81 | return tokenOptions; 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /Repository/DataShaping/DataShaper.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Dynamic; 5 | using System.Linq; 6 | using System.Reflection; 7 | 8 | namespace Repository.DataShaping 9 | { 10 | public class DataShaper : IDataShaper where T : class 11 | { 12 | public PropertyInfo[] Properties { get; set; } 13 | public DataShaper() 14 | { 15 | Properties = typeof(T).GetProperties(BindingFlags.Public | 16 | BindingFlags.Instance); 17 | } 18 | 19 | public IEnumerable ShapeData(IEnumerable entities, string fieldsString) 20 | { 21 | var requiredProperties = GetRequiredProperties(fieldsString); 22 | 23 | return FetchData(entities, requiredProperties); 24 | } 25 | 26 | public ExpandoObject ShapeData(T entity, string fieldsString) 27 | { 28 | var requiredProperties = GetRequiredProperties(fieldsString); 29 | 30 | return FetchDataForEntity(entity, requiredProperties); 31 | } 32 | 33 | private IEnumerable GetRequiredProperties(string fieldsString) 34 | { 35 | var requiredProperties = new List(); 36 | if (!string.IsNullOrWhiteSpace(fieldsString)) 37 | { 38 | var fields = fieldsString.Split(',', 39 | StringSplitOptions.RemoveEmptyEntries); 40 | 41 | foreach (var field in fields) 42 | { 43 | var property = Properties 44 | .FirstOrDefault(pi => pi.Name.Equals(field.Trim(), 45 | StringComparison.InvariantCultureIgnoreCase)); 46 | 47 | if (property == null) 48 | continue; 49 | 50 | requiredProperties.Add(property); 51 | } 52 | } 53 | else 54 | { 55 | requiredProperties = Properties.ToList(); 56 | } 57 | 58 | return requiredProperties; 59 | } 60 | 61 | private IEnumerable FetchData(IEnumerable entities, 62 | IEnumerable requiredProperties) 63 | { 64 | var shapedData = new List(); 65 | 66 | foreach (var entity in entities) 67 | { 68 | var shapedObject = FetchDataForEntity(entity, requiredProperties); 69 | 70 | shapedData.Add(shapedObject); 71 | } 72 | 73 | return shapedData; 74 | } 75 | 76 | private ExpandoObject FetchDataForEntity(T entity, IEnumerable requiredProperties) 77 | { 78 | var shapedObject = new ExpandoObject(); 79 | 80 | foreach (var property in requiredProperties) 81 | { 82 | var objectPropertyValue = property.GetValue(entity); 83 | 84 | shapedObject.TryAdd(property.Name, objectPropertyValue); 85 | } 86 | 87 | return shapedObject; 88 | } 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /Repository/Extensions/RepositoryEmployeeExtensions.cs: -------------------------------------------------------------------------------- 1 | using Entities.Models; 2 | using System; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using System.Linq.Dynamic.Core; 7 | 8 | namespace Repository.Extensions 9 | { 10 | public static class RepositoryEmployeeExtensions 11 | { 12 | public static IQueryable FilterEmployees(this IQueryable employees, uint minAge, uint maxAge) => 13 | employees.Where(e => (e.Age >= minAge && e.Age <= maxAge)); 14 | 15 | public static IQueryable Search(this IQueryable employees, string searchTerm) 16 | { 17 | if (string.IsNullOrWhiteSpace(searchTerm)) 18 | return employees; 19 | 20 | var lowerCaseTerm = searchTerm.Trim().ToLower(); 21 | 22 | return employees.Where(e => e.Name.ToLower().Contains(lowerCaseTerm)); 23 | } 24 | 25 | public static IQueryable Sort(this IQueryable employees, string orderByQueryString) 26 | { 27 | if (string.IsNullOrWhiteSpace(orderByQueryString)) 28 | return employees.OrderBy(e => e.Name); 29 | 30 | var orderParams = orderByQueryString.Trim().Split(','); 31 | var propertyInfos = typeof(Employee).GetProperties(BindingFlags.Public | 32 | BindingFlags.Instance); 33 | 34 | var orderQueryBuilder = new StringBuilder(); 35 | 36 | foreach (var param in orderParams) 37 | { 38 | if (string.IsNullOrWhiteSpace(param)) 39 | continue; 40 | 41 | var propertyFromQueryName = param.Split(" ")[0]; 42 | var objectProperty = propertyInfos.FirstOrDefault(pi => 43 | 44 | pi.Name.Equals(propertyFromQueryName, StringComparison.InvariantCultureIgnoreCase)); 45 | 46 | if (objectProperty == null) 47 | continue; 48 | 49 | var direction = param.EndsWith(" desc") ? "descending" : "ascending"; 50 | orderQueryBuilder.Append($"{objectProperty.Name.ToString()} {direction}, "); 51 | } 52 | 53 | var orderQuery = orderQueryBuilder.ToString().TrimEnd(',', ' '); 54 | 55 | if (string.IsNullOrWhiteSpace(orderQuery)) 56 | return employees.OrderBy(e => e.Name); 57 | 58 | return employees.OrderBy(orderQuery); 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /Repository/Repositories/CompanyRepository.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Entities; 3 | using Entities.Models; 4 | using Microsoft.EntityFrameworkCore; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace Repository.Repositories 11 | { 12 | public class CompanyRepository : RepositoryBase, ICompanyRepository 13 | { 14 | public CompanyRepository(CompanyEmployeeDbContext companyEmployeeDbContext) : base(companyEmployeeDbContext) 15 | { 16 | } 17 | 18 | public async Task> GetAllCompaniesAsync(bool trackChanges) => 19 | await FindAll(trackChanges) 20 | .OrderBy(c => c.Name) 21 | .ToListAsync(); 22 | 23 | public async Task GetCompanyAsync(Guid companyId, bool trackChanges) => 24 | await FindByCondition(c => c.Id.Equals(companyId), trackChanges) 25 | .SingleOrDefaultAsync(); 26 | 27 | public async Task> GetByIdsAsync(IEnumerable ids, bool 28 | trackChanges) => 29 | await FindByCondition(x => ids.Contains(x.Id), trackChanges) 30 | .ToListAsync(); 31 | 32 | public void CreateCompany(Company company) => Create(company); 33 | 34 | public void DeleteCompany(Company company) 35 | { 36 | Delete(company); 37 | } 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Repository/Repositories/EmployeeRepository.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Entities; 3 | using Entities.Models; 4 | using Entities.RequestFeatures; 5 | using Microsoft.EntityFrameworkCore; 6 | using Repository.Extensions; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading.Tasks; 11 | 12 | namespace Repository.Repositories 13 | { 14 | public class EmployeeRepository : RepositoryBase, IEmployeeRepository 15 | { 16 | 17 | public EmployeeRepository(CompanyEmployeeDbContext companyEmployeeDbContext) : base(companyEmployeeDbContext) 18 | { 19 | } 20 | public async Task> GetEmployeesAsync(Guid companyId, bool trackChanges) => 21 | await FindAll(trackChanges) 22 | .OrderBy(c => c.Name) 23 | .ToListAsync(); 24 | 25 | public async Task GetEmployeeAsync(Guid companyId, Guid id, bool trackChanges) => 26 | await FindByCondition(e => e.CompanyId.Equals(companyId) && e.Id.Equals(id), trackChanges).SingleOrDefaultAsync(); 27 | 28 | public async Task> GetEmployeesAsync(Guid companyId, EmployeeParameters employeeParameters, bool trackChanges) 29 | { 30 | var employees = await FindByCondition(e => e.CompanyId.Equals(companyId), 31 | trackChanges) 32 | .FilterEmployees(employeeParameters.MinAge, employeeParameters.MaxAge) 33 | .Search(employeeParameters.SearchTerm) 34 | .Sort(employeeParameters.OrderBy) 35 | .ToListAsync(); 36 | 37 | return PagedList 38 | .ToPagedList(employees, employeeParameters.PageNumber, 39 | employeeParameters.PageSize); 40 | } 41 | 42 | 43 | 44 | public void CreateEmployeeForCompany(Guid companyId, Employee employee) 45 | { 46 | employee.CompanyId = companyId; 47 | Create(employee); 48 | } 49 | 50 | public void DeleteEmployee(Employee employee) 51 | { 52 | Delete(employee); 53 | } 54 | 55 | 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Repository/Repositories/RepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using Entities; 3 | using Microsoft.EntityFrameworkCore; 4 | using System; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | 8 | namespace Repository.Repositories 9 | { 10 | public abstract class RepositoryBase : IRepositoryBase where T : class 11 | { 12 | protected CompanyEmployeeDbContext _companyEmployeeDbContext; 13 | public RepositoryBase(CompanyEmployeeDbContext companyEmployeeDbContext) 14 | { 15 | _companyEmployeeDbContext = companyEmployeeDbContext; 16 | } 17 | public IQueryable FindAll(bool trackChanges) => 18 | !trackChanges ? 19 | _companyEmployeeDbContext.Set() 20 | .AsNoTracking() : 21 | _companyEmployeeDbContext.Set(); 22 | 23 | public IQueryable FindByCondition(Expression> expression, 24 | bool trackChanges) => 25 | !trackChanges ? 26 | _companyEmployeeDbContext.Set() 27 | .Where(expression) 28 | .AsNoTracking() : 29 | _companyEmployeeDbContext.Set() 30 | .Where(expression); 31 | 32 | public void Create(T entity) => _companyEmployeeDbContext.Set().Add(entity); 33 | 34 | public void Update(T entity) => _companyEmployeeDbContext.Set().Update(entity); 35 | 36 | public void Delete(T entity) => _companyEmployeeDbContext.Set().Remove(entity); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Repository/Repositories/RepositoryManager.cs: -------------------------------------------------------------------------------- 1 | using Contracts.IServices; 2 | using System.Threading.Tasks; 3 | using Entities; 4 | 5 | namespace Repository.Repositories 6 | { 7 | public class RepositoryManager : IRepositoryManager 8 | { 9 | private CompanyEmployeeDbContext _repositoryContext; 10 | private ICompanyRepository _companyRepository; 11 | private IEmployeeRepository _employeeRepository; 12 | 13 | public RepositoryManager(CompanyEmployeeDbContext repositoryContext) 14 | { 15 | _repositoryContext = repositoryContext; 16 | } 17 | 18 | public ICompanyRepository Company 19 | { 20 | get 21 | { 22 | if (_companyRepository == null) 23 | _companyRepository = new CompanyRepository(_repositoryContext); 24 | 25 | return _companyRepository; 26 | } 27 | } 28 | 29 | public IEmployeeRepository Employee 30 | { 31 | get 32 | { 33 | if (_employeeRepository == null) 34 | _employeeRepository = new EmployeeRepository(_repositoryContext); 35 | 36 | return _employeeRepository; 37 | } 38 | } 39 | 40 | public Task SaveAsync() => _repositoryContext.SaveChangesAsync(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Repository/Repository.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /img/ASPNETCore5.0WebAPI.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZahraBayatgh/ASP.NET-Core-5.0-Web-API/94535af56e7664b66eb04449fdced86f0a75a959/img/ASPNETCore5.0WebAPI.jpg --------------------------------------------------------------------------------