├── .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 ├── 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 ├── UsersController.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 | 6 | namespace Business.Abstract 7 | { 8 | public interface IAuthService 9 | { 10 | IDataResult Register(UserForRegisterDto userForRegisterDto, string password); 11 | IDataResult Login(UserForLoginDto userForLoginDto); 12 | IResult UserExists(string email); 13 | IDataResult CreateAccessToken(User user); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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< List> GetAll(); 12 | IDataResult GetById(int categoryId); 13 | IResult Add(Category category); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /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 | 20 | IResult AddTransactionalTest(Product product); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Business/Abstract/IUserService.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities.Concrete; 2 | using Core.Utilities.Results; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Business.Abstract 8 | { 9 | public interface IUserService 10 | { 11 | IResult Add(User user); 12 | IResult Update(User user); 13 | IResult Delete(User user); 14 | IDataResult GetByUserId(int id); 15 | IDataResult> GetAllUsers(); 16 | IDataResult> GetClaims(User user); 17 | IDataResult GetByMail(string email); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /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 Microsoft.AspNetCore.Http; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | using Core.Extensions; 7 | using Castle.DynamicProxy; 8 | using Business.Constants; 9 | using Core.Utilities.IoC; 10 | using Microsoft.Extensions.DependencyInjection; 11 | 12 | 13 | namespace Business.BusinessAspects.Autofac 14 | { 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 | 4 | namespace Business.CCS 5 | { 6 | public class DatabaseLogger : ILogger 7 | { 8 | public void Log() 9 | { 10 | Console.WriteLine("Veri tabanına Loglandı"); 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 | -------------------------------------------------------------------------------- /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 |  2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | using Business.Abstract; 6 | using Business.Constants; 7 | using Core.Entities.Concrete; 8 | using Core.Utilities.Results; 9 | using Core.Utilities.Security.Hashing; 10 | using Core.Utilities.Security.JWT; 11 | using Entities.DTOs; 12 | 13 | namespace Business.Concrete 14 | { 15 | public class AuthManager : IAuthService 16 | { 17 | private IUserService _userService; 18 | private ITokenHelper _tokenHelper; 19 | 20 | public AuthManager(IUserService userService, ITokenHelper tokenHelper) 21 | { 22 | _userService = userService; 23 | _tokenHelper = tokenHelper; 24 | } 25 | 26 | public IDataResult Register(UserForRegisterDto userForRegisterDto, string password) 27 | { 28 | byte[] passwordHash, passwordSalt; 29 | HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt); 30 | var user = new User 31 | { 32 | Email = userForRegisterDto.Email, 33 | FirstName = userForRegisterDto.FirstName, 34 | LastName = userForRegisterDto.LastName, 35 | PasswordHash = passwordHash, 36 | PasswordSalt = passwordSalt, 37 | Status = true 38 | }; 39 | _userService.Add(user); 40 | return new SuccessDataResult(user, Messages.UserRegistered); 41 | } 42 | 43 | public IDataResult Login(UserForLoginDto userForLoginDto) 44 | { 45 | var userToCheck = _userService.GetByMail(userForLoginDto.Email); 46 | if (userToCheck == null) 47 | { 48 | return new ErrorDataResult(Messages.UserNotFound); 49 | } 50 | 51 | if (!HashingHelper.VerifyPasswordHash(userForLoginDto.Password, userToCheck.Data.PasswordHash, userToCheck.Data.PasswordSalt)) 52 | { 53 | return new ErrorDataResult(Messages.PasswordError); 54 | } 55 | 56 | return new SuccessDataResult(userToCheck.Data, Messages.SuccessfulLogin); 57 | } 58 | 59 | public IResult UserExists(string email) 60 | { 61 | if (_userService.GetByMail(email).Data != null) 62 | { 63 | return new ErrorResult(Messages.UserAlreadyExists); 64 | } 65 | return new SuccessResult(); 66 | } 67 | 68 | public IDataResult CreateAccessToken(User user) 69 | { 70 | var claims = _userService.GetClaims(user); 71 | var accessToken = _tokenHelper.CreateToken(user, claims.Data); 72 | return new SuccessDataResult(accessToken, Messages.AccessTokenCreated); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /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 | public CategoryManager(ICategoryDal categoryDal) 15 | { 16 | _categorydal = categoryDal; 17 | } 18 | 19 | public IResult Add(Category category) 20 | { 21 | _categorydal.Add(category); 22 | return new SuccessResult(); 23 | } 24 | 25 | public IDataResult< List> GetAll() 26 | { 27 | return new SuccessDataResult>( _categorydal.GetAll()); 28 | } 29 | 30 | public IDataResult GetById(int categoryId) 31 | { 32 | return new SuccessDataResult( _categorydal.Get(c=>c.CategoryId==categoryId)); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Business/Concrete/ProductManager.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Business.BusinessAspects.Autofac; 3 | using Business.CCS; 4 | using Business.Constants; 5 | using Business.ValidationRules.FluentValidation; 6 | using Core.Aspects.Autofac.Caching; 7 | using Core.Aspects.Autofac.Performance; 8 | using Core.Aspects.Autofac.Transaction; 9 | using Core.Aspects.Autofac.Validation; 10 | using Core.CrossCuttingConcerns.Validation; 11 | using Core.Utilities.Business; 12 | using Core.Utilities.Results; 13 | using DataAccess.Abstract; 14 | using DataAccess.Concrete.InMemory; 15 | using Entities.Concrete; 16 | using Entities.DTOs; 17 | using FluentValidation; 18 | using System; 19 | using System.Collections.Generic; 20 | using System.Linq; 21 | using System.Text; 22 | 23 | namespace Business.Concrete 24 | { 25 | public class ProductManager : IProductService 26 | { 27 | IProductDal _productDal; 28 | ICategoryService _categoryService; 29 | 30 | public ProductManager(IProductDal productDal, ICategoryService categoryService) 31 | { 32 | _productDal = productDal; 33 | 34 | _categoryService = categoryService; 35 | 36 | 37 | } 38 | //[SecuredOperation("senpai,admin,product.add")] 39 | [ValidationAspect(typeof(ProductValidator))] 40 | [CacheRemoveAspect("IProductService.Get")] 41 | public IResult Add(Product product) 42 | { 43 | IResult result = BusinessRules.Run(CheckIfProductCountOfCategoryCorrect(product.CategoryId), 44 | CheckIfProductNameExists(product.ProductName), CheckIfCategoryLimitExceded()); 45 | 46 | if (result != null) 47 | { 48 | return result; 49 | } 50 | 51 | _productDal.Add(product); 52 | return new SuccessResult(Messages.ProductAdded); 53 | 54 | 55 | } 56 | // [PerformanceAspect(4)] 57 | [CacheAspect] 58 | public IDataResult> GetAll() 59 | { 60 | //iş kodları 61 | //yetkisi varsa 62 | 63 | 64 | return new SuccessDataResult>(_productDal.GetAll(), Messages.DefaultS); 65 | 66 | } 67 | 68 | public IDataResult> GetAllByCategoryId(int id) 69 | { 70 | return new SuccessDataResult>(_productDal.GetAll(p => p.CategoryId == id)); 71 | } 72 | [CacheAspect] 73 | public IDataResult GetById(int productId) 74 | { 75 | return new SuccessDataResult(_productDal.Get(p => p.ProductId == productId)); 76 | } 77 | 78 | public IDataResult> GetByUnitPrice(decimal min, decimal max) 79 | { 80 | return new SuccessDataResult>(_productDal.GetAll(p => p.UnitPrice >= min && p.UnitPrice <= max)); 81 | } 82 | 83 | public IDataResult> GetProductDetails() 84 | { 85 | return new SuccessDataResult>(_productDal.GetProductDetails()); 86 | } 87 | [ValidationAspect(typeof(ProductValidator))] 88 | [CacheRemoveAspect("IProductService.Get")] 89 | public IResult Update(Product product) 90 | { 91 | 92 | _productDal.Add(product); 93 | return new SuccessResult(Messages.ProductAdded); 94 | } 95 | private IResult CheckIfProductCountOfCategoryCorrect(int categoryId) 96 | { 97 | var result = _productDal.GetAll(c => c.CategoryId == categoryId).Count; 98 | 99 | if (result >= 30) 100 | { 101 | return new ErrorResult(Messages.DefaultE); 102 | } 103 | return new SuccessResult(Messages.DefaultS); 104 | } 105 | private IResult CheckIfProductNameExists(string productName) 106 | { 107 | var result = _productDal.GetAll(p => p.ProductName == productName).Any(); 108 | 109 | if (result) 110 | { 111 | return new ErrorResult(Messages.DefaultE); 112 | 113 | } 114 | return new SuccessResult(Messages.DefaultS); 115 | } 116 | private IResult CheckIfCategoryLimitExceded() 117 | 118 | { 119 | var result = _categoryService.GetAll(); 120 | 121 | if (result.Data.Count > 25) 122 | { 123 | return new ErrorResult(Messages.DefaultE); 124 | 125 | } 126 | return new SuccessResult(Messages.DefaultS); 127 | } 128 | [TransactionScopeAspect] 129 | public IResult AddTransactionalTest(Product product) 130 | { 131 | _productDal.Update(product); 132 | _productDal.Add(product); 133 | return new SuccessResult(Messages.ProductUpdated); 134 | 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /Business/Concrete/UserManager.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Business.Constants; 3 | using Core.Aspects.Autofac.Validation; 4 | using Core.Entities.Concrete; 5 | using Core.Utilities.Results; 6 | using DataAccess.Abstract; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Text; 10 | 11 | namespace Business.Concrete 12 | { 13 | 14 | public class UserManager : IUserService 15 | { 16 | IUserDal _userDal; 17 | public UserManager(IUserDal userDal) 18 | { 19 | _userDal = userDal; 20 | } 21 | //[ValidationAspect(typeof(UserValidator))] 22 | public IResult Add(User user) 23 | { 24 | _userDal.Add(user); 25 | return new SuccessResult(Messages.Added); 26 | } 27 | 28 | public IResult Delete(User user) 29 | { 30 | _userDal.Delete(user); 31 | return new SuccessResult(Messages.Deleted); 32 | } 33 | 34 | public IDataResult> GetAllUsers() 35 | { 36 | return new SuccessDataResult>(_userDal.GetAll(), Messages.UsersListed); 37 | } 38 | 39 | public IDataResult GetByUserId(int id) 40 | { 41 | return new SuccessDataResult(_userDal.Get(u => u.Id == id), Messages.UsersListed); 42 | } 43 | 44 | public IResult Update(User user) 45 | { 46 | _userDal.Update(user); 47 | return new SuccessResult(Messages.Updated); 48 | } 49 | public IDataResult> GetClaims(User user) 50 | { 51 | var getClaims = _userDal.GetClaims(user); 52 | return new SuccessDataResult>(getClaims); 53 | } 54 | public IDataResult GetByMail(string email) 55 | { 56 | var getByMail = _userDal.Get(u => u.Email == email); 57 | return new SuccessDataResult(getByMail); 58 | } 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Business/Constants/Messages.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.Serialization; 4 | using System.Text; 5 | 6 | namespace Business.Constants 7 | { 8 | public static class Messages 9 | { 10 | public static string Added = "Ekleme işlemi gerçekleşti"; 11 | public static string Deleted = "Silme işlemi gerçekleşti"; 12 | public static string Updated = "Güncelleme işlemi gerçekleşti"; 13 | public static string Rented = "Kiralama gerçekleşti"; 14 | public static string RentOff = "Sözleşme iptal edildi"; 15 | public static string RentUpdate = "Sözleşme güncellendi"; 16 | public static string RentList = "Sözleşmeler Listelendi"; 17 | public static string RentGet = "Sözleşme Getirildi"; 18 | public static string UsersListed = "Kullanıcılar Listelendi"; 19 | public static string UserListed = "Kullanıcı Listelendi"; 20 | public static string CustomersListed = "Müşteriler Listelendi"; 21 | public static string CustomerListed = "Müşteri Listelendi"; 22 | public static string ReturnDateNull = "Araba mevcut değil"; 23 | public static string CantDeleted = "Silme başarısız"; 24 | public static string UserNotFound = "Kullanıcı bulunamadı"; 25 | public static string PasswordError = "Şifre hatalı"; 26 | public static string SuccessfulLogin = "Sisteme giriş başarılı"; 27 | public static string UserAlreadyExists = "Bu kullanıcı zaten mevcut"; 28 | public static string UserRegistered = "Kullanıcı başarıyla kaydedildi"; 29 | public static string AccessTokenCreated = "Access token başarıyla oluşturuldu"; 30 | public static string AuthorizationDenied = "Yetkiniz yok"; 31 | public static string ProductNameAlreadyExists = "Ürün ismi zaten mevcut"; 32 | public static string ColorsListed = "Renkler listelendi"; 33 | public static string CantAdded = "Ekleme başarısız"; 34 | public static string CarsListed = "Arabalar listelendi"; 35 | public static string ColorAddInvalid = "Var olan Renk eklenemez"; 36 | public static string BrandAddInvalid = "Var olan Marka eklenemez"; 37 | public static string ImagesAdded = "Görüntü Eklendi"; 38 | public static string ImagesCantAdded = "Ekleme başarısız"; 39 | public static string ProductAdded = "Ürün başarıyla eklendi"; 40 | public static string ProductDeleted = "Ürün başarıyla silindi"; 41 | public static string ProductUpdated = "Ürün başarıyla güncellendi"; 42 | public static string DefaultS = "Başarılı"; 43 | public static string DefaultE = "Başarısız"; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /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 | builder.RegisterType().As().SingleInstance(); 23 | builder.RegisterType().As().SingleInstance(); 24 | builder.RegisterType().As().SingleInstance(); 25 | builder.RegisterType().As().SingleInstance(); 26 | builder.RegisterType().As().SingleInstance(); 27 | builder.RegisterType().As().SingleInstance(); 28 | builder.RegisterType().As(); 29 | builder.RegisterType().As(); 30 | 31 | 32 | 33 | 34 | var assembly = System.Reflection.Assembly.GetExecutingAssembly(); 35 | 36 | builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces() 37 | .EnableInterfaceInterceptors(new ProxyGenerationOptions() 38 | { 39 | Selector = new AspectInterceptorSelector() 40 | }).SingleInstance(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /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 | 15 | RuleFor(p=>p.ProductName).MinimumLength(2); 16 | RuleFor(p => p.UnitPrice).NotEmpty(); 17 | RuleFor(p => p.UnitPrice).GreaterThan(0); 18 | RuleFor(p => p.UnitPrice).GreaterThanOrEqualTo(10).When(p => p.CategoryId == 1); 19 | RuleFor(p => p.ProductName).Must(StartWithA).WithMessage("Ürünler A harfi ile başlamalı"); 20 | } 21 | 22 | private bool StartWithA(string arg) 23 | { 24 | return arg.StartsWith("A"); 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 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | //ProductTest(); 13 | //CategoryTest(); 14 | NorthwindContext northwind = new NorthwindContext(); 15 | foreach (var item in northwind.Customers) 16 | { 17 | Console.WriteLine(item.ContactName); 18 | } 19 | 20 | } 21 | 22 | private static void CategoryTest() 23 | { 24 | CategoryManager categoryManager = new CategoryManager(new EfCategoryDal()); 25 | foreach (var category in categoryManager.GetAll().Data) 26 | { 27 | Console.WriteLine(category.CategoryName); 28 | } 29 | } 30 | 31 | private static void ProductTest() 32 | { 33 | ProductManager productManager = new ProductManager(new EfProductDal(),new CategoryManager(new EfCategoryDal())); 34 | 35 | var result = productManager.GetProductDetails(); 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 | //foreach (var product in productManager.GetProductDetails().Data) 49 | //{ 50 | // Console.WriteLine(product.ProductName+" - "+product.CategoryName); 51 | //} 52 | //Console.WriteLine("Hello World!"); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Core/Aspects/Autofac/Caching/CacheAspect.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 | 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 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 | 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 Core.Utilities.Interceptors; 2 | using Core.Utilities.IoC; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.Text; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Castle.DynamicProxy; 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 13 | { 14 | private Type _validatorType; 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 | _validatorType = validatorType; 23 | } 24 | protected override void OnBefore(IInvocation invocation) 25 | { 26 | var validator = (IValidator)Activator.CreateInstance(_validatorType); 27 | var entityType = _validatorType.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 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /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 | T Get(string key); 10 | object Get(string key); 11 | void Add(string key, object value,int duration); 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.Linq; 6 | using System.Text; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using System.Text.RegularExpressions; 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 | public T Get(string key) 25 | { 26 | return _memoryCache.Get(key); 27 | } 28 | 29 | public object Get(string key) 30 | { 31 | return _memoryCache.Get(key); 32 | } 33 | 34 | public bool IsAdd(string key) 35 | { 36 | return _memoryCache.TryGetValue(key, out _); 37 | } 38 | 39 | public void Remove(string key) 40 | { 41 | _memoryCache.Remove(key); 42 | } 43 | 44 | public void RemoveByPattern(string pattern) 45 | { // çalışma anında bellekten siliyor with reflection ... 46 | var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 47 | var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; 48 | List cacheCollectionValues = new List(); 49 | 50 | foreach (var cacheItem in cacheEntriesCollection) 51 | { 52 | ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); 53 | cacheCollectionValues.Add(cacheItemValue); 54 | } 55 | 56 | var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); 57 | var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); 58 | 59 | foreach (var key in keysToRemove) 60 | { 61 | _memoryCache.Remove(key); 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /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 | 14 | var result = validator.Validate(context); 15 | if (!result.IsValid) 16 | { 17 | throw new ValidationException(result.Errors); 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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 | 10 | namespace Core.DataAccess.EntityFramework 11 | { 12 | public class EfEntityRepositoryBase:IEntityRepository 13 | where TEntity: class ,IEntity,new() 14 | where TContext: DbContext,new() 15 | { 16 | public void Add(TEntity entity) 17 | { 18 | 19 | using (TContext context = new TContext()) 20 | { 21 | var addedEntity = context.Entry(entity); 22 | addedEntity.State = EntityState.Added; 23 | context.SaveChanges(); 24 | } 25 | } 26 | 27 | public void Delete(TEntity entity) 28 | { 29 | using (TContext context = new TContext()) 30 | { 31 | var deletedEntity = context.Entry(entity); 32 | deletedEntity.State = EntityState.Deleted; 33 | context.SaveChanges(); 34 | } 35 | } 36 | 37 | public TEntity Get(Expression> filter) 38 | { 39 | using (TContext context = new TContext()) 40 | { 41 | return context.Set().SingleOrDefault(filter); 42 | } 43 | } 44 | 45 | public List GetAll(Expression> filter = null) 46 | { 47 | using (TContext context = new TContext()) 48 | { 49 | return filter == null ? context.Set().ToList() : context.Set().Where(filter).ToList(); 50 | } 51 | } 52 | 53 | public void Update(TEntity entity) 54 | { 55 | using (TContext context = new TContext()) 56 | { 57 | var UpdatedEntity = context.Entry(entity); 58 | UpdatedEntity.State = EntityState.Modified; 59 | context.SaveChanges(); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /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 | 8 | namespace Core.DataAccess 9 | {//generic constraint 10 | //Class : reference type 11 | public interface IEntityRepository where T:class,IEntity,new() 12 | { 13 | List GetAll(Expression>filter=null); 14 | 15 | T Get(Expression> filter ); 16 | 17 | void Add(T entity); 18 | void Update(T entity); 19 | void Delete(T entity); 20 | 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Entities.Concrete 6 | { 7 | public class OperationClaim : IEntity 8 | { 9 | public int Id { get; set; } 10 | public string Name { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /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[] PasswordHash { get; set; } 14 | public byte[] PasswordSalt { get; set; } 15 | public bool Status { get; set; } 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Core/Entities/Concrete/UserOperationClaim.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Core.Entities.Concrete 6 | { 7 | public class UserOperationClaim : IEntity 8 | { 9 | public int Id { get; set; } 10 | public int UserId { get; set; } 11 | public int OperationClaimId { get; set; } 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /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 | { // IEntity implement eden class bir veritabanı tablosudur. 7 | public interface IEntity 8 | { 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Core/Extensions/ClaimExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Linq; 5 | using System.Security.Claims; 6 | using System.Text; 7 | 8 | namespace Core.Extensions 9 | { 10 | public static class ClaimExtensions 11 | { 12 | public static void AddEmail(this ICollection claims, string email) 13 | { 14 | claims.Add(new Claim(JwtRegisteredClaimNames.Email, email)); 15 | } 16 | 17 | public static void AddName(this ICollection claims, string name) 18 | { 19 | claims.Add(new Claim(ClaimTypes.Name, name)); 20 | } 21 | 22 | public static void AddNameIdentifier(this ICollection claims, string nameIdentifier) 23 | { 24 | claims.Add(new Claim(ClaimTypes.NameIdentifier, nameIdentifier)); 25 | } 26 | 27 | public static void AddRoles(this ICollection claims, string[] roles) 28 | { 29 | roles.ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role))); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Core/Extensions/ClaimsPrincipalExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Text; 6 | 7 | namespace Core.Extensions 8 | { 9 | public static class ClaimsPrincipalExtensions 10 | { 11 | public static List Claims(this ClaimsPrincipal claimsPrincipal, string claimType) 12 | { 13 | var result = claimsPrincipal?.FindAll(claimType)?.Select(x => x.Value).ToList(); 14 | return result; 15 | } 16 | 17 | public static List ClaimRoles(this ClaimsPrincipal claimsPrincipal) 18 | { 19 | return claimsPrincipal?.Claims(ClaimTypes.Role); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Core/Extensions/ErrorDetails.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation.Results; 2 | using Newtonsoft.Json; 3 | using System.Collections.Generic; 4 | 5 | namespace Core.Extensions 6 | { 7 | public class ErrorDetails 8 | { 9 | public string Message { get; set; } 10 | public int StatusCode { get; set; } 11 | 12 | 13 | public override string ToString() 14 | { 15 | return JsonConvert.SerializeObject(this); 16 | } 17 | } 18 | public class ValidationErrorDetails : ErrorDetails 19 | { 20 | public IEnumerable Errors { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Core/Extensions/ExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using FluentValidation.Results; 3 | using Microsoft.AspNetCore.Http; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Net; 7 | using System.Text; 8 | using System.Threading.Tasks; 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 | StatusCode=400, 48 | Message=message, 49 | Errors=errors, 50 | }.ToString()); 51 | } 52 | 53 | return httpContext.Response.WriteAsync(new ErrorDetails 54 | { 55 | StatusCode = httpContext.Response.StatusCode, 56 | Message = message 57 | }.ToString()); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Core/Extensions/ExceptionMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 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 | } 16 | -------------------------------------------------------------------------------- /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(this IServiceCollection servicesCollection, 12 | ICoreModule[] modules) 13 | { 14 | foreach (var module in modules) 15 | { 16 | module.Load(servicesCollection); 17 | } 18 | 19 | return ServiceTool.Create(servicesCollection); 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 | return null; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Core/Utilities/Interceptors/AspectInterceptorSelector.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using Core.Aspects.Autofac.Performance; 3 | using System; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using System.Reflection; 7 | 8 | namespace Core.Utilities.Interceptors 9 | { 10 | public class AspectInterceptorSelector : IInterceptorSelector 11 | { 12 | public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors) 13 | { 14 | var classAttributes = type.GetCustomAttributes 15 | (true).ToList(); 16 | var methodAttributes = type.GetMethod(method.Name) 17 | .GetCustomAttributes(true); 18 | classAttributes.AddRange(methodAttributes); 19 | //classAttributes.Add(new ExceptionLogAspect(typeof(FileLogger))); 20 | classAttributes.Add(new PerformanceAspect(5)); 21 | return classAttributes.OrderBy(x => x.Priority).ToArray(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /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 | protected virtual void OnBefore(IInvocation invocation) { } 9 | protected virtual void OnAfter(IInvocation invocation) { } 10 | protected virtual void OnException(IInvocation invocation, System.Exception e) { } 11 | protected virtual void OnSuccess(IInvocation invocation) { } 12 | public override void Intercept(IInvocation invocation) 13 | { 14 | var isSuccess = true; 15 | OnBefore(invocation); 16 | try 17 | { 18 | invocation.Proceed(); 19 | } 20 | catch (Exception e) 21 | { 22 | isSuccess = false; 23 | OnException(invocation, e); 24 | throw; 25 | } 26 | finally 27 | { 28 | if (isSuccess) 29 | { 30 | OnSuccess(invocation); 31 | } 32 | } 33 | OnAfter(invocation); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Core/Utilities/Interceptors/MethodInterceptionBaseAttribute.cs: -------------------------------------------------------------------------------- 1 | using Castle.DynamicProxy; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Core.Utilities.Interceptors 7 | { 8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] 9 | public abstract class MethodInterceptionBaseAttribute : Attribute, IInterceptor 10 | { 11 | public int Priority { get; set; } 12 | 13 | public virtual void Intercept(IInvocation invocation) 14 | { 15 | 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /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 collection); 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 T Data { get; } 10 | 11 | public DataResult(T data,bool success,string message):base(success,message) 12 | { 13 | Data = data; 14 | } 15 | public DataResult(T data,bool success):base(success) 16 | { 17 | Data = data; 18 | } 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 | public ErrorDataResult(T data) : base(data, false) 14 | { 15 | 16 | } 17 | 18 | public ErrorDataResult(string message) : base(default, false, message) 19 | { 20 | 21 | } 22 | 23 | public ErrorDataResult() : base(default, false) 24 | { 25 | 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /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 | public ErrorResult():base(false) 14 | { 15 | 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /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 | { //Temel voidler için başlangıç 7 | public interface IResult 8 | { 9 | bool Success { get; } 10 | string Message { get; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /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 | 11 | public Result(bool success, string message):this(success) 12 | { 13 | Message = message; 14 | 15 | } 16 | public Result(bool success) 17 | { 18 | 19 | Success = success; 20 | } 21 | 22 | public bool Success { get; } 23 | 24 | public string Message { get; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /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 | public SuccessDataResult(T data):base(data,true) 14 | { 15 | 16 | } 17 | 18 | public SuccessDataResult(string message):base(default,true,message) 19 | { 20 | 21 | } 22 | 23 | public SuccessDataResult():base(default,true) 24 | { 25 | 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /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 | public SuccessResult():base(true) 14 | { 15 | 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /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 | 17 | -------------------------------------------------------------------------------- /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(string password,out byte[] passwordHash,out byte[] passwordSalt) 10 | { 11 | using (var hmac = new System.Security.Cryptography.HMACSHA512()) 12 | { 13 | passwordSalt = hmac.Key; 14 | passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); 15 | } 16 | } 17 | public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) 18 | { 19 | using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) 20 | { 21 | var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); 22 | for (int i = 0; i < computedHash.Length; i++) 23 | { 24 | if (computedHash[i]!=passwordHash[i]) 25 | { 26 | return false; 27 | } 28 | } 29 | } 30 | return true; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /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 | } 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | public class EfProductDal : EfEntityRepositoryBase, IProductDal 15 | { 16 | public List GetProductDetails() 17 | { 18 | using (NorthwindContext context = new NorthwindContext()) 19 | 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, 27 | ProductName = p.ProductName, 28 | CategoryName = c.CategoryName, 29 | UnitsInStock = p.UnitsInStock 30 | }; 31 | return result.ToList(); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /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 | public class NorthwindContext : DbContext 11 | { 12 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 13 | { 14 | optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Northwind;Trusted_Connection=true"); 15 | } 16 | public DbSet Products { get; set; } 17 | public DbSet Categories { get; set; } 18 | public DbSet Customers { get; set; } 19 | public DbSet Orders { get; set; } 20 | public DbSet Users { get; set; } 21 | public DbSet UserOperationClaims { get; set; } 22 | public DbSet OperationClaims { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /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 | { // Oracle , Sql server , Postgres , MongoDb den geliyormuş gibi simule ediyoruz 17 | _products = new List 18 | { 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 | 27 | 28 | public void Add(Product product) 29 | { 30 | _products.Add(product); 31 | } 32 | 33 | public void Delete(Product product) 34 | { //LINQ-Language Intergrated Query 35 | //p=> Lambda 36 | Product productToDelete = _products.SingleOrDefault(p=>p.ProductId==product.ProductId); 37 | 38 | _products.Remove(productToDelete); 39 | } 40 | 41 | public Product Get(Expression> fiter) 42 | { 43 | throw new NotImplementedException(); 44 | } 45 | 46 | public List GetAll() 47 | { 48 | return _products; 49 | } 50 | 51 | public List GetAll(Expression> fiter = null) 52 | { 53 | throw new NotImplementedException(); 54 | } 55 | 56 | public List GetAllByCategory(int categoryId) 57 | { 58 | return _products.Where(p => p.CategoryId == categoryId).ToList(); 59 | } 60 | 61 | public List GetProductDetails() 62 | { 63 | throw new NotImplementedException(); 64 | } 65 | 66 | public void Update(Product product) 67 | { // Gönderdiğim ürün id'sine sahip olan listedeki ürünü bul 68 | Product productToUpdate = _products.SingleOrDefault(p => p.ProductId == product.ProductId); 69 | productToUpdate.ProductName = product.ProductName; 70 | productToUpdate.CategoryId = product.CategoryId; 71 | productToUpdate.UnitPrice = product.UnitPrice; 72 | productToUpdate.UnitsInStock = product.UnitsInStock; 73 | 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /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 |  2 | using Core.Entities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Entities.Concrete 8 | { // Çıplak class kalmasın -- bi yere interface yada inherit alsın yoksa problem yaşarsın 9 | 10 | public class Category :IEntity 11 | { 12 | public int CategoryId { get; set; } 13 | public string CategoryName { get; set; } 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Entities/Concrete/Customer.cs: -------------------------------------------------------------------------------- 1 |  2 | using Core.Entities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Entities.Concrete 8 | { 9 | public class Customer : IEntity 10 | { 11 | public string CustomerId { get; set; } 12 | public string ContactName { get; set; } 13 | public string CompanyName { get; set; } 14 | public string City { get; set; } 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /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 |  2 | using Core.Entities; 3 | using System; 4 | using System.Collections.Generic; 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 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Entities.DTOs 7 | { 8 | public class UserForLoginDto : IDto 9 | { 10 | public string Email { get; set; } 11 | public string Password { get; set; } 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Entities/DTOs/UserForRegisterDto.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | 3 | namespace Entities.DTOs 4 | { 5 | public class UserForRegisterDto : IDto 6 | { 7 | public string Email { get; set; } 8 | public string Password { get; set; } 9 | public string FirstName { get; set; } 10 | public string LastName { get; set; } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /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", "{F3F7235B-5585-4B89-B188-5626A182B3DE}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Business", "Business\Business.csproj", "{DB6AEA19-B911-47E6-A1AE-3681723FCE72}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "Entities\Entities.csproj", "{22C2C75F-123E-4976-8A1B-12160C291293}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleUI", "ConsoleUI\ConsoleUI.csproj", "{6F2CBD13-21AF-4E6B-A4C7-957D0583A505}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "Core\Core.csproj", "{F8EC7B51-9590-48B4-A6E3-109F88BAE211}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAPI", "WebAPI\WebAPI.csproj", "{BD7A2699-61DC-4BB7-965F-BDC521773483}" 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 | {F3F7235B-5585-4B89-B188-5626A182B3DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {F3F7235B-5585-4B89-B188-5626A182B3DE}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {F3F7235B-5585-4B89-B188-5626A182B3DE}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {F3F7235B-5585-4B89-B188-5626A182B3DE}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {DB6AEA19-B911-47E6-A1AE-3681723FCE72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {DB6AEA19-B911-47E6-A1AE-3681723FCE72}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {DB6AEA19-B911-47E6-A1AE-3681723FCE72}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {DB6AEA19-B911-47E6-A1AE-3681723FCE72}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {22C2C75F-123E-4976-8A1B-12160C291293}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {22C2C75F-123E-4976-8A1B-12160C291293}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {22C2C75F-123E-4976-8A1B-12160C291293}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {22C2C75F-123E-4976-8A1B-12160C291293}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {6F2CBD13-21AF-4E6B-A4C7-957D0583A505}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {6F2CBD13-21AF-4E6B-A4C7-957D0583A505}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {6F2CBD13-21AF-4E6B-A4C7-957D0583A505}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {6F2CBD13-21AF-4E6B-A4C7-957D0583A505}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {F8EC7B51-9590-48B4-A6E3-109F88BAE211}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {F8EC7B51-9590-48B4-A6E3-109F88BAE211}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {F8EC7B51-9590-48B4-A6E3-109F88BAE211}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {F8EC7B51-9590-48B4-A6E3-109F88BAE211}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {BD7A2699-61DC-4BB7-965F-BDC521773483}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {BD7A2699-61DC-4BB7-965F-BDC521773483}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {BD7A2699-61DC-4BB7-965F-BDC521773483}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {BD7A2699-61DC-4BB7-965F-BDC521773483}.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 = {FB187A58-53FC-48C4-83A7-25F329E60576} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /WebAPI/Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Entities.DTOs; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace WebAPI.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class AuthController : ControllerBase 15 | { 16 | private IAuthService _authService; 17 | 18 | public AuthController(IAuthService authService) 19 | { 20 | _authService = authService; 21 | } 22 | 23 | [HttpPost("login")] 24 | public ActionResult Login(UserForLoginDto userForLoginDto) 25 | { 26 | var userToLogin = _authService.Login(userForLoginDto); 27 | if (!userToLogin.Success) 28 | { 29 | return BadRequest(userToLogin.Message); 30 | } 31 | 32 | var result = _authService.CreateAccessToken(userToLogin.Data); 33 | if (result.Success) 34 | { 35 | return Ok(result.Data); 36 | } 37 | 38 | return BadRequest(result.Message); 39 | } 40 | 41 | [HttpPost("register")] 42 | public ActionResult Register(UserForRegisterDto userForRegisterDto) 43 | { 44 | var userExists = _authService.UserExists(userForRegisterDto.Email); 45 | if (!userExists.Success) 46 | { 47 | return BadRequest(userExists.Message); 48 | } 49 | 50 | var registerResult = _authService.Register(userForRegisterDto, userForRegisterDto.Password); 51 | var result = _authService.CreateAccessToken(registerResult.Data); 52 | if (result.Success) 53 | { 54 | return Ok(result.Data); 55 | } 56 | 57 | return BadRequest(result.Message); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /WebAPI/Controllers/CategoriesController.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Entities.Concrete; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace WebAPI.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class CategoriesController : ControllerBase 15 | { 16 | ICategoryService _categoryService; 17 | public CategoriesController(ICategoryService categoryService) 18 | { 19 | _categoryService = categoryService; 20 | } 21 | [HttpGet("getall")] 22 | public IActionResult GetAll() 23 | { 24 | 25 | 26 | 27 | var result = _categoryService.GetAll(); 28 | if (result.Success) 29 | { 30 | return Ok(result); 31 | } 32 | return BadRequest(result); 33 | } 34 | 35 | [HttpGet("getbyid")] 36 | public IActionResult GetById(int id) 37 | { 38 | var result = _categoryService.GetById(id); 39 | if (result.Success) 40 | { 41 | return Ok(result); 42 | } 43 | return BadRequest(result); 44 | } 45 | 46 | [HttpPost("add")] 47 | public IActionResult Add(Category category) 48 | { 49 | var result = _categoryService.Add(category); 50 | if (result.Success) 51 | { 52 | return Ok(result); 53 | } 54 | return BadRequest(result); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /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 | public ProductsController(IProductService productService) 24 | { 25 | _productService = productService; 26 | } 27 | [HttpGet("getall")] 28 | public IActionResult GetAll() 29 | { 30 | 31 | 32 | 33 | var result = _productService.GetAll(); 34 | if (result.Success) 35 | { 36 | return Ok(result); 37 | } 38 | return BadRequest(result); 39 | } 40 | 41 | [HttpGet("getbyid")] 42 | public IActionResult GetById(int id) 43 | { 44 | var result = _productService.GetById(id); 45 | if (result.Success) 46 | { 47 | return Ok(result); 48 | } 49 | return BadRequest(result); 50 | } 51 | [HttpGet("getbycategory")] 52 | public IActionResult GetByCategory(int id) 53 | { 54 | var result = _productService.GetAllByCategoryId(id); 55 | if (result.Success) 56 | { 57 | return Ok(result); 58 | } 59 | return BadRequest(result); 60 | } 61 | 62 | [HttpPost("add")] 63 | public IActionResult Add(Product product) 64 | { 65 | var result = _productService.Add(product); 66 | if (result.Success) 67 | { 68 | return Ok(result); 69 | } 70 | return BadRequest(result); 71 | } 72 | 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /WebAPI/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using Business.Abstract; 2 | using Core.Entities.Concrete; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace WebAPI.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class UsersController : ControllerBase 15 | { 16 | IUserService _userService; 17 | public UsersController(IUserService userService) 18 | { 19 | _userService = userService; 20 | } 21 | [HttpPost("add")] 22 | public IActionResult Add(User user) 23 | { 24 | var result = _userService.Add(user); 25 | if (result.Success) 26 | { 27 | return Ok(result); 28 | } 29 | 30 | return BadRequest(result.Message); 31 | } 32 | [HttpPost("delete")] 33 | public IActionResult Delete(User user) 34 | { 35 | var result = _userService.Delete(user); 36 | if (result.Success) 37 | { 38 | return Ok(result.Message); 39 | } 40 | return BadRequest(result.Message); 41 | 42 | } 43 | [HttpPut("update")] 44 | public IActionResult Update(User user) 45 | { 46 | var result = _userService.Update(user); 47 | if (result.Success) 48 | { 49 | return Ok(result.Message); 50 | } 51 | return BadRequest(result.Message); 52 | } 53 | [HttpGet("getall")] 54 | public IActionResult GetAll() 55 | { 56 | var result = _userService.GetAllUsers(); 57 | if (result.Success) 58 | { 59 | return Ok(result.Data); 60 | } 61 | return BadRequest(result.Message); 62 | } 63 | [HttpGet("getbyid")] 64 | public IActionResult GetById(int id) 65 | { 66 | var result = _userService.GetByUserId(id); 67 | if (result.Success) 68 | { 69 | return Ok(result.Data); 70 | } 71 | return BadRequest(result); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /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 | public DateTime? MyProperty { get; set; } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /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:49861", 8 | "sslPort": 44320 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 | { //Autofac , Ninject,CastleWindsor ,StructureMap ,LightInject,DryInject --> IoC Container 40 | 41 | services.AddControllers(); 42 | //services.AddSingleton(); 43 | services.AddCors(); 44 | 45 | var tokenOptions = Configuration.GetSection("TokenOptions").Get(); 46 | 47 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 48 | .AddJwtBearer(options => 49 | { 50 | options.TokenValidationParameters = new TokenValidationParameters 51 | { 52 | ValidateIssuer = true, 53 | ValidateAudience = true, 54 | ValidateLifetime = true, 55 | ValidIssuer = tokenOptions.Issuer, 56 | ValidAudience = tokenOptions.Audience, 57 | ValidateIssuerSigningKey = true, 58 | IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey) 59 | }; 60 | }); 61 | services.AddDependencyResolvers(new ICoreModule[] { 62 | new CoreModule() 63 | }); 64 | } 65 | 66 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 67 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 68 | { 69 | if (env.IsDevelopment()) 70 | { 71 | app.UseDeveloperExceptionPage(); 72 | } 73 | app.UseCors(builder=>builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyOrigin()); 74 | app.ConfigureCustomExceptionMiddleware(); 75 | app.UseHttpsRedirection(); 76 | 77 | app.UseRouting(); 78 | 79 | app.UseAuthentication(); 80 | 81 | app.UseAuthorization(); 82 | 83 | app.UseEndpoints(endpoints => 84 | { 85 | endpoints.MapControllers(); 86 | }); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /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": "Ahmet@amet.com", 4 | "Issuer": "Ahmet@amet.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 | --------------------------------------------------------------------------------