├── .gitattributes ├── .gitignore ├── Business ├── Abstract │ ├── IAuthService.cs │ ├── ICategoryService.cs │ ├── IProductService.cs │ └── IUserService.cs ├── Business.csproj ├── BusinessAspects │ └── Autofac │ │ └── SecuredOperation.cs ├── CCS │ ├── DatabaseLogger.cs │ ├── FileLogger.cs │ └── ILogger.cs ├── Concrete │ ├── AuthManager.cs │ ├── CategoryManager.cs │ ├── ProductManager.cs │ └── UserManager.cs ├── Constants │ └── Messages.cs ├── DependencyResolvers │ └── Autofac │ │ └── AutofacBusinessModule.cs └── ValidationRules │ └── FluentValidation │ └── ProductValidator.cs ├── ConsoleUI ├── ConsoleUI.csproj └── Program.cs ├── Core ├── Aspects │ └── Autofac │ │ ├── Caching │ │ ├── CacheAspect.cs │ │ └── CacheRemoveAspect.cs │ │ ├── Performance │ │ └── PerformanceAspect.cs │ │ ├── Transaction │ │ └── TransactionScopeAspect.cs │ │ └── Validation │ │ ├── ValidationAspect.cs │ │ └── VallidationAspect.cs ├── Core.csproj ├── CrossCuttingConcerns │ ├── Caching │ │ ├── ICacheManager.cs │ │ └── Microsoft │ │ │ └── MemoryCacheManager.cs │ └── Validation │ │ └── ValidationTool.cs ├── DataAccess │ ├── EntityFramework │ │ └── EfEntityRepositoryBase.cs │ └── IEntityRepository.cs ├── DependencyResolvers │ └── CoreModule.cs ├── Entities │ ├── Concrete │ │ ├── OperationClaim.cs │ │ ├── User.cs │ │ └── UserOperationClaim.cs │ ├── IDto.cs │ └── IEntity.cs ├── Extensions │ ├── ClaimExtensions.cs │ ├── ClaimsPrincipalExtensions.cs │ ├── ErrorDetails.cs │ ├── ExceptionMiddleware.cs │ ├── ExceptionMiddlewareExtensions.cs │ └── ServiceCollectionExtensions.cs └── Utilities │ ├── Business │ └── BusinessRules.cs │ ├── Interceptors │ ├── AspectInterceptorSelector.cs │ ├── MethodInterception.cs │ └── MethodInterceptionBaseAttribute.cs │ ├── IoC │ ├── ICoreModule.cs │ └── ServiceTool.cs │ ├── Results │ ├── DataResult.cs │ ├── ErrorDataResult.cs │ ├── ErrorResult.cs │ ├── IDataResult.cs │ ├── IResult.cs │ ├── Result.cs │ ├── SuccessDataResult.cs │ └── SuccessResult.cs │ └── Security │ ├── Encryption │ ├── SecurityKeyHelper.cs │ └── SigningCredentialsHelper.cs │ ├── Hashing │ └── HashingHelper.cs │ └── JWT │ ├── AccessToken.cs │ ├── ITokenHelper.cs │ ├── JwtHelper.cs │ └── TokenOptions.cs ├── DataAccess ├── Abstract │ ├── ICategoryDal.cs │ ├── ICustomerDal.cs │ ├── IOrderDal.cs │ ├── IProductDal.cs │ └── IUserDal.cs ├── Concrete │ ├── EntityFramework │ │ ├── EfCategoryDal.cs │ │ ├── EfOrderDal.cs │ │ ├── EfProductDal.cs │ │ ├── EfUserDal.cs │ │ └── NorthwindContext.cs │ └── InMemory │ │ └── InMemoryProductDal.cs └── DataAccess.csproj ├── Entities ├── Concrete │ ├── Category.cs │ ├── Customer.cs │ ├── Order.cs │ └── Product.cs ├── DTOs │ ├── ProductDetailDTO.cs │ ├── UserForLoginDto.cs │ └── UserForRegisterDto.cs └── Entities.csproj ├── MyFinalProject.sln └── WebAPI ├── Controllers ├── AuthController.cs ├── CategoriesController.cs ├── ProductsController.cs └── WeatherForecastController.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Startup.cs ├── WeatherForecast.cs ├── WebAPI.csproj ├── appsettings.Development.json └── appsettings.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /Business/Abstract/IAuthService.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities.Concrete; 2 | using Core.Utilities.Results; 3 | using Core.Utilities.Security.JWT; 4 | using Entities.DTOs; 5 | using System; 6 | using System.Text; 7 | 8 | namespace Business.Abstract 9 | { 10 | 11 | public interface IAuthService 12 | { 13 | IDataResult Register(UserForRegisterDto userForRegisterDto, string password); 14 | IDataResult Login(UserForLoginDto userForLoginDto); 15 | IResult UserExists(string email); 16 | IDataResult CreateAccessToken(User user); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Business/Abstract/ICategoryService.cs: -------------------------------------------------------------------------------- 1 | using Core.Utilities.Results; 2 | using Entities.Concrete; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Business.Abstract 8 | { 9 | public interface ICategoryService 10 | { 11 | IDataResult> GetAll(); 12 | IDataResult GetById(int categoryId); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Business/Abstract/IProductService.cs: -------------------------------------------------------------------------------- 1 | using Core.Utilities.Results; 2 | using Entities.Concrete; 3 | using Entities.DTOs; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace Business.Abstract 9 | { 10 | public interface IProductService 11 | { 12 | IDataResult> GetAll(); 13 | IDataResult> GetAllByCategoryId(int id); 14 | IDataResult> GetByUnitPrice(decimal min, decimal max); 15 | IDataResult> GetProductDetails(); 16 | IDataResult GetById(int productId); 17 | IResult Add(Product product); 18 | IResult Update(Product product); 19 | IResult AddTransactionalTest(Product product); 20 | 21 | //RESTFUL --> HTTP --> 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Business/Abstract/IUserService.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities.Concrete; 2 | using System.Collections.Generic; 3 | 4 | namespace Business.Abstract 5 | { 6 | public interface IUserService 7 | { 8 | List GetClaims(User user); 9 | void Add(User user); 10 | User GetByMail(string email); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Business/Business.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Business/BusinessAspects/Autofac/SecuredOperation.cs: -------------------------------------------------------------------------------- 1 | using Core.Utilities.Interceptors; 2 | using Core.Utilities.IoC; 3 | using Microsoft.AspNetCore.Http; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | using Castle.DynamicProxy; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Core.Extensions; 10 | using Business.Constants; 11 | 12 | namespace Business.BusinessAspects.Autofac 13 | { 14 | //JWT 15 | public class SecuredOperation : MethodInterception 16 | { 17 | private string[] _roles; 18 | private IHttpContextAccessor _httpContextAccessor; 19 | 20 | public SecuredOperation(string roles) 21 | { 22 | _roles = roles.Split(','); 23 | _httpContextAccessor = ServiceTool.ServiceProvider.GetService(); 24 | 25 | } 26 | 27 | protected override void OnBefore(IInvocation invocation) 28 | { 29 | var roleClaims = _httpContextAccessor.HttpContext.User.ClaimRoles(); 30 | foreach (var role in _roles) 31 | { 32 | if (roleClaims.Contains(role)) 33 | { 34 | return; 35 | } 36 | } 37 | throw new Exception(Messages.AuthorizationDenied); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Business/CCS/DatabaseLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Business.CCS 4 | { 5 | public class DatabaseLogger : ILogger 6 | { 7 | public void Log() 8 | { 9 | Console.WriteLine("Veritabanına loglandı"); 10 | } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Business/CCS/FileLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Business.CCS 6 | { 7 | public class FileLogger : ILogger 8 | { 9 | public void Log() 10 | { 11 | Console.WriteLine("Dosyaya loglandı"); 12 | } 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Business/CCS/ILogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Business.CCS 6 | { 7 | public interface ILogger 8 | { 9 | void Log(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Business/Concrete/AuthManager.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Core.Entities.Concrete; 3 | using Core.Utilities.Results; 4 | using Core.Utilities.Security.Hashing; 5 | using Core.Utilities.Security.JWT; 6 | using Entities.DTOs; 7 | 8 | namespace Business.Concrete 9 | { 10 | public class AuthManager : IAuthService 11 | { 12 | private IUserService _userService; 13 | private ITokenHelper _tokenHelper; 14 | 15 | public AuthManager(IUserService userService, ITokenHelper tokenHelper) 16 | { 17 | _userService = userService; 18 | _tokenHelper = tokenHelper; 19 | } 20 | 21 | public IDataResult Register(UserForRegisterDto userForRegisterDto, string password) 22 | { 23 | byte[] passwordHash, passwordSalt; 24 | HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt); 25 | var user = new User 26 | { 27 | Email = userForRegisterDto.Email, 28 | FirstName = userForRegisterDto.FirstName, 29 | LastName = userForRegisterDto.LastName, 30 | PasswordHash = passwordHash, 31 | PasswordSalt = passwordSalt, 32 | Status = true 33 | }; 34 | _userService.Add(user); 35 | return new SuccessDataResult(user, "Kayıt oldu"); 36 | } 37 | 38 | public IDataResult Login(UserForLoginDto userForLoginDto) 39 | { 40 | var userToCheck = _userService.GetByMail(userForLoginDto.Email); 41 | if (userToCheck == null) 42 | { 43 | return new ErrorDataResult("Kullanıcı bulunamadı"); 44 | } 45 | 46 | if (!HashingHelper.VerifyPasswordHash(userForLoginDto.Password, userToCheck.PasswordHash, userToCheck.PasswordSalt)) 47 | { 48 | return new ErrorDataResult("Parola hatası"); 49 | } 50 | 51 | return new SuccessDataResult(userToCheck, "Başarılı giriş"); 52 | } 53 | 54 | public IResult UserExists(string email) 55 | { 56 | if (_userService.GetByMail(email) != null) 57 | { 58 | return new ErrorResult("Kullanıcı mevcut"); 59 | } 60 | return new SuccessResult(); 61 | } 62 | 63 | public IDataResult CreateAccessToken(User user) 64 | { 65 | var claims = _userService.GetClaims(user); 66 | var accessToken = _tokenHelper.CreateToken(user, claims); 67 | return new SuccessDataResult(accessToken, "Token oluşturuldu"); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Business/Concrete/CategoryManager.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Core.Utilities.Results; 3 | using DataAccess.Abstract; 4 | using Entities.Concrete; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Text; 8 | 9 | namespace Business.Concrete 10 | { 11 | public class CategoryManager : ICategoryService 12 | { 13 | ICategoryDal _categoryDal; 14 | 15 | public CategoryManager(ICategoryDal categoryDal) 16 | { 17 | _categoryDal = categoryDal; 18 | } 19 | 20 | public IDataResult> GetAll() 21 | { 22 | //İş kodları 23 | return new SuccessDataResult>(_categoryDal.GetAll()); 24 | } 25 | 26 | //Select * from Categories where CategoryId = 3 27 | public IDataResult GetById(int categoryId) 28 | { 29 | return new SuccessDataResult(_categoryDal.Get(c=>c.CategoryId == categoryId)); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Business/Concrete/ProductManager.cs: -------------------------------------------------------------------------------- 1 |  2 | using Business.Abstract; 3 | using Business.BusinessAspects.Autofac; 4 | using Business.Constants; 5 | using Business.ValidationRules.FluentValidation; 6 | using Core.Aspects.Autofac.Validation; 7 | using Core.Utilities.Business; 8 | using Core.Utilities.Results; 9 | using DataAccess.Abstract; 10 | using Entities.Concrete; 11 | using Entities.DTOs; 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using FluentValidation; 16 | using Core.Aspects.Autofac.Caching; 17 | using Core.Aspects.Autofac.Performance; 18 | 19 | namespace Business.Concrete 20 | { 21 | public class ProductManager : IProductService 22 | { 23 | IProductDal _productDal; 24 | ICategoryService _categoryService; 25 | 26 | public ProductManager(IProductDal productDal,ICategoryService categoryService) 27 | { 28 | _productDal = productDal; 29 | _categoryService = categoryService; 30 | } 31 | 32 | //00.25 Dersteyiz 33 | //Claim 34 | // [SecuredOperation("product.add,admin")] 35 | [ValidationAspect(typeof(ProductValidator))] 36 | [CacheRemoveAspect("IProductService.Get")] 37 | public IResult Add(Product product) 38 | { 39 | 40 | //Aynı isimde ürün eklenemez 41 | //Eğer mevcut kategori sayısı 15'i geçtiyse sisteme yeni ürün eklenemez. ve 42 | IResult result = BusinessRules.Run(CheckIfProductNameExists(product.ProductName), 43 | CheckIfProductCountOfCategoryCorrect(product.CategoryId), CheckIfCategoryLimitExceded()); 44 | 45 | if (result != null) 46 | { 47 | return result; 48 | } 49 | 50 | _productDal.Add(product); 51 | 52 | return new SuccessResult(Messages.ProductAdded); 53 | 54 | 55 | 56 | //23:10 Dersteyiz 57 | } 58 | 59 | [CacheAspect] 60 | [PerformanceAspect(1)] 61 | public IDataResult> GetAll() 62 | { 63 | if (DateTime.Now.Hour == 1) 64 | { 65 | return new ErrorDataResult>(Messages.MaintenanceTime); 66 | } 67 | 68 | return new SuccessDataResult>(_productDal.GetAll(), Messages.ProductsListed); 69 | } 70 | 71 | public IDataResult> GetAllByCategoryId(int id) 72 | { 73 | return new SuccessDataResult>(_productDal.GetAll(p => p.CategoryId == id)); 74 | } 75 | [CacheAspect] 76 | public IDataResult GetById(int productId) 77 | { 78 | return new SuccessDataResult(_productDal.Get(p => p.ProductId == productId)); 79 | } 80 | 81 | public IDataResult> GetByUnitPrice(decimal min, decimal max) 82 | { 83 | return new SuccessDataResult>(_productDal.GetAll(p => p.UnitPrice >= min && p.UnitPrice <= max)); 84 | } 85 | 86 | public IDataResult> GetProductDetails() 87 | { 88 | if (DateTime.Now.Hour == 23) 89 | { 90 | return new ErrorDataResult>(Messages.MaintenanceTime); 91 | } 92 | return new SuccessDataResult>(_productDal.GetProductDetails()); 93 | } 94 | 95 | [ValidationAspect(typeof(ProductValidator))] 96 | [CacheRemoveAspect("IProductService.Get")] 97 | public IResult Update(Product product) 98 | { 99 | var result = _productDal.GetAll(p => p.CategoryId == product.CategoryId).Count; 100 | if (result >= 10) 101 | { 102 | return new ErrorResult(Messages.ProductCountOfCategoryError); 103 | } 104 | throw new NotImplementedException(); 105 | } 106 | 107 | private IResult CheckIfProductCountOfCategoryCorrect(int categoryId) 108 | { 109 | //Select count(*) from products where categoryId=1 110 | var result = _productDal.GetAll(p => p.CategoryId == categoryId).Count; 111 | if (result >= 15) 112 | { 113 | return new ErrorResult(Messages.ProductCountOfCategoryError); 114 | } 115 | return new SuccessResult(); 116 | } 117 | 118 | private IResult CheckIfProductNameExists(string productName) 119 | { 120 | var result = _productDal.GetAll(p => p.ProductName == productName).Any(); 121 | if (result) 122 | { 123 | return new ErrorResult(Messages.ProductNameAlreadyExists); 124 | } 125 | return new SuccessResult(); 126 | } 127 | 128 | private IResult CheckIfCategoryLimitExceded() 129 | { 130 | var result = _categoryService.GetAll(); 131 | if (result.Data.Count>15) 132 | { 133 | return new ErrorResult(Messages.CategoryLimitExceded); 134 | } 135 | 136 | return new SuccessResult(); 137 | } 138 | 139 | public IResult AddTransactionalTest(Product product) 140 | { 141 | throw new NotImplementedException(); 142 | } 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /Business/Concrete/UserManager.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Core.Entities.Concrete; 3 | using DataAccess.Abstract; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace Business.Concrete 9 | { 10 | public class UserManager : IUserService 11 | { 12 | IUserDal _userDal; 13 | 14 | public UserManager(IUserDal userDal) 15 | { 16 | _userDal = userDal; 17 | } 18 | 19 | public List GetClaims(User user) 20 | { 21 | return _userDal.GetClaims(user); 22 | } 23 | 24 | public void Add(User user) 25 | { 26 | _userDal.Add(user); 27 | } 28 | 29 | public User GetByMail(string email) 30 | { 31 | return _userDal.Get(u => u.Email == email); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Business/Constants/Messages.cs: -------------------------------------------------------------------------------- 1 | using Entities.Concrete; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | 7 | namespace Business.Constants 8 | { 9 | public static class Messages 10 | { 11 | public static string ProductAdded = "Ürün eklendi"; 12 | public static string ProductNameInvalid = "Ürün ismi geçersiz"; 13 | public static string MaintenanceTime ="Sistem bakımda"; 14 | public static string ProductsListed ="Ürünler listelendi"; 15 | public static string ProductCountOfCategoryError="Bir kategoride en fazla 10 ürün olabilir"; 16 | public static string ProductNameAlreadyExists="Bu isimde zaten başka bir ürün var"; 17 | public static string CategoryLimitExceded = "Kategori limiti aşıldığı için yeni ürün eklenemiyor"; 18 | public static string AuthorizationDenied="Yetkiniz yok."; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Business/DependencyResolvers/Autofac/AutofacBusinessModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extras.DynamicProxy; 3 | using Business.Abstract; 4 | using Business.CCS; 5 | using Business.Concrete; 6 | using Castle.DynamicProxy; 7 | using Core.Utilities.Interceptors; 8 | using Core.Utilities.Security.JWT; 9 | using DataAccess.Abstract; 10 | using DataAccess.Concrete.EntityFramework; 11 | using Microsoft.AspNetCore.Http; 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Text; 15 | 16 | namespace Business.DependencyResolvers.Autofac 17 | { 18 | public class AutofacBusinessModule : Module 19 | { 20 | protected override void Load(ContainerBuilder builder) 21 | { 22 | 23 | builder.RegisterType().As().SingleInstance(); 24 | builder.RegisterType().As().SingleInstance(); 25 | 26 | builder.RegisterType().As().SingleInstance(); 27 | builder.RegisterType().As().SingleInstance(); 28 | 29 | builder.RegisterType().As(); 30 | builder.RegisterType().As(); 31 | 32 | builder.RegisterType().As(); 33 | builder.RegisterType().As(); 34 | 35 | var assembly = System.Reflection.Assembly.GetExecutingAssembly(); 36 | 37 | builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces() 38 | .EnableInterfaceInterceptors(new ProxyGenerationOptions() 39 | { 40 | Selector = new AspectInterceptorSelector() 41 | }).SingleInstance(); 42 | 43 | 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Business/ValidationRules/FluentValidation/ProductValidator.cs: -------------------------------------------------------------------------------- 1 | using Entities.Concrete; 2 | using FluentValidation; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Business.ValidationRules.FluentValidation 8 | { 9 | public class ProductValidator : AbstractValidator 10 | { 11 | public ProductValidator() 12 | { 13 | RuleFor(p => p.ProductName).NotEmpty(); 14 | RuleFor(p => p.ProductName).MinimumLength(2); 15 | RuleFor(p => p.UnitPrice).NotEmpty(); 16 | RuleFor(p => p.UnitPrice).GreaterThan(0); 17 | RuleFor(p => p.UnitPrice).GreaterThanOrEqualTo(10).When(p => p.CategoryId == 1); 18 | RuleFor(p => p.ProductName).Must(StartWithA).WithMessage("Ürünler A harfi ile başlamalı"); 19 | 20 | } 21 | 22 | private bool StartWithA(string arg) 23 | { 24 | return true; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ConsoleUI/ConsoleUI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ConsoleUI/Program.cs: -------------------------------------------------------------------------------- 1 | using Business.Concrete; 2 | using DataAccess.Concrete.EntityFramework; 3 | using DataAccess.Concrete.InMemory; 4 | using System; 5 | 6 | namespace ConsoleUI 7 | { 8 | //SOLID 9 | //Open Closed Principle 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | //Data Transformation Object 15 | ProductTest(); 16 | //IoC 17 | //CategoryTest(); 18 | } 19 | 20 | private static void CategoryTest() 21 | { 22 | CategoryManager categoryManager = new CategoryManager(new EfCategoryDal()); 23 | foreach (var category in categoryManager.GetAll().Data) 24 | { 25 | Console.WriteLine(category.CategoryName); 26 | } 27 | } 28 | 29 | private static void ProductTest() 30 | { 31 | ProductManager productManager = new ProductManager(new EfProductDal() 32 | ,new CategoryManager(new EfCategoryDal())); 33 | 34 | var result = productManager.GetProductDetails(); 35 | 36 | if (result.Success==true) 37 | { 38 | foreach (var product in result.Data) 39 | { 40 | Console.WriteLine(product.ProductName + "/" + product.CategoryName); 41 | } 42 | } 43 | else 44 | { 45 | Console.WriteLine(result.Message); 46 | } 47 | 48 | 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Caching/CacheAspect.cs: -------------------------------------------------------------------------------- 1 | using Core.CrossCuttingConcerns.Caching; 2 | using Core.Utilities.Interceptors; 3 | using Core.Utilities.IoC; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Castle.DynamicProxy; 9 | using System.Linq; 10 | 11 | namespace Core.Aspects.Autofac.Caching 12 | { 13 | public class CacheAspect : MethodInterception 14 | { 15 | private int _duration; 16 | private ICacheManager _cacheManager; 17 | 18 | public CacheAspect(int duration = 60) 19 | { 20 | _duration = duration; 21 | _cacheManager = ServiceTool.ServiceProvider.GetService(); 22 | } 23 | 24 | public override void Intercept(IInvocation invocation) 25 | { 26 | var methodName = string.Format($"{invocation.Method.ReflectedType.FullName}.{invocation.Method.Name}"); 27 | var arguments = invocation.Arguments.ToList(); 28 | var key = $"{methodName}({string.Join(",", arguments.Select(x => x?.ToString() ?? ""))})"; 29 | if (_cacheManager.IsAdd(key)) 30 | { 31 | invocation.ReturnValue = _cacheManager.Get(key); 32 | return; 33 | } 34 | invocation.Proceed(); 35 | _cacheManager.Add(key, invocation.ReturnValue, _duration); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Caching/CacheRemoveAspect.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using Core.CrossCuttingConcerns.Caching; 3 | using Core.Utilities.Interceptors; 4 | using Core.Utilities.IoC; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Text; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace Core.Aspects.Autofac.Caching 11 | { 12 | public class CacheRemoveAspect : MethodInterception 13 | { 14 | private string _pattern; 15 | private ICacheManager _cacheManager; 16 | 17 | public CacheRemoveAspect(string pattern) 18 | { 19 | _pattern = pattern; 20 | _cacheManager = ServiceTool.ServiceProvider.GetService(); 21 | } 22 | 23 | protected override void OnSuccess(IInvocation invocation) 24 | { 25 | _cacheManager.RemoveByPattern(_pattern); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Performance/PerformanceAspect.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using Core.Utilities.Interceptors; 3 | using Core.Utilities.IoC; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Text; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace Core.Aspects.Autofac.Performance 11 | { 12 | public class PerformanceAspect : MethodInterception 13 | { 14 | private int _interval; 15 | private Stopwatch _stopwatch; 16 | 17 | public PerformanceAspect(int interval) 18 | { 19 | _interval = interval; 20 | _stopwatch = ServiceTool.ServiceProvider.GetService(); 21 | } 22 | 23 | 24 | protected override void OnBefore(IInvocation invocation) 25 | { 26 | _stopwatch.Start(); 27 | } 28 | 29 | protected override void OnAfter(IInvocation invocation) 30 | { 31 | if (_stopwatch.Elapsed.TotalSeconds > _interval) 32 | { 33 | Debug.WriteLine($"Performance : {invocation.Method.DeclaringType.FullName}.{invocation.Method.Name}-->{_stopwatch.Elapsed.TotalSeconds}"); 34 | } 35 | _stopwatch.Reset(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Transaction/TransactionScopeAspect.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using Core.Utilities.Interceptors; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | using System.Transactions; 7 | 8 | namespace Core.Aspects.Autofac.Transaction 9 | { 10 | public class TransactionScopeAspect : MethodInterception 11 | { 12 | public override void Intercept(IInvocation invocation) 13 | { 14 | using (TransactionScope transactionScope = new TransactionScope()) 15 | { 16 | try 17 | { 18 | invocation.Proceed(); 19 | transactionScope.Complete(); 20 | } 21 | catch (System.Exception e) 22 | { 23 | transactionScope.Dispose(); 24 | throw; 25 | } 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Validation/ValidationAspect.cs: -------------------------------------------------------------------------------- 1 | /*using Castle.DynamicProxy; 2 | using Core.CrossCuttingConcerns.Validation; 3 | using Core.Utilities.Interceptors; 4 | using FluentValidation; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | 10 | namespace Core.Aspects.Autofac.Validation 11 | { 12 | public class ValidationAspect : MethodInterception //Aspect 13 | { 14 | private Type _validatorType; 15 | public ValidationAspect(Type validatorType) 16 | { 17 | //defensive coding 18 | if (!typeof(IValidator).IsAssignableFrom(validatorType)) 19 | { 20 | throw new System.Exception("Bu bir doğrulama sınıfı değil"); 21 | } 22 | 23 | _validatorType = validatorType; 24 | } 25 | protected override void OnBefore(IInvocation invocation) 26 | { 27 | var validator = (IValidator)Activator.CreateInstance(_validatorType); 28 | var entityType = _validatorType.BaseType.GetGenericArguments()[0]; 29 | var entities = invocation.Arguments.Where(t => t.GetType() == entityType); 30 | foreach (var entity in entities) 31 | { 32 | ValidationTool.Validate(validator, entity); 33 | } 34 | } 35 | 36 | 37 | } 38 | } */ 39 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Validation/VallidationAspect.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using Core.CrossCuttingConcerns.Validation; 3 | using Core.Utilities.Interceptors; 4 | using FluentValidation; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | 10 | namespace Core.Aspects.Autofac.Validation 11 | { 12 | public class ValidationAspect : MethodInterception 13 | { 14 | private Type _vvalidatorType; 15 | public ValidationAspect(Type validatorType) 16 | { 17 | if (!typeof(IValidator).IsAssignableFrom(validatorType)) 18 | { 19 | throw new System.Exception("Bu bir doğrulama sınıfı değil"); 20 | } 21 | 22 | _vvalidatorType = validatorType; 23 | } 24 | protected override void OnBefore(IInvocation invocation) 25 | { 26 | var validator = (IValidator)Activator.CreateInstance(_vvalidatorType); 27 | var entityType = _vvalidatorType.BaseType.GetGenericArguments()[0]; 28 | var entities = invocation.Arguments.Where(t => t.GetType() == entityType); 29 | foreach (var entity in entities) 30 | { 31 | ValidationTool.Validate(validator, entity); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Core/Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Core/CrossCuttingConcerns/Caching/ICacheManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.CrossCuttingConcerns.Caching 6 | { 7 | public interface ICacheManager 8 | { 9 | void Add(string key, object value,int duration); 10 | T Get(string key); 11 | object Get(string key); 12 | bool IsAdd(string key); 13 | void Remove(string key); 14 | void RemoveByPattern(string pattern); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Core/CrossCuttingConcerns/Caching/Microsoft/MemoryCacheManager.cs: -------------------------------------------------------------------------------- 1 | using Core.Utilities.IoC; 2 | using Microsoft.Extensions.Caching.Memory; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using System.Text.RegularExpressions; 8 | using System.Linq; 9 | 10 | namespace Core.CrossCuttingConcerns.Caching.Microsoft 11 | { 12 | public class MemoryCacheManager : ICacheManager 13 | { 14 | IMemoryCache _memoryCache; 15 | public MemoryCacheManager() 16 | { 17 | _memoryCache = ServiceTool.ServiceProvider.GetService(); 18 | } 19 | public void Add(string key, object value, int duration) 20 | { 21 | _memoryCache.Set(key, value, TimeSpan.FromMinutes(duration)); 22 | 23 | } 24 | 25 | public T Get(string key) 26 | { 27 | return _memoryCache.Get(key); 28 | } 29 | 30 | public object Get(string key) 31 | { 32 | return _memoryCache.Get(key); 33 | } 34 | 35 | public bool IsAdd(string key) 36 | { 37 | return _memoryCache.TryGetValue(key, out _); 38 | } 39 | 40 | public void Remove(string key) 41 | { 42 | _memoryCache.Remove(key); 43 | } 44 | 45 | public void RemoveByPattern(string pattern) 46 | { 47 | var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 48 | var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; 49 | List cacheCollectionValues = new List(); 50 | 51 | foreach (var cacheItem in cacheEntriesCollection) 52 | { 53 | ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); 54 | cacheCollectionValues.Add(cacheItemValue); 55 | } 56 | 57 | var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); 58 | var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); 59 | 60 | foreach (var key in keysToRemove) 61 | { 62 | _memoryCache.Remove(key); 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Core/CrossCuttingConcerns/Validation/ValidationTool.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.CrossCuttingConcerns.Validation 7 | { 8 | public static class ValidationTool 9 | { 10 | public static void Validate(IValidator validator,object entity) 11 | { 12 | var context = new ValidationContext(entity); 13 | var result = validator.Validate(context); 14 | if (!result.IsValid) 15 | { 16 | throw new ValidationException(result.Errors); 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Core/DataAccess/EntityFramework/EfEntityRepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Text; 8 | 9 | namespace Core.DataAccess.EntityFramework 10 | { 11 | public class EfEntityRepositoryBase: IEntityRepository 12 | where TEntity: class, IEntity, new() 13 | where TContext : DbContext,new() 14 | { 15 | public void Add(TEntity entity) 16 | { 17 | //IDisposable pattern implementation of c# 18 | using (TContext context = new TContext()) 19 | { 20 | var addedEntity = context.Entry(entity); 21 | addedEntity.State = EntityState.Added; 22 | context.SaveChanges(); 23 | } 24 | } 25 | 26 | public void Delete(TEntity entity) 27 | { 28 | using (TContext context = new TContext()) 29 | { 30 | var deletedEntity = context.Entry(entity); 31 | deletedEntity.State = EntityState.Deleted; 32 | context.SaveChanges(); 33 | } 34 | } 35 | 36 | public TEntity Get(Expression> filter) 37 | { 38 | using (TContext context = new TContext()) 39 | { 40 | return context.Set().SingleOrDefault(filter); 41 | } 42 | } 43 | 44 | public List GetAll(Expression> filter = null) 45 | { 46 | using (TContext context = new TContext()) 47 | { 48 | return filter == null 49 | ? context.Set().ToList() 50 | : context.Set().Where(filter).ToList(); 51 | } 52 | } 53 | 54 | public void Update(TEntity entity) 55 | { 56 | using (TContext context = new TContext()) 57 | { 58 | var updatedEntity = context.Entry(entity); 59 | updatedEntity.State = EntityState.Modified; 60 | context.SaveChanges(); 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Core/DataAccess/IEntityRepository.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | 7 | namespace Core.DataAccess 8 | { 9 | //generic constraint 10 | //class : referans tip 11 | //IEntity : IEntity olabilir veya IEntity implemente eden bir nesne olabilir 12 | //new() : new'lenebilir olmalı 13 | public interface IEntityRepository where T:class,IEntity,new() 14 | { 15 | List GetAll(Expression> filter=null); 16 | T Get(Expression> filter); 17 | void Add(T entity); 18 | void Update(T entity); 19 | void Delete(T entity); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Core/DependencyResolvers/CoreModule.cs: -------------------------------------------------------------------------------- 1 | using Core.CrossCuttingConcerns.Caching; 2 | using Core.CrossCuttingConcerns.Caching.Microsoft; 3 | using Core.Utilities.IoC; 4 | using Microsoft.AspNetCore.Http; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Diagnostics; 9 | using System.Text; 10 | 11 | namespace Core.DependencyResolvers 12 | { 13 | public class CoreModule : ICoreModule 14 | { 15 | public void Load(IServiceCollection serviceCollection) 16 | { 17 | serviceCollection.AddMemoryCache(); 18 | serviceCollection.AddSingleton(); 19 | serviceCollection.AddSingleton(); 20 | serviceCollection.AddSingleton(); 21 | 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Core/Entities/Concrete/OperationClaim.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Entities.Concrete 2 | { 3 | public class OperationClaim:IEntity 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Core/Entities/Concrete/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Entities.Concrete 6 | { 7 | public class User:IEntity 8 | { 9 | public int Id { get; set; } 10 | public string FirstName { get; set; } 11 | public string LastName { get; set; } 12 | public string Email { get; set; } 13 | public byte[] PasswordSalt { get; set; } 14 | public byte[] PasswordHash { get; set; } 15 | public bool Status { get; set; } 16 | 17 | //22:05 Dersteyiz 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Core/Entities/Concrete/UserOperationClaim.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Entities.Concrete 2 | { 3 | public class UserOperationClaim:IEntity 4 | { 5 | public int Id { get; set; } 6 | public int UserId { get; set; } 7 | public int OperationClaimId { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Core/Entities/IDto.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Entities 2 | { 3 | public interface IDto 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /Core/Entities/IEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Entities 6 | { 7 | //IEntity implement eden class bir veritabanı tablosudur 8 | public interface IEntity 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Core/Extensions/ClaimExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | 6 | namespace Core.Extensions 7 | { 8 | public static class ClaimExtensions 9 | { 10 | public static void AddEmail(this ICollection claims, string email) 11 | { 12 | claims.Add(new Claim(JwtRegisteredClaimNames.Email, email)); 13 | } 14 | 15 | public static void AddName(this ICollection claims, string name) 16 | { 17 | claims.Add(new Claim(ClaimTypes.Name, name)); 18 | } 19 | 20 | public static void AddNameIdentifier(this ICollection claims, string nameIdentifier) 21 | { 22 | claims.Add(new Claim(ClaimTypes.NameIdentifier, nameIdentifier)); 23 | } 24 | 25 | public static void AddRoles(this ICollection claims, string[] roles) 26 | { 27 | roles.ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role))); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Core/Extensions/ClaimsPrincipalExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Security.Claims; 4 | 5 | namespace Core.Extensions 6 | { 7 | public static class ClaimsPrincipalExtensions 8 | { 9 | public static List Claims(this ClaimsPrincipal claimsPrincipal, string claimType) 10 | { 11 | var result = claimsPrincipal?.FindAll(claimType)?.Select(x => x.Value).ToList(); 12 | return result; 13 | } 14 | 15 | public static List ClaimRoles(this ClaimsPrincipal claimsPrincipal) 16 | { 17 | return claimsPrincipal?.Claims(ClaimTypes.Role); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Core/Extensions/ErrorDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using FluentValidation.Results; 5 | using Newtonsoft.Json; 6 | 7 | namespace Core.Extensions 8 | { 9 | public class ErrorDetails 10 | { 11 | public string Message { get; set; } 12 | public int StatusCode { get; set; } 13 | public override string ToString() 14 | { 15 | return JsonConvert.SerializeObject(this); 16 | } 17 | } 18 | 19 | public class ValidationErrorDetails : ErrorDetails 20 | { 21 | public IEnumerable Errors { get; set; } 22 | } 23 | 24 | 25 | } -------------------------------------------------------------------------------- /Core/Extensions/ExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using FluentValidation; 7 | using FluentValidation.Results; 8 | using Microsoft.AspNetCore.Http; 9 | 10 | namespace Core.Extensions 11 | { 12 | public class ExceptionMiddleware 13 | { 14 | private RequestDelegate _next; 15 | 16 | public ExceptionMiddleware(RequestDelegate next) 17 | { 18 | _next = next; 19 | } 20 | 21 | public async Task InvokeAsync(HttpContext httpContext) 22 | { 23 | try 24 | { 25 | await _next(httpContext); 26 | } 27 | catch (Exception e) 28 | { 29 | await HandleExceptionAsync(httpContext, e); 30 | } 31 | } 32 | 33 | private Task HandleExceptionAsync(HttpContext httpContext, Exception e) 34 | { 35 | httpContext.Response.ContentType = "application/json"; 36 | httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 37 | 38 | string message = "Internal Server Error"; 39 | IEnumerable errors; 40 | if (e.GetType() == typeof(ValidationException)) 41 | { 42 | message = e.Message; 43 | errors = ((ValidationException)e).Errors; 44 | httpContext.Response.StatusCode = 400; 45 | 46 | return httpContext.Response.WriteAsync(new ValidationErrorDetails 47 | { 48 | StatusCode = 400, 49 | Message = message, 50 | Errors = errors 51 | }.ToString()); 52 | 53 | } 54 | 55 | return httpContext.Response.WriteAsync(new ErrorDetails 56 | { 57 | StatusCode = httpContext.Response.StatusCode, 58 | Message = message 59 | }.ToString()); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /Core/Extensions/ExceptionMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.AspNetCore.Builder; 5 | 6 | namespace Core.Extensions 7 | { 8 | public static class ExceptionMiddlewareExtensions 9 | { 10 | public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app) 11 | { 12 | app.UseMiddleware(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Core/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Core.Utilities.IoC; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Core.Extensions 8 | { 9 | public static class ServiceCollectionExtensions 10 | { 11 | public static IServiceCollection AddDependencyResolvers 12 | (this IServiceCollection serviceCollection, ICoreModule[] modules) 13 | { 14 | foreach (var module in modules) 15 | { 16 | module.Load(serviceCollection); 17 | } 18 | 19 | return ServiceTool.Create(serviceCollection); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Core/Utilities/Business/BusinessRules.cs: -------------------------------------------------------------------------------- 1 | using Core.Utilities.Results; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.Business 7 | { 8 | public class BusinessRules 9 | { 10 | public static IResult Run(params IResult[] logics) 11 | { 12 | foreach (var logic in logics) 13 | { 14 | if (!logic.Success) 15 | { 16 | return logic; 17 | } 18 | } 19 | 20 | return null; 21 | } 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Core/Utilities/Interceptors/AspectInterceptorSelector.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | 8 | namespace Core.Utilities.Interceptors 9 | { 10 | 11 | public class AspectInterceptorSelector : IInterceptorSelector 12 | { 13 | public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors) 14 | { 15 | var classAttributes = type.GetCustomAttributes 16 | (true).ToList(); 17 | var methodAttributes = type.GetMethod(method.Name) 18 | .GetCustomAttributes(true); 19 | classAttributes.AddRange(methodAttributes); 20 | 21 | return classAttributes.OrderBy(x => x.Priority).ToArray(); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Core/Utilities/Interceptors/MethodInterception.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using System; 3 | 4 | namespace Core.Utilities.Interceptors 5 | { 6 | public abstract class MethodInterception : MethodInterceptionBaseAttribute 7 | { 8 | //invocation : business method 9 | protected virtual void OnBefore(IInvocation invocation) { } 10 | protected virtual void OnAfter(IInvocation invocation) { } 11 | protected virtual void OnException(IInvocation invocation, System.Exception e) { } 12 | protected virtual void OnSuccess(IInvocation invocation) { } 13 | public override void Intercept(IInvocation invocation) 14 | { 15 | var isSuccess = true; 16 | OnBefore(invocation); 17 | try 18 | { 19 | invocation.Proceed(); 20 | } 21 | catch (Exception e) 22 | { 23 | isSuccess = false; 24 | OnException(invocation, e); 25 | throw; 26 | } 27 | finally 28 | { 29 | if (isSuccess) 30 | { 31 | OnSuccess(invocation); 32 | } 33 | } 34 | OnAfter(invocation); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Core/Utilities/Interceptors/MethodInterceptionBaseAttribute.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using System; 3 | 4 | namespace Core.Utilities.Interceptors 5 | { 6 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] 7 | public abstract class MethodInterceptionBaseAttribute : Attribute, IInterceptor 8 | { 9 | public int Priority { get; set; } 10 | 11 | public virtual void Intercept(IInvocation invocation) 12 | { 13 | 14 | } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Core/Utilities/IoC/ICoreModule.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.IoC 7 | { 8 | public interface ICoreModule 9 | { 10 | void Load(IServiceCollection serviceCollection); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Core/Utilities/IoC/ServiceTool.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.IoC 7 | { 8 | public static class ServiceTool 9 | { 10 | public static IServiceProvider ServiceProvider { get; private set; } 11 | 12 | public static IServiceCollection Create(IServiceCollection services) 13 | { 14 | ServiceProvider = services.BuildServiceProvider(); 15 | return services; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Core/Utilities/Results/DataResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public class DataResult : Result, IDataResult 8 | { 9 | public DataResult(T data,bool success, string message):base(success,message) 10 | { 11 | Data = data; 12 | } 13 | 14 | public DataResult(T data, bool success):base(success) 15 | { 16 | Data = data; 17 | } 18 | public T Data { get; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Core/Utilities/Results/ErrorDataResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public class ErrorDataResult : DataResult 8 | { 9 | public ErrorDataResult(T data, string message) : base(data, false, message) 10 | { 11 | 12 | } 13 | 14 | public ErrorDataResult(T data) : base(data, false) 15 | { 16 | 17 | } 18 | 19 | public ErrorDataResult(string message) : base(default, false, message) 20 | { 21 | 22 | } 23 | 24 | public ErrorDataResult() : base(default, false) 25 | { 26 | 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Core/Utilities/Results/ErrorResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public class ErrorResult:Result 8 | { 9 | public ErrorResult(string message) : base(false, message) 10 | { 11 | 12 | } 13 | 14 | public ErrorResult() : base(false) 15 | { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Core/Utilities/Results/IDataResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public interface IDataResult:IResult 8 | { 9 | T Data { get; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Core/Utilities/Results/IResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | //Temel voidler için başlangıç 8 | public interface IResult 9 | { 10 | bool Success { get; } 11 | string Message { get; } 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Core/Utilities/Results/Result.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public class Result : IResult 8 | { 9 | 10 | public Result(bool success, string message):this(success) 11 | { 12 | Message = message; 13 | } 14 | 15 | public Result(bool success) 16 | { 17 | Success = success; 18 | } 19 | 20 | public bool Success { get; } 21 | 22 | public string Message { get; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Core/Utilities/Results/SuccessDataResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public class SuccessDataResult:DataResult 8 | { 9 | public SuccessDataResult(T data, string message):base(data,true,message) 10 | { 11 | 12 | } 13 | 14 | public SuccessDataResult(T data):base(data,true) 15 | { 16 | 17 | } 18 | 19 | public SuccessDataResult(string message):base(default,true,message) 20 | { 21 | 22 | } 23 | 24 | public SuccessDataResult():base(default,true) 25 | { 26 | 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Core/Utilities/Results/SuccessResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Results 6 | { 7 | public class SuccessResult:Result 8 | { 9 | public SuccessResult(string message) : base(true, message) 10 | { 11 | 12 | } 13 | 14 | public SuccessResult():base(true) 15 | { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Core/Utilities/Security/Encryption/SecurityKeyHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.IdentityModel.Tokens; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.Security.Encryption 7 | { 8 | public class SecurityKeyHelper 9 | { 10 | public static SecurityKey CreateSecurityKey(string securityKey) 11 | { 12 | return new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Core/Utilities/Security/Encryption/SigningCredentialsHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.IdentityModel.Tokens; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.Security.Encryption 7 | { 8 | public class SigningCredentialsHelper 9 | { 10 | public static SigningCredentials CreateSigningCredentials(SecurityKey securityKey) 11 | { 12 | return new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha512Signature); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Core/Utilities/Security/Hashing/HashingHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Security.Hashing 6 | { 7 | public class HashingHelper 8 | { 9 | public static void CreatePasswordHash 10 | (string password, out byte[] passwordHash, out byte[] passwordSalt) 11 | { 12 | using (var hmac = new System.Security.Cryptography.HMACSHA512()) 13 | { 14 | passwordSalt = hmac.Key; 15 | passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); 16 | 17 | } 18 | } 19 | 20 | public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) 21 | { 22 | using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) 23 | { 24 | var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); 25 | for (int i = 0; i < computedHash.Length; i++) 26 | { 27 | if (computedHash[i]!=passwordHash[i]) 28 | { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | 35 | 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Core/Utilities/Security/JWT/AccessToken.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Security.JWT 6 | { 7 | public class AccessToken 8 | { 9 | public string Token { get; set; } 10 | public DateTime Expiration { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Core/Utilities/Security/JWT/ITokenHelper.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities.Concrete; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.Security.JWT 7 | { 8 | public interface ITokenHelper 9 | { 10 | AccessToken CreateToken(User user, List operationClaims); 11 | } 12 | } 13 | 14 | //23.05 Dersteyiz -------------------------------------------------------------------------------- /Core/Utilities/Security/JWT/JwtHelper.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities.Concrete; 2 | using Core.Extensions; 3 | using Core.Utilities.Security.Encryption; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.IdentityModel.Tokens; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IdentityModel.Tokens.Jwt; 9 | using System.Linq; 10 | using System.Security.Claims; 11 | using System.Text; 12 | 13 | namespace Core.Utilities.Security.JWT 14 | { 15 | public class JwtHelper : ITokenHelper 16 | { 17 | public IConfiguration Configuration { get; } 18 | private TokenOptions _tokenOptions; 19 | private DateTime _accessTokenExpiration; 20 | public JwtHelper(IConfiguration configuration) 21 | { 22 | Configuration = configuration; 23 | _tokenOptions = Configuration.GetSection("TokenOptions").Get(); 24 | 25 | } 26 | public AccessToken CreateToken(User user, List operationClaims) 27 | { 28 | _accessTokenExpiration = DateTime.Now.AddMinutes(_tokenOptions.AccessTokenExpiration); 29 | var securityKey = SecurityKeyHelper.CreateSecurityKey(_tokenOptions.SecurityKey); 30 | var signingCredentials = SigningCredentialsHelper.CreateSigningCredentials(securityKey); 31 | var jwt = CreateJwtSecurityToken(_tokenOptions, user, signingCredentials, operationClaims); 32 | var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); 33 | var token = jwtSecurityTokenHandler.WriteToken(jwt); 34 | 35 | return new AccessToken 36 | { 37 | Token = token, 38 | Expiration = _accessTokenExpiration 39 | }; 40 | 41 | } 42 | 43 | public JwtSecurityToken CreateJwtSecurityToken(TokenOptions tokenOptions, User user, 44 | SigningCredentials signingCredentials, List operationClaims) 45 | { 46 | var jwt = new JwtSecurityToken( 47 | issuer: tokenOptions.Issuer, 48 | audience: tokenOptions.Audience, 49 | expires: _accessTokenExpiration, 50 | notBefore: DateTime.Now, 51 | claims: SetClaims(user, operationClaims), 52 | signingCredentials: signingCredentials 53 | ); 54 | return jwt; 55 | } 56 | 57 | private IEnumerable SetClaims(User user, List operationClaims) 58 | { 59 | var claims = new List(); 60 | claims.AddNameIdentifier(user.Id.ToString()); 61 | claims.AddEmail(user.Email); 62 | claims.AddName($"{user.FirstName} {user.LastName}"); 63 | claims.AddRoles(operationClaims.Select(c => c.Name).ToArray()); 64 | 65 | return claims; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Core/Utilities/Security/JWT/TokenOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Utilities.Security.JWT 6 | { 7 | public class TokenOptions 8 | { 9 | public string Audience { get; set; } 10 | public string Issuer { get; set; } 11 | public int AccessTokenExpiration { get; set; } 12 | public string SecurityKey { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DataAccess/Abstract/ICategoryDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess; 2 | using Entities.Concrete; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace DataAccess.Abstract 8 | { 9 | public interface ICategoryDal:IEntityRepository 10 | { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DataAccess/Abstract/ICustomerDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess; 2 | using Entities.Concrete; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace DataAccess.Abstract 8 | { 9 | public interface ICustomerDal:IEntityRepository 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /DataAccess/Abstract/IOrderDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess; 2 | using Entities.Concrete; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace DataAccess.Abstract 8 | { 9 | public interface IOrderDal:IEntityRepository 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /DataAccess/Abstract/IProductDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess; 2 | using Entities.Concrete; 3 | using Entities.DTOs; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace DataAccess.Abstract 9 | { 10 | public interface IProductDal:IEntityRepository 11 | { 12 | List GetProductDetails(); 13 | } 14 | } 15 | 16 | //Code Refactoring 17 | -------------------------------------------------------------------------------- /DataAccess/Abstract/IUserDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess; 2 | using Core.Entities.Concrete; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace DataAccess.Abstract 8 | { 9 | public interface IUserDal : IEntityRepository 10 | { 11 | List GetClaims(User user); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DataAccess/Concrete/EntityFramework/EfCategoryDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess.EntityFramework; 2 | using DataAccess.Abstract; 3 | using Entities.Concrete; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using System.Text; 8 | 9 | namespace DataAccess.Concrete.EntityFramework 10 | { 11 | public class EfCategoryDal : EfEntityRepositoryBase, ICategoryDal 12 | { 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /DataAccess/Concrete/EntityFramework/EfOrderDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess.EntityFramework; 2 | using DataAccess.Abstract; 3 | using Entities.Concrete; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace DataAccess.Concrete.EntityFramework 9 | { 10 | public class EfOrderDal:EfEntityRepositoryBase,IOrderDal 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DataAccess/Concrete/EntityFramework/EfProductDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess.EntityFramework; 2 | using DataAccess.Abstract; 3 | using Entities.Concrete; 4 | using Entities.DTOs; 5 | using Microsoft.EntityFrameworkCore; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Linq.Expressions; 10 | using System.Text; 11 | 12 | namespace DataAccess.Concrete.EntityFramework 13 | { 14 | //NuGet 15 | public class EfProductDal : EfEntityRepositoryBase, IProductDal 16 | { 17 | public List GetProductDetails() 18 | { 19 | using (NorthwindContext context = new NorthwindContext()) 20 | { 21 | var result = from p in context.Products 22 | join c in context.Categories 23 | on p.CategoryId equals c.CategoryId 24 | select new ProductDetailDto 25 | { 26 | ProductId = p.ProductId, ProductName = p.ProductName, 27 | CategoryName =c.CategoryName, UnitsInStock = p.UnitsInStock 28 | }; 29 | return result.ToList(); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DataAccess/Concrete/EntityFramework/EfUserDal.cs: -------------------------------------------------------------------------------- 1 | using Core.DataAccess.EntityFramework; 2 | using Core.Entities.Concrete; 3 | using DataAccess.Abstract; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | using System.Linq; 8 | 9 | namespace DataAccess.Concrete.EntityFramework 10 | { 11 | public class EfUserDal : EfEntityRepositoryBase, IUserDal 12 | { 13 | public List GetClaims(User user) 14 | { 15 | using (var context = new NorthwindContext()) 16 | { 17 | var result = from operationClaim in context.OperationClaims 18 | join userOperationClaim in context.UserOperationClaims 19 | on operationClaim.Id equals userOperationClaim.OperationClaimId 20 | where userOperationClaim.UserId == user.Id 21 | select new OperationClaim { Id = operationClaim.Id, Name = operationClaim.Name }; 22 | return result.ToList(); 23 | 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /DataAccess/Concrete/EntityFramework/NorthwindContext.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities.Concrete; 2 | using Entities.Concrete; 3 | using Microsoft.EntityFrameworkCore; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace DataAccess.Concrete.EntityFramework 9 | { 10 | //Context : Db tabloları ile proje classlarını bağlamak 11 | public class NorthwindContext:DbContext 12 | { 13 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 14 | { 15 | optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Northwind;Trusted_Connection=true"); 16 | } 17 | 18 | public DbSet Products { get; set; } 19 | public DbSet Categories { get; set; } 20 | public DbSet Customers { get; set; } 21 | public DbSet Orders { get; set; } 22 | public DbSet OperationClaims { get; set; } 23 | public DbSet Users { get; set; } 24 | public DbSet UserOperationClaims { get; set; } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /DataAccess/Concrete/InMemory/InMemoryProductDal.cs: -------------------------------------------------------------------------------- 1 | using DataAccess.Abstract; 2 | using Entities.Concrete; 3 | using Entities.DTOs; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Text; 9 | 10 | namespace DataAccess.Concrete.InMemory 11 | { 12 | public class InMemoryProductDal : IProductDal 13 | { 14 | List _products; 15 | public InMemoryProductDal() 16 | { 17 | //Oracle,Sql Server, Postgres , MongoDb 18 | _products = new List { 19 | new Product{ProductId=1, CategoryId=1, ProductName="Bardak", UnitPrice=15, UnitsInStock=15}, 20 | new Product{ProductId=2, CategoryId=1, ProductName="Kamera", UnitPrice=500, UnitsInStock=3}, 21 | new Product{ProductId=3, CategoryId=2, ProductName="Telefon", UnitPrice=1500, UnitsInStock=2}, 22 | new Product{ProductId=4, CategoryId=2, ProductName="Klavye", UnitPrice=150, UnitsInStock=65}, 23 | new Product{ProductId=5, CategoryId=2, ProductName="Fare", UnitPrice=85, UnitsInStock=1} 24 | }; 25 | } 26 | public void Add(Product product) 27 | { 28 | _products.Add(product); 29 | } 30 | 31 | public void Delete(Product product) 32 | { 33 | //LINQ - Language Integrated Query 34 | //Lambda 35 | Product productToDelete = _products.SingleOrDefault(p=>p.ProductId ==product.ProductId); 36 | 37 | _products.Remove(productToDelete); 38 | } 39 | 40 | public List GetAll() 41 | { 42 | return _products; 43 | } 44 | 45 | public void Update(Product product) 46 | { 47 | //Gönderdiğim ürün id'sine sahip olan listedeki ürünü bul 48 | Product productToUpdate = _products.SingleOrDefault(p => p.ProductId == product.ProductId); 49 | productToUpdate.ProductName = product.ProductName; 50 | productToUpdate.CategoryId = product.CategoryId; 51 | productToUpdate.UnitPrice = product.UnitPrice; 52 | productToUpdate.UnitsInStock = product.UnitsInStock; 53 | } 54 | 55 | public List GetAllByCategory(int categoryId) 56 | { 57 | return _products.Where(p => p.CategoryId == categoryId).ToList(); 58 | } 59 | 60 | public List GetAll(Expression> filter = null) 61 | { 62 | throw new NotImplementedException(); 63 | } 64 | 65 | public Product Get(Expression> filter) 66 | { 67 | throw new NotImplementedException(); 68 | } 69 | 70 | public List GetProductDetails() 71 | { 72 | throw new NotImplementedException(); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /DataAccess/DataAccess.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Entities/Concrete/Category.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Entities.Concrete 7 | { 8 | //Çıplak Class Kalmasın 9 | public class Category:IEntity 10 | { 11 | public int CategoryId { get; set; } 12 | public string CategoryName { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Entities/Concrete/Customer.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Entities.Concrete 7 | { 8 | public class Customer:IEntity 9 | { 10 | public string CustomerId { get; set; } 11 | public string ContactName { get; set; } 12 | public string CompanyName { get; set; } 13 | public string City { get; set; } 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Entities/Concrete/Order.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Entities.Concrete 7 | { 8 | public class Order:IEntity 9 | { 10 | public int OrderId { get; set; } 11 | public string CustomerId { get; set; } 12 | public int EmployeeId { get; set; } 13 | public DateTime OrderDate { get; set; } 14 | public string ShipCity { get; set; } 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Entities/Concrete/Product.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel.DataAnnotations; 5 | using System.Text; 6 | 7 | namespace Entities.Concrete 8 | { 9 | public class Product:IEntity 10 | { 11 | public int ProductId { get; set; } 12 | public int CategoryId { get; set; } 13 | public string ProductName { get; set; } 14 | public short UnitsInStock { get; set; } 15 | public decimal UnitPrice { get; set; } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Entities/DTOs/ProductDetailDTO.cs: -------------------------------------------------------------------------------- 1 |  2 | using Core.Entities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Entities.DTOs 8 | { 9 | public class ProductDetailDto:IDto 10 | { 11 | public int ProductId { get; set; } 12 | public string ProductName { get; set; } 13 | public string CategoryName { get; set; } 14 | public short UnitsInStock { get; set; } 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Entities/DTOs/UserForLoginDto.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | 3 | namespace Entities.DTOs 4 | { 5 | public class UserForLoginDto : IDto 6 | { 7 | public string Email { get; set; } 8 | public string Password { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Entities/DTOs/UserForRegisterDto.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Entities.DTOs 7 | { 8 | public class UserForRegisterDto : IDto 9 | { 10 | public string Email { get; set; } 11 | public string Password { get; set; } 12 | public string FirstName { get; set; } 13 | public string LastName { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Entities/Entities.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /MyFinalProject.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30907.101 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataAccess", "DataAccess\DataAccess.csproj", "{E578DD64-9DED-4E7C-9347-B1250B8C4A8B}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Business", "Business\Business.csproj", "{AE165F6D-7905-4A77-A024-8AEB8F615FCD}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "Entities\Entities.csproj", "{5D20B6CE-2802-462E-8B67-17D8AC377DB1}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleUI", "ConsoleUI\ConsoleUI.csproj", "{752C2D61-41BC-463B-A49F-E03D1DBD394E}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "Core\Core.csproj", "{EDB55B09-2584-4F27-83A4-C1AC1BFB6415}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAPI", "WebAPI\WebAPI.csproj", "{7181CB93-3DA6-430D-B4D0-4D2B41519F9C}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {E578DD64-9DED-4E7C-9347-B1250B8C4A8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {E578DD64-9DED-4E7C-9347-B1250B8C4A8B}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {E578DD64-9DED-4E7C-9347-B1250B8C4A8B}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {E578DD64-9DED-4E7C-9347-B1250B8C4A8B}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {AE165F6D-7905-4A77-A024-8AEB8F615FCD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {AE165F6D-7905-4A77-A024-8AEB8F615FCD}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {AE165F6D-7905-4A77-A024-8AEB8F615FCD}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {AE165F6D-7905-4A77-A024-8AEB8F615FCD}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {5D20B6CE-2802-462E-8B67-17D8AC377DB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {5D20B6CE-2802-462E-8B67-17D8AC377DB1}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {5D20B6CE-2802-462E-8B67-17D8AC377DB1}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {5D20B6CE-2802-462E-8B67-17D8AC377DB1}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {752C2D61-41BC-463B-A49F-E03D1DBD394E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {752C2D61-41BC-463B-A49F-E03D1DBD394E}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {752C2D61-41BC-463B-A49F-E03D1DBD394E}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {752C2D61-41BC-463B-A49F-E03D1DBD394E}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {EDB55B09-2584-4F27-83A4-C1AC1BFB6415}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {EDB55B09-2584-4F27-83A4-C1AC1BFB6415}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {EDB55B09-2584-4F27-83A4-C1AC1BFB6415}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {EDB55B09-2584-4F27-83A4-C1AC1BFB6415}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {7181CB93-3DA6-430D-B4D0-4D2B41519F9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {7181CB93-3DA6-430D-B4D0-4D2B41519F9C}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {7181CB93-3DA6-430D-B4D0-4D2B41519F9C}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {7181CB93-3DA6-430D-B4D0-4D2B41519F9C}.Release|Any CPU.Build.0 = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | GlobalSection(ExtensibilityGlobals) = postSolution 53 | SolutionGuid = {D0BDB177-FE54-4D5A-AEAD-D66B79C5F1EE} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /WebAPI/Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Entities.DTOs; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace WebAPI.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [ApiController] 13 | public class AuthController : Controller 14 | { 15 | private IAuthService _authService; 16 | 17 | public AuthController(IAuthService authService) 18 | { 19 | _authService = authService; 20 | } 21 | 22 | [HttpPost("login")] 23 | public ActionResult Login(UserForLoginDto userForLoginDto) 24 | { 25 | var userToLogin = _authService.Login(userForLoginDto); 26 | if (!userToLogin.Success) 27 | { 28 | return BadRequest(userToLogin.Message); 29 | } 30 | 31 | var result = _authService.CreateAccessToken(userToLogin.Data); 32 | if (result.Success) 33 | { 34 | return Ok(result.Data); 35 | } 36 | 37 | return BadRequest(result.Message); 38 | } 39 | 40 | [HttpPost("register")] 41 | public ActionResult Register(UserForRegisterDto userForRegisterDto) 42 | { 43 | var userExists = _authService.UserExists(userForRegisterDto.Email); 44 | if (!userExists.Success) 45 | { 46 | return BadRequest(userExists.Message); 47 | } 48 | 49 | var registerResult = _authService.Register(userForRegisterDto, userForRegisterDto.Password); 50 | var result = _authService.CreateAccessToken(registerResult.Data); 51 | if (result.Success) 52 | { 53 | return Ok(result.Data); 54 | } 55 | 56 | return BadRequest(result.Message); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /WebAPI/Controllers/CategoriesController.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace WebAPI.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [ApiController] 13 | public class CategoriesController : ControllerBase 14 | { 15 | private ICategoryService _categoryService; 16 | public CategoriesController(ICategoryService categoryService) 17 | { 18 | _categoryService = categoryService; 19 | } 20 | [HttpGet("getall")] 21 | public IActionResult GetAll() 22 | { 23 | var result = _categoryService.GetAll(); 24 | if (result.Success) 25 | { 26 | return Ok(result); 27 | } 28 | return BadRequest(result); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /WebAPI/Controllers/ProductsController.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Business.Concrete; 3 | using DataAccess.Concrete.EntityFramework; 4 | using Entities.Concrete; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading; 11 | using System.Threading.Tasks; 12 | 13 | namespace WebAPI.Controllers 14 | { 15 | [Route("api/[controller]")] 16 | [ApiController] 17 | public class ProductsController : ControllerBase 18 | { 19 | //Loosely coupled 20 | //naming convention 21 | //IoC Container -- Inversion of Control 22 | IProductService _productService; 23 | 24 | public ProductsController(IProductService productService) 25 | { 26 | _productService = productService; 27 | } 28 | 29 | [HttpGet("getall")] 30 | public IActionResult GetAll() 31 | { 32 | //Swagger 33 | //Dependency chain -- 34 | //Thread.Sleep(5000); 35 | var result = _productService.GetAll(); 36 | if (result.Success) 37 | { 38 | return Ok(result); 39 | } 40 | return BadRequest(result); 41 | 42 | } 43 | 44 | [HttpGet("getbyid")] 45 | public IActionResult GetById(int id) 46 | { 47 | var result = _productService.GetById(id); 48 | if (result.Success) 49 | { 50 | return Ok(result); 51 | } 52 | 53 | return BadRequest(result); 54 | } 55 | 56 | [HttpPost("add")] 57 | public IActionResult Add(Product product) 58 | { 59 | var result = _productService.Add(product); 60 | if (result.Success) 61 | { 62 | return Ok(result); 63 | } 64 | return BadRequest(result); 65 | } 66 | [HttpGet("GetByCategory")] 67 | public IActionResult GetByCategory(int categoryId) 68 | { 69 | var result = _productService.GetAllByCategoryId(categoryId); 70 | if (result.Success) 71 | { 72 | return Ok(result); 73 | } 74 | return BadRequest(result); 75 | } 76 | 77 | 78 | } 79 | } 80 | 81 | 82 | //22.05 DERSTEYİZ -------------------------------------------------------------------------------- /WebAPI/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace WebAPI.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public WeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /WebAPI/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Business.DependencyResolvers.Autofac; 4 | using Microsoft.AspNetCore.Hosting; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.Hosting; 7 | using Microsoft.Extensions.Logging; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Threading.Tasks; 12 | 13 | namespace WebAPI 14 | { 15 | public class Program 16 | { 17 | public static void Main(string[] args) 18 | { 19 | CreateHostBuilder(args).Build().Run(); 20 | } 21 | 22 | public static IHostBuilder CreateHostBuilder(string[] args) => 23 | Host.CreateDefaultBuilder(args) 24 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 25 | .ConfigureContainer(builder => 26 | { 27 | builder.RegisterModule(new AutofacBusinessModule()); 28 | }) 29 | .ConfigureWebHostDefaults(webBuilder => 30 | { 31 | webBuilder.UseStartup(); 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /WebAPI/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:56515", 8 | "sslPort": 44314 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 | "WebAPI": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /WebAPI/Startup.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Business.Concrete; 3 | using Core.DependencyResolvers; 4 | using Core.Extensions; 5 | using Core.Utilities.IoC; 6 | using Core.Utilities.Security.Encryption; 7 | using Core.Utilities.Security.JWT; 8 | using DataAccess.Abstract; 9 | using DataAccess.Concrete.EntityFramework; 10 | using Microsoft.AspNetCore.Authentication.JwtBearer; 11 | using Microsoft.AspNetCore.Builder; 12 | using Microsoft.AspNetCore.Hosting; 13 | using Microsoft.AspNetCore.Http; 14 | using Microsoft.AspNetCore.HttpsPolicy; 15 | using Microsoft.AspNetCore.Mvc; 16 | using Microsoft.Extensions.Configuration; 17 | using Microsoft.Extensions.DependencyInjection; 18 | using Microsoft.Extensions.Hosting; 19 | using Microsoft.Extensions.Logging; 20 | using Microsoft.IdentityModel.Tokens; 21 | using System; 22 | using System.Collections.Generic; 23 | using System.Linq; 24 | using System.Threading.Tasks; 25 | 26 | namespace WebAPI 27 | { 28 | public class Startup 29 | { 30 | public Startup(IConfiguration configuration) 31 | { 32 | Configuration = configuration; 33 | } 34 | 35 | public IConfiguration Configuration { get; } 36 | 37 | // This method gets called by the runtime. Use this method to add services to the container. 38 | public void ConfigureServices(IServiceCollection services) 39 | { 40 | //AOP 41 | //Autofac, Ninject,CastleWindsor, StructureMap, LightInject, DryInject -->IoC Container 42 | //AOP 43 | //Postsharp 44 | services.AddControllers(); 45 | //services.AddSingleton(); 46 | //services.AddSingleton(); 47 | 48 | 49 | services.AddCors(); 50 | var tokenOptions = Configuration.GetSection("TokenOptions").Get(); 51 | 52 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 53 | .AddJwtBearer(options => 54 | { 55 | options.TokenValidationParameters = new TokenValidationParameters 56 | { 57 | ValidateIssuer = true, 58 | ValidateAudience = true, 59 | ValidateLifetime = true, 60 | ValidIssuer = tokenOptions.Issuer, 61 | ValidAudience = tokenOptions.Audience, 62 | ValidateIssuerSigningKey = true, 63 | IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey) 64 | }; 65 | }); 66 | 67 | services.AddDependencyResolvers(new ICoreModule[] { 68 | new CoreModule() 69 | }); 70 | 71 | } 72 | 73 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 74 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 75 | { 76 | if (env.IsDevelopment()) 77 | { 78 | app.UseDeveloperExceptionPage(); 79 | } 80 | app.ConfigureCustomExceptionMiddleware(); 81 | app.UseCors(builder=>builder.WithOrigins("http://localhost:4200").AllowAnyHeader()); 82 | app.UseHttpsRedirection(); 83 | 84 | app.UseRouting(); 85 | 86 | app.UseAuthentication(); 87 | 88 | app.UseAuthorization(); 89 | 90 | app.UseEndpoints(endpoints => 91 | { 92 | endpoints.MapControllers(); 93 | }); 94 | //23.10 dersteyiz 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /WebAPI/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /WebAPI/WebAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /WebAPI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /WebAPI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "TokenOptions": { 3 | "Audience": "engin@engin.com", 4 | "Issuer": "engin@engin.com", 5 | "AccessTokenExpiration": 10, 6 | "SecurityKey": "mysupersecretkeymysupersecretkey" 7 | }, 8 | "Logging": { 9 | "LogLevel": { 10 | "Default": "Information", 11 | "Microsoft": "Warning", 12 | "Microsoft.Hosting.Lifetime": "Information" 13 | } 14 | }, 15 | "AllowedHosts": "*" 16 | } 17 | --------------------------------------------------------------------------------