├── .gitignore ├── ASP.NET Core Web API Fundamentals.postman_collection.json ├── CityInfo.API ├── CitiesDataStore.cs ├── CityInfo.API.csproj ├── CityInfo.API.http ├── CityInfo.API.xml ├── CityInfo.db ├── CityInfo.http ├── Controllers │ ├── AuthenticationController.cs │ ├── CitiesController.cs │ ├── FilesController.cs │ └── PointsOfInterestController.cs ├── DbContexts │ └── CityInfoContext.cs ├── Entities │ ├── City.cs │ └── PointOfInterest.cs ├── Migrations │ ├── CityInfoContextModelSnapshot.cs │ ├── CityInfoDBAddPOIDescription.Designer.cs │ ├── CityInfoDBAddPOIDescription.cs │ ├── CityInfoDBAddPointOfInterestDescription.Designer.cs │ ├── CityInfoDBAddPointOfInterestDescription.cs │ ├── CityInfoDBInitialMigration.Designer.cs │ ├── CityInfoDBInitialMigration.cs │ ├── DataSeed.Designer.cs │ ├── DataSeed.cs │ ├── InitialDataSeed.Designer.cs │ ├── InitialDataSeed.cs │ ├── InitialMigration.Designer.cs │ └── InitialMigration.cs ├── Models │ ├── CityDto.cs │ ├── CityWithoutPointsOfInterestDto.cs │ ├── PointOfInterestDto.cs │ ├── PointOfInterestForCreationDto.cs │ └── PointOfInterestForUpdateDto.cs ├── Profiles │ ├── CityProfile.cs │ └── PointOfInterestProfile.cs ├── Program.cs ├── Properties │ ├── ServiceDependencies │ │ └── PluralsightDemo-CityInfoAPI - Web Deploy │ │ │ └── profile.arm.json │ └── launchSettings.json ├── Services │ ├── CityInfoRepository.cs │ ├── CloudMailService.cs │ ├── ICityInfoRepository.cs │ ├── IMailService.cs │ ├── LocalMailService.cs │ └── PaginationMetadata.cs ├── appSettings.Production.json ├── appsettings.Development.json ├── appsettings.json ├── getting-started-with-rest-slides.pdf └── uploaded_file_a0a9de17-1941-4d82-b102-f062ad0c84b5.pdf ├── CityInfo.sln ├── LICENSE └── README.md /.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/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | 400 | # SQLite temporary files 401 | *.db-shm 402 | *.db-wal -------------------------------------------------------------------------------- /ASP.NET Core Web API Fundamentals.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "e1c2c02e-7e05-4019-9c93-9b7405d3b53d", 4 | "name": "ASP.NET Core Web API Fundamentals", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", 6 | "_exporter_id": "805617" 7 | }, 8 | "item": [ 9 | { 10 | "name": "GET Cities", 11 | "request": { 12 | "method": "GET", 13 | "header": [], 14 | "url": { 15 | "raw": "https://localhost:{{portNumber}}/api/cities", 16 | "protocol": "https", 17 | "host": [ 18 | "localhost" 19 | ], 20 | "port": "{{portNumber}}", 21 | "path": [ 22 | "api", 23 | "cities" 24 | ] 25 | } 26 | }, 27 | "response": [] 28 | }, 29 | { 30 | "name": "GET City", 31 | "request": { 32 | "method": "GET", 33 | "header": [], 34 | "url": { 35 | "raw": "https://localhost:{{portNumber}}/api/cities/1", 36 | "protocol": "https", 37 | "host": [ 38 | "localhost" 39 | ], 40 | "port": "{{portNumber}}", 41 | "path": [ 42 | "api", 43 | "cities", 44 | "1" 45 | ] 46 | } 47 | }, 48 | "response": [] 49 | }, 50 | { 51 | "name": "GET Points of Interest", 52 | "request": { 53 | "method": "GET", 54 | "header": [], 55 | "url": { 56 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest", 57 | "protocol": "https", 58 | "host": [ 59 | "localhost" 60 | ], 61 | "port": "{{portNumber}}", 62 | "path": [ 63 | "api", 64 | "cities", 65 | "1", 66 | "pointsofinterest" 67 | ] 68 | } 69 | }, 70 | "response": [] 71 | }, 72 | { 73 | "name": "GET Points of Interest (unexisting City)", 74 | "request": { 75 | "method": "GET", 76 | "header": [], 77 | "url": { 78 | "raw": "https://localhost:{{portNumber}}/api/cities/4/pointsofinterest", 79 | "protocol": "https", 80 | "host": [ 81 | "localhost" 82 | ], 83 | "port": "{{portNumber}}", 84 | "path": [ 85 | "api", 86 | "cities", 87 | "4", 88 | "pointsofinterest" 89 | ] 90 | }, 91 | "description": "Should return 404 NotFound" 92 | }, 93 | "response": [] 94 | }, 95 | { 96 | "name": "GET Point of Interest", 97 | "request": { 98 | "method": "GET", 99 | "header": [], 100 | "url": { 101 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 102 | "protocol": "https", 103 | "host": [ 104 | "localhost" 105 | ], 106 | "port": "{{portNumber}}", 107 | "path": [ 108 | "api", 109 | "cities", 110 | "1", 111 | "pointsofinterest", 112 | "1" 113 | ] 114 | } 115 | }, 116 | "response": [] 117 | }, 118 | { 119 | "name": "GET Point of Interest (unexisting City)", 120 | "request": { 121 | "method": "GET", 122 | "header": [], 123 | "url": { 124 | "raw": "https://localhost:{{portNumber}}/api/cities/4/pointsofinterest/1", 125 | "protocol": "https", 126 | "host": [ 127 | "localhost" 128 | ], 129 | "port": "{{portNumber}}", 130 | "path": [ 131 | "api", 132 | "cities", 133 | "4", 134 | "pointsofinterest", 135 | "1" 136 | ] 137 | }, 138 | "description": "Should return 404 NotFound" 139 | }, 140 | "response": [] 141 | }, 142 | { 143 | "name": "GET Point of Interest (unexisting Point of Interest)", 144 | "request": { 145 | "method": "GET", 146 | "header": [], 147 | "url": { 148 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/10", 149 | "protocol": "https", 150 | "host": [ 151 | "localhost" 152 | ], 153 | "port": "{{portNumber}}", 154 | "path": [ 155 | "api", 156 | "cities", 157 | "1", 158 | "pointsofinterest", 159 | "10" 160 | ] 161 | }, 162 | "description": "Should return 404 NotFound" 163 | }, 164 | "response": [] 165 | }, 166 | { 167 | "name": "GET Cities (XML)", 168 | "request": { 169 | "method": "GET", 170 | "header": [ 171 | { 172 | "key": "Accept", 173 | "value": "application/xml" 174 | } 175 | ], 176 | "url": { 177 | "raw": "https://localhost:{{portNumber}}/api/cities", 178 | "protocol": "https", 179 | "host": [ 180 | "localhost" 181 | ], 182 | "port": "{{portNumber}}", 183 | "path": [ 184 | "api", 185 | "cities" 186 | ] 187 | } 188 | }, 189 | "response": [] 190 | }, 191 | { 192 | "name": "GET File", 193 | "request": { 194 | "method": "GET", 195 | "header": [ 196 | { 197 | "key": "Accept", 198 | "value": "application/xml" 199 | } 200 | ], 201 | "url": { 202 | "raw": "https://localhost:{{portNumber}}/api/files/1", 203 | "protocol": "https", 204 | "host": [ 205 | "localhost" 206 | ], 207 | "port": "{{portNumber}}", 208 | "path": [ 209 | "api", 210 | "files", 211 | "1" 212 | ] 213 | } 214 | }, 215 | "response": [] 216 | }, 217 | { 218 | "name": "POST Point of Interest", 219 | "request": { 220 | "method": "POST", 221 | "header": [ 222 | { 223 | "key": "Content-Type", 224 | "value": "application/json" 225 | } 226 | ], 227 | "body": { 228 | "mode": "raw", 229 | "raw": "{\n \"name\": \"Père Lachaise\",\n \"description\": \"Famous cemetery where Jim Morrison and Oscar Wilde are buried.\"\n}" 230 | }, 231 | "url": { 232 | "raw": "https://localhost:{{portNumber}}/api/cities/3/pointsofinterest", 233 | "protocol": "https", 234 | "host": [ 235 | "localhost" 236 | ], 237 | "port": "{{portNumber}}", 238 | "path": [ 239 | "api", 240 | "cities", 241 | "3", 242 | "pointsofinterest" 243 | ] 244 | } 245 | }, 246 | "response": [] 247 | }, 248 | { 249 | "name": "POST Point of Interest (can't deserialize)", 250 | "request": { 251 | "method": "POST", 252 | "header": [ 253 | { 254 | "key": "Content-Type", 255 | "value": "application/json" 256 | } 257 | ], 258 | "body": { 259 | "mode": "raw", 260 | "raw": "" 261 | }, 262 | "url": { 263 | "raw": "https://localhost:{{portNumber}}/api/cities/3/pointsofinterest", 264 | "protocol": "https", 265 | "host": [ 266 | "localhost" 267 | ], 268 | "port": "{{portNumber}}", 269 | "path": [ 270 | "api", 271 | "cities", 272 | "3", 273 | "pointsofinterest" 274 | ] 275 | } 276 | }, 277 | "response": [] 278 | }, 279 | { 280 | "name": "POST Point of Interest (missing name, long description)", 281 | "request": { 282 | "method": "POST", 283 | "header": [ 284 | { 285 | "key": "Content-Type", 286 | "value": "application/json" 287 | } 288 | ], 289 | "body": { 290 | "mode": "raw", 291 | "raw": "{\n \"invalidProperty\": 1,\n \"description\": \"Scallywag holystone landlubber or just lubber yardarm tackle Shiver me timbers cog heave down provost Admiral of the Black. Hornswaggle spanker man-of-war yo-ho-ho mutiny splice the main brace jack keelhaul fire ship Corsair. Bounty prow walk the plank lugsail port loot pirate bilge jib scuppers. Sutler lee matey sloop plunder splice the main brace interloper Yellow Jack maroon quarter. Draft Privateer run a shot across the bow chandler gaff broadside Pirate Round jolly boat skysail bilge. Chandler mutiny careen execution dock splice the main brace bring a spring upon her cable lass run a rig grog blossom smartly. Gangplank Davy Jones' Locker plunder overhaul draught pinnace blow the man down bring a spring upon her cable no prey, no pay keel. Gold Road gaff grapple sutler scurvy aft bilge come about coffer gunwalls. Scuttle list Davy Jones' Locker pinnace chase trysail draught Pirate Round Jolly Roger log.\"\n}\n" 292 | }, 293 | "url": { 294 | "raw": "https://localhost:{{portNumber}}/api/cities/3/pointsofinterest", 295 | "protocol": "https", 296 | "host": [ 297 | "localhost" 298 | ], 299 | "port": "{{portNumber}}", 300 | "path": [ 301 | "api", 302 | "cities", 303 | "3", 304 | "pointsofinterest" 305 | ] 306 | } 307 | }, 308 | "response": [] 309 | }, 310 | { 311 | "name": "PUT Point of Interest", 312 | "request": { 313 | "method": "PUT", 314 | "header": [ 315 | { 316 | "key": "Content-Type", 317 | "value": "application/json" 318 | } 319 | ], 320 | "body": { 321 | "mode": "raw", 322 | "raw": "{\n \"name\": \"Updated - Central Park\",\n \"description\": \"Updated - The most visited urban park in the United States.\"\n}" 323 | }, 324 | "url": { 325 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 326 | "protocol": "https", 327 | "host": [ 328 | "localhost" 329 | ], 330 | "port": "{{portNumber}}", 331 | "path": [ 332 | "api", 333 | "cities", 334 | "1", 335 | "pointsofinterest", 336 | "1" 337 | ] 338 | } 339 | }, 340 | "response": [] 341 | }, 342 | { 343 | "name": "PUT Point of Interest (no description)", 344 | "request": { 345 | "method": "PUT", 346 | "header": [ 347 | { 348 | "key": "Content-Type", 349 | "value": "application/json" 350 | } 351 | ], 352 | "body": { 353 | "mode": "raw", 354 | "raw": "{\n \"name\": \"Updated again - Central Park\"\n}" 355 | }, 356 | "url": { 357 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 358 | "protocol": "https", 359 | "host": [ 360 | "localhost" 361 | ], 362 | "port": "{{portNumber}}", 363 | "path": [ 364 | "api", 365 | "cities", 366 | "1", 367 | "pointsofinterest", 368 | "1" 369 | ] 370 | } 371 | }, 372 | "response": [] 373 | }, 374 | { 375 | "name": "PATCH Point of Interest", 376 | "request": { 377 | "method": "PATCH", 378 | "header": [ 379 | { 380 | "key": "Content-Type", 381 | "value": "application/json" 382 | } 383 | ], 384 | "body": { 385 | "mode": "raw", 386 | "raw": "[\n {\n \"op\": \"replace\",\n \"path\": \"/name\",\n \"value\": \"Updated - Central Park\"\n }\n]" 387 | }, 388 | "url": { 389 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 390 | "protocol": "https", 391 | "host": [ 392 | "localhost" 393 | ], 394 | "port": "{{portNumber}}", 395 | "path": [ 396 | "api", 397 | "cities", 398 | "1", 399 | "pointsofinterest", 400 | "1" 401 | ] 402 | } 403 | }, 404 | "response": [] 405 | }, 406 | { 407 | "name": "PATCH Point of Interest (update multiple)", 408 | "request": { 409 | "method": "PATCH", 410 | "header": [ 411 | { 412 | "key": "Content-Type", 413 | "value": "application/json" 414 | } 415 | ], 416 | "body": { 417 | "mode": "raw", 418 | "raw": "[\n {\n \"op\": \"replace\",\n \"path\": \"/name\",\n \"value\": \"Updated - Central Park\"\n },\n {\n \"op\": \"replace\",\n \"path\": \"/description\",\n \"value\": \"Updated - Description\"\n }\n]" 419 | }, 420 | "url": { 421 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 422 | "protocol": "https", 423 | "host": [ 424 | "localhost" 425 | ], 426 | "port": "{{portNumber}}", 427 | "path": [ 428 | "api", 429 | "cities", 430 | "1", 431 | "pointsofinterest", 432 | "1" 433 | ] 434 | } 435 | }, 436 | "response": [] 437 | }, 438 | { 439 | "name": "PATCH Point of Interest (invalid property)", 440 | "request": { 441 | "method": "PATCH", 442 | "header": [ 443 | { 444 | "key": "Content-Type", 445 | "value": "application/json" 446 | } 447 | ], 448 | "body": { 449 | "mode": "raw", 450 | "raw": "[\n {\n \"op\": \"replace\",\n \"path\": \"/invalidproperty\",\n \"value\": \"Updated - Central Park\"\n }\n]" 451 | }, 452 | "url": { 453 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 454 | "protocol": "https", 455 | "host": [ 456 | "localhost" 457 | ], 458 | "port": "{{portNumber}}", 459 | "path": [ 460 | "api", 461 | "cities", 462 | "1", 463 | "pointsofinterest", 464 | "1" 465 | ] 466 | } 467 | }, 468 | "response": [] 469 | }, 470 | { 471 | "name": "PATCH Point of Interest (remove name)", 472 | "request": { 473 | "method": "PATCH", 474 | "header": [ 475 | { 476 | "key": "Content-Type", 477 | "value": "application/json" 478 | } 479 | ], 480 | "body": { 481 | "mode": "raw", 482 | "raw": "[\n {\n \"op\": \"remove\",\n \"path\": \"/name\"\n }\n]" 483 | }, 484 | "url": { 485 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 486 | "protocol": "https", 487 | "host": [ 488 | "localhost" 489 | ], 490 | "port": "{{portNumber}}", 491 | "path": [ 492 | "api", 493 | "cities", 494 | "1", 495 | "pointsofinterest", 496 | "1" 497 | ] 498 | } 499 | }, 500 | "response": [] 501 | }, 502 | { 503 | "name": "DELETE Point of Interest", 504 | "request": { 505 | "method": "DELETE", 506 | "header": [], 507 | "body": { 508 | "mode": "raw", 509 | "raw": "" 510 | }, 511 | "url": { 512 | "raw": "https://localhost:{{portNumber}}/api/cities/1/pointsofinterest/1", 513 | "protocol": "https", 514 | "host": [ 515 | "localhost" 516 | ], 517 | "port": "{{portNumber}}", 518 | "path": [ 519 | "api", 520 | "cities", 521 | "1", 522 | "pointsofinterest", 523 | "1" 524 | ] 525 | } 526 | }, 527 | "response": [] 528 | }, 529 | { 530 | "name": "GET Cities, filtered", 531 | "request": { 532 | "method": "GET", 533 | "header": [], 534 | "url": { 535 | "raw": "https://localhost:{{portNumber}}/api/cities?name=Antwerp", 536 | "protocol": "https", 537 | "host": [ 538 | "localhost" 539 | ], 540 | "port": "{{portNumber}}", 541 | "path": [ 542 | "api", 543 | "cities" 544 | ], 545 | "query": [ 546 | { 547 | "key": "name", 548 | "value": "Antwerp" 549 | } 550 | ] 551 | } 552 | }, 553 | "response": [] 554 | }, 555 | { 556 | "name": "GET Cities, searched", 557 | "request": { 558 | "method": "GET", 559 | "header": [], 560 | "url": { 561 | "raw": "https://localhost:{{portNumber}}/api/cities?searchQuery=the", 562 | "protocol": "https", 563 | "host": [ 564 | "localhost" 565 | ], 566 | "port": "{{portNumber}}", 567 | "path": [ 568 | "api", 569 | "cities" 570 | ], 571 | "query": [ 572 | { 573 | "key": "searchQuery", 574 | "value": "the" 575 | } 576 | ] 577 | } 578 | }, 579 | "response": [] 580 | }, 581 | { 582 | "name": "GET Cities, filtered, searched", 583 | "request": { 584 | "method": "GET", 585 | "header": [], 586 | "url": { 587 | "raw": "https://localhost:{{portNumber}}/api/cities?name=Antwerp&searchQuery=the", 588 | "protocol": "https", 589 | "host": [ 590 | "localhost" 591 | ], 592 | "port": "{{portNumber}}", 593 | "path": [ 594 | "api", 595 | "cities" 596 | ], 597 | "query": [ 598 | { 599 | "key": "name", 600 | "value": "Antwerp" 601 | }, 602 | { 603 | "key": "searchQuery", 604 | "value": "the" 605 | } 606 | ] 607 | } 608 | }, 609 | "response": [] 610 | }, 611 | { 612 | "name": "GET Cities, paged", 613 | "request": { 614 | "method": "GET", 615 | "header": [], 616 | "url": { 617 | "raw": "https://localhost:{{portNumber}}/api/cities?pageSize=1&pageNumber=2", 618 | "protocol": "https", 619 | "host": [ 620 | "localhost" 621 | ], 622 | "port": "{{portNumber}}", 623 | "path": [ 624 | "api", 625 | "cities" 626 | ], 627 | "query": [ 628 | { 629 | "key": "pageSize", 630 | "value": "1" 631 | }, 632 | { 633 | "key": "pageNumber", 634 | "value": "2" 635 | } 636 | ] 637 | } 638 | }, 639 | "response": [] 640 | }, 641 | { 642 | "name": "POST Authentication info to get a token", 643 | "request": { 644 | "method": "POST", 645 | "header": [], 646 | "body": { 647 | "mode": "raw", 648 | "raw": "{\r\n \"username\": \"KevinDockx\",\r\n \"password\": \"This is a relatively long sentence that acts as my password\"\r\n}", 649 | "options": { 650 | "raw": { 651 | "language": "json" 652 | } 653 | } 654 | }, 655 | "url": { 656 | "raw": "https://localhost:{{portNumber}}/api/authentication/authenticate", 657 | "protocol": "https", 658 | "host": [ 659 | "localhost" 660 | ], 661 | "port": "{{portNumber}}", 662 | "path": [ 663 | "api", 664 | "authentication", 665 | "authenticate" 666 | ] 667 | } 668 | }, 669 | "response": [] 670 | } 671 | ] 672 | } -------------------------------------------------------------------------------- /CityInfo.API/CitiesDataStore.cs: -------------------------------------------------------------------------------- 1 | using CityInfo.API.Models; 2 | 3 | namespace CityInfo.API 4 | { 5 | public class CitiesDataStore 6 | { 7 | public List Cities { get; set; } 8 | // public static CitiesDataStore Current { get; } = new CitiesDataStore(); 9 | 10 | public CitiesDataStore() 11 | { 12 | // init dummy data 13 | Cities = new List() 14 | { 15 | new CityDto() 16 | { 17 | Id = 1, 18 | Name = "New York City", 19 | Description = "The one with that big park.", 20 | PointsOfInterest = new List() 21 | { 22 | new PointOfInterestDto() { 23 | Id = 1, 24 | Name = "Central Park", 25 | Description = "The most visited urban park in the United States." }, 26 | new PointOfInterestDto() { 27 | Id = 2, 28 | Name = "Empire State Building", 29 | Description = "A 102-story skyscraper located in Midtown Manhattan." }, 30 | } 31 | }, 32 | new CityDto() 33 | { 34 | Id = 2, 35 | Name = "Antwerp", 36 | Description = "The one with the cathedral that was never really finished.", 37 | PointsOfInterest = new List() 38 | { 39 | new PointOfInterestDto() { 40 | Id = 3, 41 | Name = "Cathedral of Our Lady", 42 | Description = "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans." }, 43 | new PointOfInterestDto() { 44 | Id = 4, 45 | Name = "Antwerp Central Station", 46 | Description = "The the finest example of railway architecture in Belgium." }, 47 | } 48 | }, 49 | new CityDto() 50 | { 51 | Id= 3, 52 | Name = "Paris", 53 | Description = "The one with that big tower.", 54 | PointsOfInterest = new List() 55 | { 56 | new PointOfInterestDto() { 57 | Id = 5, 58 | Name = "Eiffel Tower", 59 | Description = "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel." }, 60 | new PointOfInterestDto() { 61 | Id = 6, 62 | Name = "The Louvre", 63 | Description = "The world's largest museum." }, 64 | } 65 | } 66 | }; 67 | 68 | } 69 | 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /CityInfo.API/CityInfo.API.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 32bf9efa-71b4-4891-8d2a-a498fa63be4b 8 | True 9 | CityInfo.API.xml 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Always 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | all 35 | runtime; build; native; contentfiles; analyzers; buildtransitive 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | Always 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /CityInfo.API/CityInfo.API.http: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /CityInfo.API/CityInfo.API.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CityInfo.API 5 | 6 | 7 | 8 | 9 | Get a city by id 10 | 11 | The id of the city to get 12 | Whether or not to include the points of interest 13 | Returns the requested city 14 | A city with or without points of interest 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | A city without points of interest 91 | 92 | 93 | 94 | 95 | The id of the city 96 | 97 | 98 | 99 | 100 | The name of the city 101 | 102 | 103 | 104 | 105 | The description of the city 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /CityInfo.API/CityInfo.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KevinDockx/AspNetCoreWebApiFundamentals/c6e3c88a265292450b2001231180317da079cf6f/CityInfo.API/CityInfo.db -------------------------------------------------------------------------------- /CityInfo.API/CityInfo.http: -------------------------------------------------------------------------------- 1 | @schema=https 2 | @hostname=localhost 3 | @port=7169 4 | 5 | GET {{schema}}://{{hostname}}:{{port}}/api/v2/cities 6 | 7 | ### 8 | 9 | GET {{schema}}://{{hostname}}:{{port}}/api/v2/cities 10 | Accept: application/xml 11 | 12 | ### 13 | 14 | 15 | // This won't work. 16 | # @name createpoi 17 | POST {{schema}}://{{hostname}}:{{port}}/api/v2/cities/1/pointsofinterest 18 | Accept: application/json 19 | Content-Type: application/json 20 | 21 | { 22 | "name": "A name for testing", 23 | "description": "A description for testing" 24 | } 25 | 26 | ### 27 | 28 | @poiid = {{createpoi.response.body.id}} 29 | 30 | GET {{schema}}://{{hostname}}:{{port}}/api/v2/cities/1/pointsofinterest/{{poiid}} 31 | Accept: application/json 32 | 33 | ### 34 | 35 | // get a token 36 | POST {{schema}}://{{hostname}}:{{port}}/api/authentication/authenticate 37 | Content-Type: application/json 38 | 39 | { 40 | "username": "KevinDockx", 41 | "password": "This is a relatively long sentence that acts as my password" 42 | } 43 | 44 | ### 45 | 46 | // authenticated GET request 47 | GET {{schema}}://{{hostname}}:{{port}}/api/v2/cities 48 | Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZ2l2ZW5fbmFtZSI6IktldmluIiwiZmFtaWx5X25hbWUiOiJEb2NreCIsImNpdHkiOiJBbnR3ZXJwIiwibmJmIjoxNzA1NTc0Mjg0LCJleHAiOjE3MDU1Nzc4ODQsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjcxNjkiLCJhdWQiOiJjaXR5aW5mb2FwaSJ9.H7mXjRGrVSyvpQ9JczohPb-nagVVknDTEhM4fp8wq3g 49 | 50 | ### -------------------------------------------------------------------------------- /CityInfo.API/Controllers/AuthenticationController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.IdentityModel.Tokens; 4 | using System.IdentityModel.Tokens.Jwt; 5 | using System.Security.Claims; 6 | using System.Text; 7 | 8 | namespace CityInfo.API.Controllers 9 | { 10 | [Route("api/authentication")] 11 | [ApiController] 12 | public class AuthenticationController : ControllerBase 13 | { 14 | private readonly IConfiguration _configuration; 15 | 16 | // we won't use this outside of this class, so we can scope it to this namespace 17 | public class AuthenticationRequestBody 18 | { 19 | public string? UserName { get; set; } 20 | public string? Password { get; set; } 21 | } 22 | 23 | private class CityInfoUser 24 | { 25 | public int UserId { get; set; } 26 | public string UserName { get; set; } 27 | public string FirstName { get; set; } 28 | public string LastName { get; set; } 29 | public string City { get; set; } 30 | 31 | public CityInfoUser( 32 | int userId, 33 | string userName, 34 | string firstName, 35 | string lastName, 36 | string city) 37 | { 38 | UserId = userId; 39 | UserName = userName; 40 | FirstName = firstName; 41 | LastName = lastName; 42 | City = city; 43 | } 44 | 45 | } 46 | 47 | public AuthenticationController(IConfiguration configuration) 48 | { 49 | _configuration = configuration ?? 50 | throw new ArgumentNullException(nameof(configuration)); 51 | } 52 | 53 | [HttpPost("authenticate")] 54 | public ActionResult Authenticate( 55 | AuthenticationRequestBody authenticationRequestBody) 56 | { 57 | // Step 1: validate the username/password 58 | var user = ValidateUserCredentials( 59 | authenticationRequestBody.UserName, 60 | authenticationRequestBody.Password); 61 | 62 | if (user == null) 63 | { 64 | return Unauthorized(); 65 | } 66 | 67 | // Step 2: create a token 68 | var securityKey = new SymmetricSecurityKey( 69 | Convert.FromBase64String(_configuration["Authentication:SecretForKey"])); 70 | var signingCredentials = new SigningCredentials( 71 | securityKey, SecurityAlgorithms.HmacSha256); 72 | 73 | var claimsForToken = new List(); 74 | claimsForToken.Add(new Claim("sub", user.UserId.ToString())); 75 | claimsForToken.Add(new Claim("given_name", user.FirstName)); 76 | claimsForToken.Add(new Claim("family_name", user.LastName)); 77 | claimsForToken.Add(new Claim("city", user.City)); 78 | 79 | var jwtSecurityToken = new JwtSecurityToken( 80 | _configuration["Authentication:Issuer"], 81 | _configuration["Authentication:Audience"], 82 | claimsForToken, 83 | DateTime.UtcNow, 84 | DateTime.UtcNow.AddHours(1), 85 | signingCredentials); 86 | 87 | var tokenToReturn = new JwtSecurityTokenHandler() 88 | .WriteToken(jwtSecurityToken); 89 | 90 | return Ok(tokenToReturn); 91 | } 92 | 93 | private CityInfoUser ValidateUserCredentials(string? userName, string? password) 94 | { 95 | // we don't have a user DB or table. If you have, check the passed-through 96 | // username/password against what's stored in the database. 97 | // 98 | // For demo purposes, we assume the credentials are valid 99 | 100 | // return a new CityInfoUser (values would normally come from your user DB/table) 101 | return new CityInfoUser( 102 | 1, 103 | userName ?? "", 104 | "Kevin", 105 | "Dockx", 106 | "Antwerp"); 107 | 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /CityInfo.API/Controllers/CitiesController.cs: -------------------------------------------------------------------------------- 1 | using Asp.Versioning; 2 | using AutoMapper; 3 | using CityInfo.API.Models; 4 | using CityInfo.API.Services; 5 | using Microsoft.AspNetCore.Authorization; 6 | using Microsoft.AspNetCore.Mvc; 7 | using System.Text.Json; 8 | 9 | namespace CityInfo.API.Controllers 10 | { 11 | [ApiController] 12 | [Authorize] 13 | [Route("api/v{version:apiVersion}/cities")] 14 | [ApiVersion(1)] 15 | [ApiVersion(2)] 16 | public class CitiesController : ControllerBase 17 | { 18 | private readonly ICityInfoRepository _cityInfoRepository; 19 | private readonly IMapper _mapper; 20 | const int maxCitiesPageSize = 20; 21 | 22 | public CitiesController(ICityInfoRepository cityInfoRepository, 23 | IMapper mapper) 24 | { 25 | _cityInfoRepository = cityInfoRepository ?? 26 | throw new ArgumentNullException(nameof(cityInfoRepository)); 27 | _mapper = mapper ?? 28 | throw new ArgumentNullException(nameof(mapper)); 29 | } 30 | 31 | [HttpGet] 32 | public async Task>> GetCities( 33 | string? name, string? searchQuery, int pageNumber = 1, int pageSize = 10) 34 | { 35 | if (pageSize > maxCitiesPageSize) 36 | { 37 | pageSize = maxCitiesPageSize; 38 | } 39 | 40 | var (cityEntities, paginationMetadata) = await _cityInfoRepository 41 | .GetCitiesAsync(name, searchQuery, pageNumber, pageSize); 42 | 43 | Response.Headers.Add("X-Pagination", 44 | JsonSerializer.Serialize(paginationMetadata)); 45 | 46 | return Ok(_mapper.Map>(cityEntities)); 47 | } 48 | 49 | /// 50 | /// Get a city by id 51 | /// 52 | /// The id of the city to get 53 | /// Whether or not to include the points of interest 54 | /// Returns the requested city 55 | /// A city with or without points of interest 56 | [HttpGet("{cityId}")] 57 | [ProducesResponseType(StatusCodes.Status404NotFound)] 58 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 59 | [ProducesResponseType(StatusCodes.Status200OK)] 60 | public async Task GetCity( 61 | int cityId, bool includePointsOfInterest = false) 62 | { 63 | var city = await _cityInfoRepository.GetCityAsync(cityId, includePointsOfInterest); 64 | if (city == null) 65 | { 66 | return NotFound(); 67 | } 68 | 69 | if (includePointsOfInterest) 70 | { 71 | return Ok(_mapper.Map(city)); 72 | } 73 | 74 | return Ok(_mapper.Map(city)); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /CityInfo.API/Controllers/FilesController.cs: -------------------------------------------------------------------------------- 1 | using Asp.Versioning; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.AspNetCore.StaticFiles; 6 | using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; 7 | 8 | namespace CityInfo.API.Controllers 9 | { 10 | [Route("api/v{version:apiVersion}/files")] 11 | [Authorize] 12 | [ApiController] 13 | public class FilesController : ControllerBase 14 | { 15 | 16 | private readonly FileExtensionContentTypeProvider _fileExtensionContentTypeProvider; 17 | 18 | public FilesController( 19 | FileExtensionContentTypeProvider fileExtensionContentTypeProvider) 20 | { 21 | _fileExtensionContentTypeProvider = fileExtensionContentTypeProvider 22 | ?? throw new System.ArgumentNullException( 23 | nameof(fileExtensionContentTypeProvider)); 24 | } 25 | 26 | [HttpGet("{fileId}")] 27 | [ApiVersion(0.1, Deprecated = true)] 28 | public ActionResult GetFile(string fileId) 29 | { 30 | // look up the actual file, depending on the fileId... 31 | // demo code 32 | var pathToFile = "getting-started-with-rest-slides.pdf"; 33 | 34 | // check whether the file exists 35 | if (!System.IO.File.Exists(pathToFile)) 36 | { 37 | return NotFound(); 38 | } 39 | 40 | if (!_fileExtensionContentTypeProvider.TryGetContentType( 41 | pathToFile, out var contentType)) 42 | { 43 | contentType = "application/octet-stream"; 44 | } 45 | 46 | var bytes = System.IO.File.ReadAllBytes(pathToFile); 47 | return File(bytes, contentType, Path.GetFileName(pathToFile)); 48 | } 49 | 50 | [HttpPost] 51 | [ApiVersion(1)] 52 | public async Task CreateFile(IFormFile file) 53 | { 54 | // Validate the input. Put a limit on filesize to avoid large uploads attacks. 55 | // Only accept .pdf files (check content-type) 56 | if (file.Length == 0 || file.Length > 20971520 || file.ContentType != "application/pdf") 57 | { 58 | return BadRequest("No file or an invalid one has been inputted."); 59 | } 60 | 61 | // Create the file path. Avoid using file.FileName, as an attacker can provide a 62 | // malicious one, including full paths or relative paths. 63 | var path = Path.Combine( 64 | Directory.GetCurrentDirectory(), 65 | $"uploaded_file_{Guid.NewGuid()}.pdf"); 66 | 67 | using (var stream = new FileStream(path, FileMode.Create)) 68 | { 69 | await file.CopyToAsync(stream); 70 | } 71 | 72 | return Ok("Your file has been uploaded successfully."); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /CityInfo.API/Controllers/PointsOfInterestController.cs: -------------------------------------------------------------------------------- 1 | using Asp.Versioning; 2 | using AutoMapper; 3 | using CityInfo.API.Models; 4 | using CityInfo.API.Services; 5 | using Microsoft.AspNetCore.Authorization; 6 | using Microsoft.AspNetCore.JsonPatch; 7 | using Microsoft.AspNetCore.Mvc; 8 | 9 | namespace CityInfo.API.Controllers 10 | { 11 | [Route("api/v{version:apiVersion}/cities/{cityId}/pointsofinterest")] 12 | [Authorize(Policy = "MustBeFromAntwerp")] 13 | [ApiVersion(2)] 14 | [ApiController] 15 | public class PointsOfInterestController : ControllerBase 16 | { 17 | private readonly ILogger _logger; 18 | private readonly IMailService _mailService; 19 | private readonly ICityInfoRepository _cityInfoRepository; 20 | private readonly IMapper _mapper; 21 | 22 | public PointsOfInterestController(ILogger logger, 23 | IMailService mailService, 24 | ICityInfoRepository cityInfoRepository, 25 | IMapper mapper) 26 | { 27 | _logger = logger ?? 28 | throw new ArgumentNullException(nameof(logger)); 29 | _mailService = mailService ?? 30 | throw new ArgumentNullException(nameof(mailService)); 31 | _cityInfoRepository = cityInfoRepository ?? 32 | throw new ArgumentNullException(nameof(cityInfoRepository)); 33 | _mapper = mapper ?? 34 | throw new ArgumentNullException(nameof(mapper)); 35 | } 36 | 37 | [HttpGet] 38 | public async Task>> GetPointsOfInterest( 39 | int cityId) 40 | { 41 | if (!await _cityInfoRepository.CityExistsAsync(cityId)) 42 | { 43 | _logger.LogInformation( 44 | $"City with id {cityId} wasn't found when accessing points of interest."); 45 | return NotFound(); 46 | } 47 | 48 | var pointsOfInterestForCity = await _cityInfoRepository 49 | .GetPointsOfInterestForCityAsync(cityId); 50 | 51 | return Ok(_mapper.Map>(pointsOfInterestForCity)); 52 | } 53 | 54 | [HttpGet("{pointofinterestid}", Name = "GetPointOfInterest")] 55 | public async Task> GetPointOfInterest( 56 | int cityId, int pointOfInterestId) 57 | { 58 | if (!await _cityInfoRepository.CityExistsAsync(cityId)) 59 | { 60 | return NotFound(); 61 | } 62 | 63 | var pointOfInterest = await _cityInfoRepository 64 | .GetPointOfInterestForCityAsync(cityId, pointOfInterestId); 65 | 66 | if (pointOfInterest == null) 67 | { 68 | return NotFound(); 69 | } 70 | 71 | return Ok(_mapper.Map(pointOfInterest)); 72 | } 73 | 74 | [HttpPost] 75 | public async Task> CreatePointOfInterest( 76 | int cityId, 77 | PointOfInterestForCreationDto pointOfInterest) 78 | { 79 | if (!await _cityInfoRepository.CityExistsAsync(cityId)) 80 | { 81 | return NotFound(); 82 | } 83 | 84 | var finalPointOfInterest = _mapper.Map(pointOfInterest); 85 | 86 | await _cityInfoRepository.AddPointOfInterestForCityAsync( 87 | cityId, finalPointOfInterest); 88 | 89 | await _cityInfoRepository.SaveChangesAsync(); 90 | 91 | var createdPointOfInterestToReturn = 92 | _mapper.Map(finalPointOfInterest); 93 | 94 | return CreatedAtRoute("GetPointOfInterest", 95 | new 96 | { 97 | cityId = cityId, 98 | pointOfInterestId = createdPointOfInterestToReturn.Id 99 | }, 100 | createdPointOfInterestToReturn); 101 | } 102 | 103 | [HttpPut("{pointofinterestid}")] 104 | public async Task UpdatePointOfInterest(int cityId, int pointOfInterestId, 105 | PointOfInterestForUpdateDto pointOfInterest) 106 | { 107 | if (!await _cityInfoRepository.CityExistsAsync(cityId)) 108 | { 109 | return NotFound(); 110 | } 111 | 112 | var pointOfInterestEntity = await _cityInfoRepository 113 | .GetPointOfInterestForCityAsync(cityId, pointOfInterestId); 114 | if (pointOfInterestEntity == null) 115 | { 116 | return NotFound(); 117 | } 118 | 119 | _mapper.Map(pointOfInterest, pointOfInterestEntity); 120 | 121 | await _cityInfoRepository.SaveChangesAsync(); 122 | 123 | return NoContent(); 124 | } 125 | 126 | [HttpPatch("{pointofinterestid}")] 127 | public async Task PartiallyUpdatePointOfInterest( 128 | int cityId, int pointOfInterestId, 129 | JsonPatchDocument patchDocument) 130 | { 131 | if (!await _cityInfoRepository.CityExistsAsync(cityId)) 132 | { 133 | return NotFound(); 134 | } 135 | 136 | var pointOfInterestEntity = await _cityInfoRepository 137 | .GetPointOfInterestForCityAsync(cityId, pointOfInterestId); 138 | if (pointOfInterestEntity == null) 139 | { 140 | return NotFound(); 141 | } 142 | 143 | var pointOfInterestToPatch = _mapper.Map( 144 | pointOfInterestEntity); 145 | 146 | patchDocument.ApplyTo(pointOfInterestToPatch, ModelState); 147 | 148 | if (!ModelState.IsValid) 149 | { 150 | return BadRequest(ModelState); 151 | } 152 | 153 | if (!TryValidateModel(pointOfInterestToPatch)) 154 | { 155 | return BadRequest(ModelState); 156 | } 157 | 158 | _mapper.Map(pointOfInterestToPatch, pointOfInterestEntity); 159 | await _cityInfoRepository.SaveChangesAsync(); 160 | 161 | return NoContent(); 162 | } 163 | 164 | [HttpDelete("{pointOfInterestId}")] 165 | public async Task DeletePointOfInterest( 166 | int cityId, int pointOfInterestId) 167 | { 168 | if (!await _cityInfoRepository.CityExistsAsync(cityId)) 169 | { 170 | return NotFound(); 171 | } 172 | 173 | var pointOfInterestEntity = await _cityInfoRepository 174 | .GetPointOfInterestForCityAsync(cityId, pointOfInterestId); 175 | if (pointOfInterestEntity == null) 176 | { 177 | return NotFound(); 178 | } 179 | 180 | _cityInfoRepository.DeletePointOfInterest(pointOfInterestEntity); 181 | await _cityInfoRepository.SaveChangesAsync(); 182 | 183 | _mailService.Send( 184 | "Point of interest deleted.", 185 | $"Point of interest {pointOfInterestEntity.Name} with id {pointOfInterestEntity.Id} was deleted."); 186 | 187 | return NoContent(); 188 | } 189 | 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /CityInfo.API/DbContexts/CityInfoContext.cs: -------------------------------------------------------------------------------- 1 | using CityInfo.API.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace CityInfo.API.DbContexts 5 | { 6 | public class CityInfoContext : DbContext 7 | { 8 | public DbSet Cities { get; set; } 9 | public DbSet PointsOfInterest { get; set; } 10 | 11 | public CityInfoContext(DbContextOptions options) 12 | : base(options) 13 | { 14 | } 15 | 16 | protected override void OnModelCreating(ModelBuilder modelBuilder) 17 | { 18 | modelBuilder.Entity() 19 | .HasData( 20 | new City("New York City") 21 | { 22 | Id = 1, 23 | Description = "The one with that big park." 24 | }, 25 | new City("Antwerp") 26 | { 27 | Id = 2, 28 | Description = "The one with the cathedral that was never really finished." 29 | }, 30 | new City("Paris") 31 | { 32 | Id = 3, 33 | Description = "The one with that big tower." 34 | }); 35 | 36 | modelBuilder.Entity() 37 | .HasData( 38 | new PointOfInterest("Central Park") 39 | { 40 | Id = 1, 41 | CityId = 1, 42 | Description = "The most visited urban park in the United States." 43 | 44 | }, 45 | new PointOfInterest("Empire State Building") 46 | { 47 | Id = 2, 48 | CityId = 1, 49 | Description = "A 102-story skyscraper located in Midtown Manhattan." 50 | }, 51 | new PointOfInterest("Cathedral") 52 | { 53 | Id = 3, 54 | CityId = 2, 55 | Description = "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans." 56 | }, 57 | new PointOfInterest("Antwerp Central Station") 58 | { 59 | Id = 4, 60 | CityId = 2, 61 | Description = "The the finest example of railway architecture in Belgium." 62 | }, 63 | new PointOfInterest("Eiffel Tower") 64 | { 65 | Id = 5, 66 | CityId = 3, 67 | Description = "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel." 68 | }, 69 | new PointOfInterest("The Louvre") 70 | { 71 | Id = 6, 72 | CityId = 3, 73 | Description = "The world's largest museum." 74 | } 75 | ); 76 | 77 | 78 | 79 | base.OnModelCreating(modelBuilder); 80 | } 81 | 82 | //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 83 | //{ 84 | // optionsBuilder.UseSqlite("connectionstring"); 85 | 86 | // base.OnConfiguring(optionsBuilder); 87 | //} 88 | 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /CityInfo.API/Entities/City.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace CityInfo.API.Entities 5 | { 6 | public class City 7 | { 8 | [Key] 9 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 10 | public int Id { get; set; } 11 | 12 | [Required] 13 | [MaxLength(50)] 14 | public string Name { get; set; } 15 | 16 | [MaxLength(200)] 17 | public string? Description { get; set; } 18 | 19 | public ICollection PointsOfInterest { get; set; } 20 | = new List(); 21 | 22 | public City(string name) 23 | { 24 | Name = name; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CityInfo.API/Entities/PointOfInterest.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace CityInfo.API.Entities 5 | { 6 | public class PointOfInterest 7 | { 8 | [Key] 9 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 10 | public int Id { get; set; } 11 | 12 | [Required] 13 | [MaxLength(50)] 14 | public string Name { get; set; } 15 | 16 | [MaxLength(200)] 17 | public string? Description { get; set; } 18 | 19 | [ForeignKey("CityId")] 20 | public City? City { get; set; } 21 | public int CityId { get; set; } 22 | 23 | public PointOfInterest(string name) 24 | { 25 | Name = name; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | 7 | #nullable disable 8 | 9 | namespace CityInfo.API.Migrations 10 | { 11 | [DbContext(typeof(CityInfoContext))] 12 | partial class CityInfoContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | #pragma warning disable 612, 618 17 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 18 | 19 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 20 | { 21 | b.Property("Id") 22 | .ValueGeneratedOnAdd() 23 | .HasColumnType("INTEGER"); 24 | 25 | b.Property("Description") 26 | .HasMaxLength(200) 27 | .HasColumnType("TEXT"); 28 | 29 | b.Property("Name") 30 | .IsRequired() 31 | .HasMaxLength(50) 32 | .HasColumnType("TEXT"); 33 | 34 | b.HasKey("Id"); 35 | 36 | b.ToTable("Cities"); 37 | 38 | b.HasData( 39 | new 40 | { 41 | Id = 1, 42 | Description = "The one with that big park.", 43 | Name = "New York City" 44 | }, 45 | new 46 | { 47 | Id = 2, 48 | Description = "The one with the cathedral that was never really finished.", 49 | Name = "Antwerp" 50 | }, 51 | new 52 | { 53 | Id = 3, 54 | Description = "The one with that big tower.", 55 | Name = "Paris" 56 | }); 57 | }); 58 | 59 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 60 | { 61 | b.Property("Id") 62 | .ValueGeneratedOnAdd() 63 | .HasColumnType("INTEGER"); 64 | 65 | b.Property("CityId") 66 | .HasColumnType("INTEGER"); 67 | 68 | b.Property("Description") 69 | .HasMaxLength(200) 70 | .HasColumnType("TEXT"); 71 | 72 | b.Property("Name") 73 | .IsRequired() 74 | .HasMaxLength(50) 75 | .HasColumnType("TEXT"); 76 | 77 | b.HasKey("Id"); 78 | 79 | b.HasIndex("CityId"); 80 | 81 | b.ToTable("PointsOfInterest"); 82 | 83 | b.HasData( 84 | new 85 | { 86 | Id = 1, 87 | CityId = 1, 88 | Description = "The most visited urban park in the United States.", 89 | Name = "Central Park" 90 | }, 91 | new 92 | { 93 | Id = 2, 94 | CityId = 1, 95 | Description = "A 102-story skyscraper located in Midtown Manhattan.", 96 | Name = "Empire State Building" 97 | }, 98 | new 99 | { 100 | Id = 3, 101 | CityId = 2, 102 | Description = "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans.", 103 | Name = "Cathedral" 104 | }, 105 | new 106 | { 107 | Id = 4, 108 | CityId = 2, 109 | Description = "The the finest example of railway architecture in Belgium.", 110 | Name = "Antwerp Central Station" 111 | }, 112 | new 113 | { 114 | Id = 5, 115 | CityId = 3, 116 | Description = "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel.", 117 | Name = "Eiffel Tower" 118 | }, 119 | new 120 | { 121 | Id = 6, 122 | CityId = 3, 123 | Description = "The world's largest museum.", 124 | Name = "The Louvre" 125 | }); 126 | }); 127 | 128 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 129 | { 130 | b.HasOne("CityInfo.API.Entities.City", "City") 131 | .WithMany("PointsOfInterest") 132 | .HasForeignKey("CityId") 133 | .OnDelete(DeleteBehavior.Cascade) 134 | .IsRequired(); 135 | 136 | b.Navigation("City"); 137 | }); 138 | 139 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 140 | { 141 | b.Navigation("PointsOfInterest"); 142 | }); 143 | #pragma warning restore 612, 618 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoDBAddPOIDescription.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace CityInfo.API.Migrations 11 | { 12 | [DbContext(typeof(CityInfoContext))] 13 | [Migration("20240111155407_CityInfoDBAddPOIDescription")] 14 | partial class CityInfoDBAddPOIDescription 15 | { 16 | /// 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 21 | 22 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("INTEGER"); 27 | 28 | b.Property("Description") 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasMaxLength(50) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Cities"); 40 | }); 41 | 42 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 43 | { 44 | b.Property("Id") 45 | .ValueGeneratedOnAdd() 46 | .HasColumnType("INTEGER"); 47 | 48 | b.Property("CityId") 49 | .HasColumnType("INTEGER"); 50 | 51 | b.Property("Description") 52 | .HasMaxLength(200) 53 | .HasColumnType("TEXT"); 54 | 55 | b.Property("Name") 56 | .IsRequired() 57 | .HasMaxLength(50) 58 | .HasColumnType("TEXT"); 59 | 60 | b.HasKey("Id"); 61 | 62 | b.HasIndex("CityId"); 63 | 64 | b.ToTable("PointsOfInterest"); 65 | }); 66 | 67 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 68 | { 69 | b.HasOne("CityInfo.API.Entities.City", "City") 70 | .WithMany("PointsOfInterest") 71 | .HasForeignKey("CityId") 72 | .OnDelete(DeleteBehavior.Cascade) 73 | .IsRequired(); 74 | 75 | b.Navigation("City"); 76 | }); 77 | 78 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 79 | { 80 | b.Navigation("PointsOfInterest"); 81 | }); 82 | #pragma warning restore 612, 618 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoDBAddPOIDescription.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CityInfo.API.Migrations 6 | { 7 | /// 8 | public partial class CityInfoDBAddPOIDescription : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.AddColumn( 14 | name: "Description", 15 | table: "PointsOfInterest", 16 | type: "TEXT", 17 | maxLength: 200, 18 | nullable: true); 19 | } 20 | 21 | /// 22 | protected override void Down(MigrationBuilder migrationBuilder) 23 | { 24 | migrationBuilder.DropColumn( 25 | name: "Description", 26 | table: "PointsOfInterest"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoDBAddPointOfInterestDescription.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace CityInfo.API.Migrations 11 | { 12 | [DbContext(typeof(CityInfoContext))] 13 | [Migration("20240108091009_CityInfoDBAddPointOfInterestDescription")] 14 | partial class CityInfoDBAddPointOfInterestDescription 15 | { 16 | /// 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 21 | 22 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("INTEGER"); 27 | 28 | b.Property("Description") 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasMaxLength(50) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Cities"); 40 | }); 41 | 42 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 43 | { 44 | b.Property("Id") 45 | .ValueGeneratedOnAdd() 46 | .HasColumnType("INTEGER"); 47 | 48 | b.Property("CityId") 49 | .HasColumnType("INTEGER"); 50 | 51 | b.Property("Description") 52 | .IsRequired() 53 | .HasMaxLength(200) 54 | .HasColumnType("TEXT"); 55 | 56 | b.Property("Name") 57 | .IsRequired() 58 | .HasMaxLength(50) 59 | .HasColumnType("TEXT"); 60 | 61 | b.HasKey("Id"); 62 | 63 | b.HasIndex("CityId"); 64 | 65 | b.ToTable("PointsOfInterest"); 66 | }); 67 | 68 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 69 | { 70 | b.HasOne("CityInfo.API.Entities.City", "City") 71 | .WithMany("PointsOfInterest") 72 | .HasForeignKey("CityId") 73 | .OnDelete(DeleteBehavior.Cascade) 74 | .IsRequired(); 75 | 76 | b.Navigation("City"); 77 | }); 78 | 79 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 80 | { 81 | b.Navigation("PointsOfInterest"); 82 | }); 83 | #pragma warning restore 612, 618 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoDBAddPointOfInterestDescription.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CityInfo.API.Migrations 6 | { 7 | /// 8 | public partial class CityInfoDBAddPointOfInterestDescription : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.AddColumn( 14 | name: "Description", 15 | table: "PointsOfInterest", 16 | type: "TEXT", 17 | maxLength: 200, 18 | nullable: false, 19 | defaultValue: ""); 20 | } 21 | 22 | /// 23 | protected override void Down(MigrationBuilder migrationBuilder) 24 | { 25 | migrationBuilder.DropColumn( 26 | name: "Description", 27 | table: "PointsOfInterest"); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoDBInitialMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace CityInfo.API.Migrations 11 | { 12 | [DbContext(typeof(CityInfoContext))] 13 | [Migration("20240111154720_CityInfoDBInitialMigration")] 14 | partial class CityInfoDBInitialMigration 15 | { 16 | /// 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 21 | 22 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("INTEGER"); 27 | 28 | b.Property("Description") 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasMaxLength(50) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Cities"); 40 | }); 41 | 42 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 43 | { 44 | b.Property("Id") 45 | .ValueGeneratedOnAdd() 46 | .HasColumnType("INTEGER"); 47 | 48 | b.Property("CityId") 49 | .HasColumnType("INTEGER"); 50 | 51 | b.Property("Name") 52 | .IsRequired() 53 | .HasMaxLength(50) 54 | .HasColumnType("TEXT"); 55 | 56 | b.HasKey("Id"); 57 | 58 | b.HasIndex("CityId"); 59 | 60 | b.ToTable("PointsOfInterest"); 61 | }); 62 | 63 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 64 | { 65 | b.HasOne("CityInfo.API.Entities.City", "City") 66 | .WithMany("PointsOfInterest") 67 | .HasForeignKey("CityId") 68 | .OnDelete(DeleteBehavior.Cascade) 69 | .IsRequired(); 70 | 71 | b.Navigation("City"); 72 | }); 73 | 74 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 75 | { 76 | b.Navigation("PointsOfInterest"); 77 | }); 78 | #pragma warning restore 612, 618 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/CityInfoDBInitialMigration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CityInfo.API.Migrations 6 | { 7 | /// 8 | public partial class CityInfoDBInitialMigration : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Cities", 15 | columns: table => new 16 | { 17 | Id = table.Column(type: "INTEGER", nullable: false) 18 | .Annotation("Sqlite:Autoincrement", true), 19 | Name = table.Column(type: "TEXT", maxLength: 50, nullable: false), 20 | Description = table.Column(type: "TEXT", maxLength: 200, nullable: true) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_Cities", x => x.Id); 25 | }); 26 | 27 | migrationBuilder.CreateTable( 28 | name: "PointsOfInterest", 29 | columns: table => new 30 | { 31 | Id = table.Column(type: "INTEGER", nullable: false) 32 | .Annotation("Sqlite:Autoincrement", true), 33 | Name = table.Column(type: "TEXT", maxLength: 50, nullable: false), 34 | CityId = table.Column(type: "INTEGER", nullable: false) 35 | }, 36 | constraints: table => 37 | { 38 | table.PrimaryKey("PK_PointsOfInterest", x => x.Id); 39 | table.ForeignKey( 40 | name: "FK_PointsOfInterest_Cities_CityId", 41 | column: x => x.CityId, 42 | principalTable: "Cities", 43 | principalColumn: "Id", 44 | onDelete: ReferentialAction.Cascade); 45 | }); 46 | 47 | migrationBuilder.CreateIndex( 48 | name: "IX_PointsOfInterest_CityId", 49 | table: "PointsOfInterest", 50 | column: "CityId"); 51 | } 52 | 53 | /// 54 | protected override void Down(MigrationBuilder migrationBuilder) 55 | { 56 | migrationBuilder.DropTable( 57 | name: "PointsOfInterest"); 58 | 59 | migrationBuilder.DropTable( 60 | name: "Cities"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/DataSeed.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace CityInfo.API.Migrations 11 | { 12 | [DbContext(typeof(CityInfoContext))] 13 | [Migration("20240108091129_DataSeed")] 14 | partial class DataSeed 15 | { 16 | /// 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 21 | 22 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("INTEGER"); 27 | 28 | b.Property("Description") 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasMaxLength(50) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Cities"); 40 | 41 | b.HasData( 42 | new 43 | { 44 | Id = 1, 45 | Description = "The one with that big park.", 46 | Name = "New York City" 47 | }, 48 | new 49 | { 50 | Id = 2, 51 | Description = "The one with the cathedral that was never really finished.", 52 | Name = "Antwerp" 53 | }, 54 | new 55 | { 56 | Id = 3, 57 | Description = "The one with that big tower.", 58 | Name = "Paris" 59 | }); 60 | }); 61 | 62 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 63 | { 64 | b.Property("Id") 65 | .ValueGeneratedOnAdd() 66 | .HasColumnType("INTEGER"); 67 | 68 | b.Property("CityId") 69 | .HasColumnType("INTEGER"); 70 | 71 | b.Property("Description") 72 | .IsRequired() 73 | .HasMaxLength(200) 74 | .HasColumnType("TEXT"); 75 | 76 | b.Property("Name") 77 | .IsRequired() 78 | .HasMaxLength(50) 79 | .HasColumnType("TEXT"); 80 | 81 | b.HasKey("Id"); 82 | 83 | b.HasIndex("CityId"); 84 | 85 | b.ToTable("PointsOfInterest"); 86 | 87 | b.HasData( 88 | new 89 | { 90 | Id = 1, 91 | CityId = 1, 92 | Description = "The most visited urban park in the United States.", 93 | Name = "Central Park" 94 | }, 95 | new 96 | { 97 | Id = 2, 98 | CityId = 1, 99 | Description = "A 102-story skyscraper located in Midtown Manhattan.", 100 | Name = "Empire State Building" 101 | }, 102 | new 103 | { 104 | Id = 3, 105 | CityId = 2, 106 | Description = "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans.", 107 | Name = "Cathedral" 108 | }, 109 | new 110 | { 111 | Id = 4, 112 | CityId = 2, 113 | Description = "The the finest example of railway architecture in Belgium.", 114 | Name = "Antwerp Central Station" 115 | }, 116 | new 117 | { 118 | Id = 5, 119 | CityId = 3, 120 | Description = "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel.", 121 | Name = "Eiffel Tower" 122 | }, 123 | new 124 | { 125 | Id = 6, 126 | CityId = 3, 127 | Description = "The world's largest museum.", 128 | Name = "The Louvre" 129 | }); 130 | }); 131 | 132 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 133 | { 134 | b.HasOne("CityInfo.API.Entities.City", "City") 135 | .WithMany("PointsOfInterest") 136 | .HasForeignKey("CityId") 137 | .OnDelete(DeleteBehavior.Cascade) 138 | .IsRequired(); 139 | 140 | b.Navigation("City"); 141 | }); 142 | 143 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 144 | { 145 | b.Navigation("PointsOfInterest"); 146 | }); 147 | #pragma warning restore 612, 618 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/DataSeed.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | #pragma warning disable CA1814 // Prefer jagged arrays over multidimensional 6 | 7 | namespace CityInfo.API.Migrations 8 | { 9 | /// 10 | public partial class DataSeed : Migration 11 | { 12 | /// 13 | protected override void Up(MigrationBuilder migrationBuilder) 14 | { 15 | migrationBuilder.InsertData( 16 | table: "Cities", 17 | columns: new[] { "Id", "Description", "Name" }, 18 | values: new object[,] 19 | { 20 | { 1, "The one with that big park.", "New York City" }, 21 | { 2, "The one with the cathedral that was never really finished.", "Antwerp" }, 22 | { 3, "The one with that big tower.", "Paris" } 23 | }); 24 | 25 | migrationBuilder.InsertData( 26 | table: "PointsOfInterest", 27 | columns: new[] { "Id", "CityId", "Description", "Name" }, 28 | values: new object[,] 29 | { 30 | { 1, 1, "The most visited urban park in the United States.", "Central Park" }, 31 | { 2, 1, "A 102-story skyscraper located in Midtown Manhattan.", "Empire State Building" }, 32 | { 3, 2, "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans.", "Cathedral" }, 33 | { 4, 2, "The the finest example of railway architecture in Belgium.", "Antwerp Central Station" }, 34 | { 5, 3, "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel.", "Eiffel Tower" }, 35 | { 6, 3, "The world's largest museum.", "The Louvre" } 36 | }); 37 | } 38 | 39 | /// 40 | protected override void Down(MigrationBuilder migrationBuilder) 41 | { 42 | migrationBuilder.DeleteData( 43 | table: "PointsOfInterest", 44 | keyColumn: "Id", 45 | keyValue: 1); 46 | 47 | migrationBuilder.DeleteData( 48 | table: "PointsOfInterest", 49 | keyColumn: "Id", 50 | keyValue: 2); 51 | 52 | migrationBuilder.DeleteData( 53 | table: "PointsOfInterest", 54 | keyColumn: "Id", 55 | keyValue: 3); 56 | 57 | migrationBuilder.DeleteData( 58 | table: "PointsOfInterest", 59 | keyColumn: "Id", 60 | keyValue: 4); 61 | 62 | migrationBuilder.DeleteData( 63 | table: "PointsOfInterest", 64 | keyColumn: "Id", 65 | keyValue: 5); 66 | 67 | migrationBuilder.DeleteData( 68 | table: "PointsOfInterest", 69 | keyColumn: "Id", 70 | keyValue: 6); 71 | 72 | migrationBuilder.DeleteData( 73 | table: "Cities", 74 | keyColumn: "Id", 75 | keyValue: 1); 76 | 77 | migrationBuilder.DeleteData( 78 | table: "Cities", 79 | keyColumn: "Id", 80 | keyValue: 2); 81 | 82 | migrationBuilder.DeleteData( 83 | table: "Cities", 84 | keyColumn: "Id", 85 | keyValue: 3); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/InitialDataSeed.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace CityInfo.API.Migrations 11 | { 12 | [DbContext(typeof(CityInfoContext))] 13 | [Migration("20240111155944_InitialDataSeed")] 14 | partial class InitialDataSeed 15 | { 16 | /// 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 21 | 22 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("INTEGER"); 27 | 28 | b.Property("Description") 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasMaxLength(50) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Cities"); 40 | 41 | b.HasData( 42 | new 43 | { 44 | Id = 1, 45 | Description = "The one with that big park.", 46 | Name = "New York City" 47 | }, 48 | new 49 | { 50 | Id = 2, 51 | Description = "The one with the cathedral that was never really finished.", 52 | Name = "Antwerp" 53 | }, 54 | new 55 | { 56 | Id = 3, 57 | Description = "The one with that big tower.", 58 | Name = "Paris" 59 | }); 60 | }); 61 | 62 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 63 | { 64 | b.Property("Id") 65 | .ValueGeneratedOnAdd() 66 | .HasColumnType("INTEGER"); 67 | 68 | b.Property("CityId") 69 | .HasColumnType("INTEGER"); 70 | 71 | b.Property("Description") 72 | .HasMaxLength(200) 73 | .HasColumnType("TEXT"); 74 | 75 | b.Property("Name") 76 | .IsRequired() 77 | .HasMaxLength(50) 78 | .HasColumnType("TEXT"); 79 | 80 | b.HasKey("Id"); 81 | 82 | b.HasIndex("CityId"); 83 | 84 | b.ToTable("PointsOfInterest"); 85 | 86 | b.HasData( 87 | new 88 | { 89 | Id = 1, 90 | CityId = 1, 91 | Description = "The most visited urban park in the United States.", 92 | Name = "Central Park" 93 | }, 94 | new 95 | { 96 | Id = 2, 97 | CityId = 1, 98 | Description = "A 102-story skyscraper located in Midtown Manhattan.", 99 | Name = "Empire State Building" 100 | }, 101 | new 102 | { 103 | Id = 3, 104 | CityId = 2, 105 | Description = "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans.", 106 | Name = "Cathedral" 107 | }, 108 | new 109 | { 110 | Id = 4, 111 | CityId = 2, 112 | Description = "The the finest example of railway architecture in Belgium.", 113 | Name = "Antwerp Central Station" 114 | }, 115 | new 116 | { 117 | Id = 5, 118 | CityId = 3, 119 | Description = "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel.", 120 | Name = "Eiffel Tower" 121 | }, 122 | new 123 | { 124 | Id = 6, 125 | CityId = 3, 126 | Description = "The world's largest museum.", 127 | Name = "The Louvre" 128 | }); 129 | }); 130 | 131 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 132 | { 133 | b.HasOne("CityInfo.API.Entities.City", "City") 134 | .WithMany("PointsOfInterest") 135 | .HasForeignKey("CityId") 136 | .OnDelete(DeleteBehavior.Cascade) 137 | .IsRequired(); 138 | 139 | b.Navigation("City"); 140 | }); 141 | 142 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 143 | { 144 | b.Navigation("PointsOfInterest"); 145 | }); 146 | #pragma warning restore 612, 618 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/InitialDataSeed.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | #pragma warning disable CA1814 // Prefer jagged arrays over multidimensional 6 | 7 | namespace CityInfo.API.Migrations 8 | { 9 | /// 10 | public partial class InitialDataSeed : Migration 11 | { 12 | /// 13 | protected override void Up(MigrationBuilder migrationBuilder) 14 | { 15 | migrationBuilder.InsertData( 16 | table: "Cities", 17 | columns: new[] { "Id", "Description", "Name" }, 18 | values: new object[,] 19 | { 20 | { 1, "The one with that big park.", "New York City" }, 21 | { 2, "The one with the cathedral that was never really finished.", "Antwerp" }, 22 | { 3, "The one with that big tower.", "Paris" } 23 | }); 24 | 25 | migrationBuilder.InsertData( 26 | table: "PointsOfInterest", 27 | columns: new[] { "Id", "CityId", "Description", "Name" }, 28 | values: new object[,] 29 | { 30 | { 1, 1, "The most visited urban park in the United States.", "Central Park" }, 31 | { 2, 1, "A 102-story skyscraper located in Midtown Manhattan.", "Empire State Building" }, 32 | { 3, 2, "A Gothic style cathedral, conceived by architects Jan and Pieter Appelmans.", "Cathedral" }, 33 | { 4, 2, "The the finest example of railway architecture in Belgium.", "Antwerp Central Station" }, 34 | { 5, 3, "A wrought iron lattice tower on the Champ de Mars, named after engineer Gustave Eiffel.", "Eiffel Tower" }, 35 | { 6, 3, "The world's largest museum.", "The Louvre" } 36 | }); 37 | } 38 | 39 | /// 40 | protected override void Down(MigrationBuilder migrationBuilder) 41 | { 42 | migrationBuilder.DeleteData( 43 | table: "PointsOfInterest", 44 | keyColumn: "Id", 45 | keyValue: 1); 46 | 47 | migrationBuilder.DeleteData( 48 | table: "PointsOfInterest", 49 | keyColumn: "Id", 50 | keyValue: 2); 51 | 52 | migrationBuilder.DeleteData( 53 | table: "PointsOfInterest", 54 | keyColumn: "Id", 55 | keyValue: 3); 56 | 57 | migrationBuilder.DeleteData( 58 | table: "PointsOfInterest", 59 | keyColumn: "Id", 60 | keyValue: 4); 61 | 62 | migrationBuilder.DeleteData( 63 | table: "PointsOfInterest", 64 | keyColumn: "Id", 65 | keyValue: 5); 66 | 67 | migrationBuilder.DeleteData( 68 | table: "PointsOfInterest", 69 | keyColumn: "Id", 70 | keyValue: 6); 71 | 72 | migrationBuilder.DeleteData( 73 | table: "Cities", 74 | keyColumn: "Id", 75 | keyValue: 1); 76 | 77 | migrationBuilder.DeleteData( 78 | table: "Cities", 79 | keyColumn: "Id", 80 | keyValue: 2); 81 | 82 | migrationBuilder.DeleteData( 83 | table: "Cities", 84 | keyColumn: "Id", 85 | keyValue: 3); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/InitialMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using CityInfo.API.DbContexts; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace CityInfo.API.Migrations 11 | { 12 | [DbContext(typeof(CityInfoContext))] 13 | [Migration("20240108090922_InitialMigration")] 14 | partial class InitialMigration 15 | { 16 | /// 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); 21 | 22 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("INTEGER"); 27 | 28 | b.Property("Description") 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("Name") 33 | .IsRequired() 34 | .HasMaxLength(50) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Cities"); 40 | }); 41 | 42 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 43 | { 44 | b.Property("Id") 45 | .ValueGeneratedOnAdd() 46 | .HasColumnType("INTEGER"); 47 | 48 | b.Property("CityId") 49 | .HasColumnType("INTEGER"); 50 | 51 | b.Property("Name") 52 | .IsRequired() 53 | .HasMaxLength(50) 54 | .HasColumnType("TEXT"); 55 | 56 | b.HasKey("Id"); 57 | 58 | b.HasIndex("CityId"); 59 | 60 | b.ToTable("PointsOfInterest"); 61 | }); 62 | 63 | modelBuilder.Entity("CityInfo.API.Entities.PointOfInterest", b => 64 | { 65 | b.HasOne("CityInfo.API.Entities.City", "City") 66 | .WithMany("PointsOfInterest") 67 | .HasForeignKey("CityId") 68 | .OnDelete(DeleteBehavior.Cascade) 69 | .IsRequired(); 70 | 71 | b.Navigation("City"); 72 | }); 73 | 74 | modelBuilder.Entity("CityInfo.API.Entities.City", b => 75 | { 76 | b.Navigation("PointsOfInterest"); 77 | }); 78 | #pragma warning restore 612, 618 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /CityInfo.API/Migrations/InitialMigration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace CityInfo.API.Migrations 6 | { 7 | /// 8 | public partial class InitialMigration : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Cities", 15 | columns: table => new 16 | { 17 | Id = table.Column(type: "INTEGER", nullable: false) 18 | .Annotation("Sqlite:Autoincrement", true), 19 | Name = table.Column(type: "TEXT", maxLength: 50, nullable: false), 20 | Description = table.Column(type: "TEXT", maxLength: 200, nullable: true) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_Cities", x => x.Id); 25 | }); 26 | 27 | migrationBuilder.CreateTable( 28 | name: "PointsOfInterest", 29 | columns: table => new 30 | { 31 | Id = table.Column(type: "INTEGER", nullable: false) 32 | .Annotation("Sqlite:Autoincrement", true), 33 | Name = table.Column(type: "TEXT", maxLength: 50, nullable: false), 34 | CityId = table.Column(type: "INTEGER", nullable: false) 35 | }, 36 | constraints: table => 37 | { 38 | table.PrimaryKey("PK_PointsOfInterest", x => x.Id); 39 | table.ForeignKey( 40 | name: "FK_PointsOfInterest_Cities_CityId", 41 | column: x => x.CityId, 42 | principalTable: "Cities", 43 | principalColumn: "Id", 44 | onDelete: ReferentialAction.Cascade); 45 | }); 46 | 47 | migrationBuilder.CreateIndex( 48 | name: "IX_PointsOfInterest_CityId", 49 | table: "PointsOfInterest", 50 | column: "CityId"); 51 | } 52 | 53 | /// 54 | protected override void Down(MigrationBuilder migrationBuilder) 55 | { 56 | migrationBuilder.DropTable( 57 | name: "PointsOfInterest"); 58 | 59 | migrationBuilder.DropTable( 60 | name: "Cities"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /CityInfo.API/Models/CityDto.cs: -------------------------------------------------------------------------------- 1 | namespace CityInfo.API.Models 2 | { 3 | public class CityDto 4 | { 5 | public int Id { get; set; } 6 | 7 | public string Name { get; set; } = string.Empty; 8 | 9 | public string? Description { get; set; } 10 | public int NumberOfPointsOfInterest 11 | { 12 | get 13 | { 14 | return PointsOfInterest.Count; 15 | } 16 | } 17 | 18 | public ICollection PointsOfInterest { get; set; } 19 | = new List(); 20 | } 21 | } -------------------------------------------------------------------------------- /CityInfo.API/Models/CityWithoutPointsOfInterestDto.cs: -------------------------------------------------------------------------------- 1 | using CityInfo.API.Entities; 2 | 3 | namespace CityInfo.API.Models 4 | { 5 | /// 6 | /// A city without points of interest 7 | /// 8 | public class CityWithoutPointsOfInterestDto 9 | { 10 | /// 11 | /// The id of the city 12 | /// 13 | public int Id { get; set; } 14 | 15 | /// 16 | /// The name of the city 17 | /// 18 | public string Name { get; set; } = string.Empty; 19 | 20 | /// 21 | /// The description of the city 22 | /// 23 | public string? Description { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /CityInfo.API/Models/PointOfInterestDto.cs: -------------------------------------------------------------------------------- 1 | namespace CityInfo.API.Models 2 | { 3 | public class PointOfInterestDto 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } = string.Empty; 7 | public string? Description { get; set; } 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /CityInfo.API/Models/PointOfInterestForCreationDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace CityInfo.API.Models 4 | { 5 | public class PointOfInterestForCreationDto 6 | { 7 | [Required(ErrorMessage = "You should provide a name value.")] 8 | [MaxLength(50)] 9 | public string Name { get; set; } = string.Empty; 10 | 11 | [MaxLength(200)] 12 | public string? Description { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CityInfo.API/Models/PointOfInterestForUpdateDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace CityInfo.API.Models 4 | { 5 | public class PointOfInterestForUpdateDto 6 | { 7 | [Required(ErrorMessage = "You should provide a name value.")] 8 | [MaxLength(50)] 9 | public string Name { get; set; } = string.Empty; 10 | 11 | [MaxLength(200)] 12 | public string? Description { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CityInfo.API/Profiles/CityProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace CityInfo.API.Profiles 4 | { 5 | public class CityProfile : Profile 6 | { 7 | public CityProfile() 8 | { 9 | CreateMap(); 10 | CreateMap(); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /CityInfo.API/Profiles/PointOfInterestProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace CityInfo.API.Profiles 4 | { 5 | public class PointOfInterestProfile : Profile 6 | { 7 | public PointOfInterestProfile() 8 | { 9 | CreateMap(); 10 | CreateMap(); 11 | CreateMap(); 12 | CreateMap(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CityInfo.API/Program.cs: -------------------------------------------------------------------------------- 1 | using Asp.Versioning; 2 | using Asp.Versioning.ApiExplorer; 3 | using Azure.Extensions.AspNetCore.Configuration.Secrets; 4 | using Azure.Identity; 5 | using Azure.Security.KeyVault.Secrets; 6 | using CityInfo.API; 7 | using CityInfo.API.DbContexts; 8 | using CityInfo.API.Services; 9 | using Microsoft.ApplicationInsights.Extensibility; 10 | using Microsoft.AspNetCore.HttpOverrides; 11 | using Microsoft.AspNetCore.StaticFiles; 12 | using Microsoft.EntityFrameworkCore; 13 | using Microsoft.IdentityModel.Tokens; 14 | using Microsoft.OpenApi.Models; 15 | using Serilog; 16 | using System.Reflection; 17 | using System.Security.Cryptography.Xml; 18 | using System.Text; 19 | 20 | 21 | Log.Logger = new LoggerConfiguration() 22 | .MinimumLevel.Debug() 23 | .WriteTo.Console() 24 | .CreateLogger(); 25 | 26 | var builder = WebApplication.CreateBuilder(args); 27 | 28 | //builder.Logging.ClearProviders(); 29 | //builder.Logging.AddConsole(); 30 | 31 | var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); 32 | if (environment == Environments.Development) 33 | { 34 | builder.Host.UseSerilog( 35 | (context, loggerConfiguration) => loggerConfiguration 36 | .MinimumLevel.Debug() 37 | .WriteTo.Console()); 38 | } 39 | else 40 | { 41 | var secretClient = new SecretClient( 42 | new Uri("https://pluralsightdemokeyvault.vault.azure.net/"), 43 | new DefaultAzureCredential()); 44 | builder.Configuration.AddAzureKeyVault(secretClient, 45 | new KeyVaultSecretManager()); 46 | 47 | builder.Host.UseSerilog( 48 | (context, loggerConfiguration) => loggerConfiguration 49 | .MinimumLevel.Debug() 50 | .WriteTo.Console() 51 | .WriteTo.File("logs/cityinfo.txt", rollingInterval: RollingInterval.Day) 52 | .WriteTo.ApplicationInsights(new TelemetryConfiguration 53 | { 54 | InstrumentationKey = builder.Configuration["ApplicationInsightsInstrumentationKey"] 55 | }, TelemetryConverter.Traces)); 56 | } 57 | 58 | 59 | // Add services to the container. 60 | 61 | builder.Services.AddControllers(options => 62 | { 63 | options.ReturnHttpNotAcceptable = true; 64 | }).AddNewtonsoftJson() 65 | .AddXmlDataContractSerializerFormatters(); 66 | 67 | builder.Services.AddProblemDetails(); 68 | //builder.Services.AddProblemDetails(options => 69 | //{ 70 | // options.CustomizeProblemDetails = ctx => 71 | // { 72 | // ctx.ProblemDetails.Extensions.Add("additionalInfo", 73 | // "Additional info example"); 74 | // ctx.ProblemDetails.Extensions.Add("server", 75 | // Environment.MachineName); 76 | // }; 77 | //}); 78 | 79 | builder.Services.AddSingleton(); 80 | 81 | #if DEBUG 82 | builder.Services.AddTransient(); 83 | #else 84 | builder.Services.AddTransient(); 85 | #endif 86 | builder.Services.AddSingleton(); 87 | 88 | builder.Services.AddDbContext( 89 | dbContextOptions => dbContextOptions.UseSqlite( 90 | builder.Configuration["ConnectionStrings:CityInfoDBConnectionString"])); 91 | 92 | builder.Services.AddScoped(); 93 | 94 | builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); 95 | 96 | builder.Services.AddAuthentication("Bearer") 97 | .AddJwtBearer(options => 98 | { 99 | options.TokenValidationParameters = new() 100 | { 101 | ValidateIssuer = true, 102 | ValidateAudience = true, 103 | ValidateIssuerSigningKey = true, 104 | ValidIssuer = builder.Configuration["Authentication:Issuer"], 105 | ValidAudience = builder.Configuration["Authentication:Audience"], 106 | IssuerSigningKey = new SymmetricSecurityKey( 107 | Convert.FromBase64String(builder.Configuration["Authentication:SecretForKey"])) 108 | }; 109 | } 110 | ); 111 | 112 | builder.Services.AddAuthorization(options => 113 | { 114 | options.AddPolicy("MustBeFromAntwerp", policy => 115 | { 116 | policy.RequireAuthenticatedUser(); 117 | policy.RequireClaim("city", "Antwerp"); 118 | }); 119 | }); 120 | 121 | builder.Services.AddApiVersioning(setupAction => 122 | { 123 | setupAction.ReportApiVersions = true; 124 | setupAction.AssumeDefaultVersionWhenUnspecified = true; 125 | setupAction.DefaultApiVersion = new ApiVersion(1, 0); 126 | }).AddMvc() 127 | .AddApiExplorer(setupAction => 128 | { 129 | setupAction.SubstituteApiVersionInUrl = true; 130 | }); 131 | 132 | // Learn more about configuring Swagger/OpenAPI at 133 | // https://aka.ms/aspnetcore/swashbuckle 134 | builder.Services.AddEndpointsApiExplorer(); 135 | 136 | var apiVersionDescriptionProvider = builder.Services.BuildServiceProvider() 137 | .GetRequiredService(); 138 | 139 | builder.Services.AddSwaggerGen(setupAction => 140 | { 141 | foreach (var description in 142 | apiVersionDescriptionProvider.ApiVersionDescriptions) 143 | { 144 | setupAction.SwaggerDoc( 145 | $"{description.GroupName}", 146 | new() 147 | { 148 | Title = "City Info API", 149 | Version = description.ApiVersion.ToString(), 150 | Description = "Through this API you can access cities and their points of interest." 151 | }); 152 | } 153 | 154 | var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; 155 | var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile); 156 | 157 | setupAction.IncludeXmlComments(xmlCommentsFullPath); 158 | 159 | setupAction.AddSecurityDefinition("CityInfoApiBearerAuth", new() 160 | { 161 | Type = SecuritySchemeType.Http, 162 | Scheme = "Bearer", 163 | Description = "Input a valid token to access this API" 164 | }); 165 | 166 | setupAction.AddSecurityRequirement(new() 167 | { 168 | { 169 | new () 170 | { 171 | Reference = new OpenApiReference { 172 | Type = ReferenceType.SecurityScheme, 173 | Id = "CityInfoApiBearerAuth" } 174 | }, 175 | new List() 176 | } 177 | }); 178 | }); 179 | 180 | builder.Services.Configure(options => 181 | { 182 | options.ForwardedHeaders = ForwardedHeaders.XForwardedFor 183 | | ForwardedHeaders.XForwardedProto; 184 | }); 185 | 186 | var app = builder.Build(); 187 | 188 | // Configure the HTTP request pipeline. 189 | if (!app.Environment.IsDevelopment()) 190 | { 191 | app.UseExceptionHandler(); 192 | } 193 | 194 | app.UseForwardedHeaders(); 195 | 196 | 197 | //if (app.Environment.IsDevelopment()) 198 | //{ 199 | app.UseSwagger(); 200 | app.UseSwaggerUI(setupAction => 201 | { 202 | var descriptions = app.DescribeApiVersions(); 203 | foreach (var description in descriptions) 204 | { 205 | setupAction.SwaggerEndpoint( 206 | $"/swagger/{description.GroupName}/swagger.json", 207 | description.GroupName.ToUpperInvariant()); 208 | } 209 | }); 210 | //} 211 | 212 | app.UseHttpsRedirection(); 213 | 214 | app.UseRouting(); 215 | 216 | app.UseAuthentication(); 217 | 218 | app.UseAuthorization(); 219 | 220 | app.UseEndpoints(endpoints => 221 | { 222 | endpoints.MapControllers(); 223 | }); 224 | 225 | app.Run(); 226 | -------------------------------------------------------------------------------- /CityInfo.API/Properties/ServiceDependencies/PluralsightDemo-CityInfoAPI - Web Deploy/profile.arm.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", 3 | "contentVersion": "1.0.0.0", 4 | "metadata": { 5 | "_dependencyType": "compute.appService.windows" 6 | }, 7 | "parameters": { 8 | "resourceGroupName": { 9 | "type": "string", 10 | "defaultValue": "Default", 11 | "metadata": { 12 | "description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking." 13 | } 14 | }, 15 | "resourceGroupLocation": { 16 | "type": "string", 17 | "defaultValue": "westeurope", 18 | "metadata": { 19 | "description": "Location of the resource group. Resource groups could have different location than resources, however by default we use API versions from latest hybrid profile which support all locations for resource types we support." 20 | } 21 | }, 22 | "resourceName": { 23 | "type": "string", 24 | "defaultValue": "PluralsightDemo-CityInfoAPI", 25 | "metadata": { 26 | "description": "Name of the main resource to be created by this template." 27 | } 28 | }, 29 | "resourceLocation": { 30 | "type": "string", 31 | "defaultValue": "[parameters('resourceGroupLocation')]", 32 | "metadata": { 33 | "description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there." 34 | } 35 | } 36 | }, 37 | "variables": { 38 | "appServicePlan_name": "[concat('Plan', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]", 39 | "appServicePlan_ResourceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/serverFarms/', variables('appServicePlan_name'))]" 40 | }, 41 | "resources": [ 42 | { 43 | "type": "Microsoft.Resources/resourceGroups", 44 | "name": "[parameters('resourceGroupName')]", 45 | "location": "[parameters('resourceGroupLocation')]", 46 | "apiVersion": "2019-10-01" 47 | }, 48 | { 49 | "type": "Microsoft.Resources/deployments", 50 | "name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat(parameters('resourceName'), subscription().subscriptionId)))]", 51 | "resourceGroup": "[parameters('resourceGroupName')]", 52 | "apiVersion": "2019-10-01", 53 | "dependsOn": [ 54 | "[parameters('resourceGroupName')]" 55 | ], 56 | "properties": { 57 | "mode": "Incremental", 58 | "template": { 59 | "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", 60 | "contentVersion": "1.0.0.0", 61 | "resources": [ 62 | { 63 | "location": "[parameters('resourceLocation')]", 64 | "name": "[parameters('resourceName')]", 65 | "type": "Microsoft.Web/sites", 66 | "apiVersion": "2015-08-01", 67 | "tags": { 68 | "[concat('hidden-related:', variables('appServicePlan_ResourceId'))]": "empty" 69 | }, 70 | "dependsOn": [ 71 | "[variables('appServicePlan_ResourceId')]" 72 | ], 73 | "kind": "app", 74 | "properties": { 75 | "name": "[parameters('resourceName')]", 76 | "kind": "app", 77 | "httpsOnly": true, 78 | "reserved": false, 79 | "serverFarmId": "[variables('appServicePlan_ResourceId')]", 80 | "siteConfig": { 81 | "metadata": [ 82 | { 83 | "name": "CURRENT_STACK", 84 | "value": "dotnetcore" 85 | } 86 | ] 87 | } 88 | }, 89 | "identity": { 90 | "type": "SystemAssigned" 91 | } 92 | }, 93 | { 94 | "location": "[parameters('resourceLocation')]", 95 | "name": "[variables('appServicePlan_name')]", 96 | "type": "Microsoft.Web/serverFarms", 97 | "apiVersion": "2015-08-01", 98 | "sku": { 99 | "name": "S1", 100 | "tier": "Standard", 101 | "family": "S", 102 | "size": "S1" 103 | }, 104 | "properties": { 105 | "name": "[variables('appServicePlan_name')]" 106 | } 107 | } 108 | ] 109 | } 110 | } 111 | } 112 | ] 113 | } -------------------------------------------------------------------------------- /CityInfo.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:37419", 8 | "sslPort": 44355 9 | } 10 | }, 11 | "profiles": { 12 | "CityInfo.API": { 13 | "commandName": "Project", 14 | "launchUrl": "swagger", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | }, 18 | "applicationUrl": "https://localhost:7169;http://localhost:5169", 19 | "dotnetRunMessages": true 20 | }, 21 | "IIS Express": { 22 | "commandName": "IISExpress", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /CityInfo.API/Services/CityInfoRepository.cs: -------------------------------------------------------------------------------- 1 | using CityInfo.API.DbContexts; 2 | using CityInfo.API.Entities; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace CityInfo.API.Services 6 | { 7 | public class CityInfoRepository : ICityInfoRepository 8 | { 9 | private readonly CityInfoContext _context; 10 | 11 | public CityInfoRepository(CityInfoContext context) 12 | { 13 | _context = context ?? throw new ArgumentNullException(nameof(context)); 14 | } 15 | 16 | public async Task> GetCitiesAsync() 17 | { 18 | return await _context.Cities.OrderBy(c => c.Name).ToListAsync(); 19 | } 20 | 21 | public async Task<(IEnumerable, PaginationMetadata)> GetCitiesAsync( 22 | string? name, string? searchQuery, int pageNumber, int pageSize) 23 | { 24 | // collection to start from 25 | var collection = _context.Cities as IQueryable; 26 | 27 | if (!string.IsNullOrWhiteSpace(name)) 28 | { 29 | name = name.Trim(); 30 | collection = collection.Where(c => c.Name == name); 31 | } 32 | 33 | if (!string.IsNullOrWhiteSpace(searchQuery)) 34 | { 35 | searchQuery = searchQuery.Trim(); 36 | collection = collection.Where(a => a.Name.Contains(searchQuery) 37 | || (a.Description != null && a.Description.Contains(searchQuery))); 38 | } 39 | 40 | var totalItemCount = await collection.CountAsync(); 41 | 42 | var paginationMetadata = new PaginationMetadata( 43 | totalItemCount, pageSize, pageNumber); 44 | 45 | var collectionToReturn = await collection.OrderBy(c => c.Name) 46 | .Skip(pageSize * (pageNumber - 1)) 47 | .Take(pageSize) 48 | .ToListAsync(); 49 | 50 | return (collectionToReturn, paginationMetadata); 51 | } 52 | 53 | 54 | 55 | public async Task GetCityAsync(int cityId, bool includePointsOfInterest) 56 | { 57 | if (includePointsOfInterest) 58 | { 59 | return await _context.Cities.Include(c => c.PointsOfInterest) 60 | .Where(c => c.Id == cityId).FirstOrDefaultAsync(); 61 | } 62 | 63 | return await _context.Cities 64 | .Where(c => c.Id == cityId).FirstOrDefaultAsync(); 65 | } 66 | 67 | public async Task CityExistsAsync(int cityId) 68 | { 69 | return await _context.Cities.AnyAsync(c => c.Id == cityId); 70 | } 71 | 72 | public async Task GetPointOfInterestForCityAsync( 73 | int cityId, 74 | int pointOfInterestId) 75 | { 76 | return await _context.PointsOfInterest 77 | .Where(p => p.CityId == cityId && p.Id == pointOfInterestId) 78 | .FirstOrDefaultAsync(); 79 | } 80 | 81 | public async Task> GetPointsOfInterestForCityAsync( 82 | int cityId) 83 | { 84 | return await _context.PointsOfInterest 85 | .Where(p => p.CityId == cityId).ToListAsync(); 86 | } 87 | 88 | public async Task AddPointOfInterestForCityAsync(int cityId, 89 | PointOfInterest pointOfInterest) 90 | { 91 | var city = await GetCityAsync(cityId, false); 92 | if (city != null) 93 | { 94 | city.PointsOfInterest.Add(pointOfInterest); 95 | } 96 | } 97 | 98 | public void DeletePointOfInterest(PointOfInterest pointOfInterest) 99 | { 100 | _context.PointsOfInterest.Remove(pointOfInterest); 101 | } 102 | 103 | public async Task SaveChangesAsync() 104 | { 105 | return (await _context.SaveChangesAsync() >= 0); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /CityInfo.API/Services/CloudMailService.cs: -------------------------------------------------------------------------------- 1 | namespace CityInfo.API.Services 2 | { 3 | public class CloudMailService : IMailService 4 | { 5 | private string _mailTo = string.Empty; 6 | private string _mailFrom = string.Empty; 7 | 8 | public CloudMailService(IConfiguration configuration) 9 | { 10 | _mailTo = configuration["mailSettings:mailToAddress"]; 11 | _mailFrom = configuration["mailSettings:mailFromAddress"]; 12 | } 13 | 14 | public void Send(string subject, string message) 15 | { 16 | // send mail - output to console window 17 | Console.WriteLine($"Mail from {_mailFrom} to {_mailTo}, with {nameof(CloudMailService)}."); 18 | Console.WriteLine($"Subject: {subject}"); 19 | Console.WriteLine($"Message: {message}"); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CityInfo.API/Services/ICityInfoRepository.cs: -------------------------------------------------------------------------------- 1 | using CityInfo.API.Entities; 2 | 3 | namespace CityInfo.API.Services 4 | { 5 | public interface ICityInfoRepository 6 | { 7 | Task> GetCitiesAsync(); 8 | Task<(IEnumerable, PaginationMetadata)> GetCitiesAsync( 9 | string? name, string? searchQuery, int pageNumber, int pageSize); 10 | Task GetCityAsync(int cityId, bool includePointsOfInterest); 11 | Task CityExistsAsync(int cityId); 12 | Task> GetPointsOfInterestForCityAsync(int cityId); 13 | Task GetPointOfInterestForCityAsync(int cityId, 14 | int pointOfInterestId); 15 | Task AddPointOfInterestForCityAsync(int cityId, PointOfInterest pointOfInterest); 16 | void DeletePointOfInterest(PointOfInterest pointOfInterest); 17 | Task SaveChangesAsync(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CityInfo.API/Services/IMailService.cs: -------------------------------------------------------------------------------- 1 | namespace CityInfo.API.Services 2 | { 3 | public interface IMailService 4 | { 5 | void Send(string subject, string message); 6 | } 7 | } -------------------------------------------------------------------------------- /CityInfo.API/Services/LocalMailService.cs: -------------------------------------------------------------------------------- 1 | namespace CityInfo.API.Services 2 | { 3 | public class LocalMailService : IMailService 4 | { 5 | private string _mailTo = string.Empty; 6 | private string _mailFrom = string.Empty; 7 | 8 | public LocalMailService(IConfiguration configuration) 9 | { 10 | _mailTo = configuration["mailSettings:mailToAddress"]; 11 | _mailFrom = configuration["mailSettings:mailFromAddress"]; 12 | } 13 | 14 | public void Send(string subject, string message) 15 | { 16 | // send mail - output to console window 17 | Console.WriteLine($"Mail from {_mailFrom} to {_mailTo}, with {nameof(LocalMailService)}."); 18 | Console.WriteLine($"Subject: {subject}"); 19 | Console.WriteLine($"Message: {message}"); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CityInfo.API/Services/PaginationMetadata.cs: -------------------------------------------------------------------------------- 1 | namespace CityInfo.API.Services 2 | { 3 | public class PaginationMetadata 4 | { 5 | public int TotalItemCount { get; set; } 6 | public int TotalPageCount { get; set; } 7 | public int PageSize { get; set; } 8 | public int CurrentPage { get; set; } 9 | 10 | public PaginationMetadata(int totalItemCount, int pageSize, int currentPage) 11 | { 12 | TotalItemCount = totalItemCount; 13 | PageSize = pageSize; 14 | CurrentPage = currentPage; 15 | TotalPageCount = (int)Math.Ceiling(totalItemCount / (double)pageSize); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CityInfo.API/appSettings.Production.json: -------------------------------------------------------------------------------- 1 | { 2 | "mailSettings": { 3 | "mailToAddress": "admin@mycompany.com" 4 | }, 5 | "ConnectionStrings": { 6 | "CityInfoDBConnectionString": "Data Source=CityInfo.db" 7 | }, 8 | "Authentication": { 9 | "Issuer": "https://pluralsightdemo-cityinfoapi.azurewebsites.net/", 10 | "Audience": "cityinfoapi" 11 | } 12 | } -------------------------------------------------------------------------------- /CityInfo.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning", 6 | "CityInfo.API.Controllers": "Information", 7 | "Microsoft.EntityFrameworkCore.Database.Command": "Information" 8 | } 9 | }, 10 | "ConnectionStrings": { 11 | "CityInfoDBConnectionString": "Data Source=CityInfo.db" 12 | }, 13 | "Authentication": { 14 | "SecretForKey": "RgDldLrK+p+T0JisAKdD7THnT/npmWYl4vV3UUiRSVE=", 15 | "Issuer": "https://localhost:7169", 16 | "Audience": "cityinfoapi" 17 | } 18 | } -------------------------------------------------------------------------------- /CityInfo.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "mailSettings": { 9 | "mailToAddress": "developer@mycompany.com", 10 | "mailFromAddress": "noreply@mycompany.com" 11 | }, 12 | "AllowedHosts": "*", 13 | "ApplicationInsightsInstrumentationKey": "a416c616-5993-48ac-b420-a5f4e88392f0" 14 | } 15 | -------------------------------------------------------------------------------- /CityInfo.API/getting-started-with-rest-slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KevinDockx/AspNetCoreWebApiFundamentals/c6e3c88a265292450b2001231180317da079cf6f/CityInfo.API/getting-started-with-rest-slides.pdf -------------------------------------------------------------------------------- /CityInfo.API/uploaded_file_a0a9de17-1941-4d82-b102-f062ad0c84b5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KevinDockx/AspNetCoreWebApiFundamentals/c6e3c88a265292450b2001231180317da079cf6f/CityInfo.API/uploaded_file_a0a9de17-1941-4d82-b102-f062ad0c84b5.pdf -------------------------------------------------------------------------------- /CityInfo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31919.166 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CityInfo.API", "CityInfo.API\CityInfo.API.csproj", "{2E9DBB4F-88CA-41AC-9F0B-BC21AA23ADEE}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {2E9DBB4F-88CA-41AC-9F0B-BC21AA23ADEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {2E9DBB4F-88CA-41AC-9F0B-BC21AA23ADEE}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {2E9DBB4F-88CA-41AC-9F0B-BC21AA23ADEE}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {2E9DBB4F-88CA-41AC-9F0B-BC21AA23ADEE}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {8246798E-74EA-4D7A-9E06-5B8930FFBD43} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Kevin Dockx 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ASP.NET Core Web API Fundamentals 2 | Fully functioning sample code for my ASP.NET Core Web API Fundamentals course, currently targeting .NET 8 and .NET 9. 3 | 4 | - The **main** branch targets .NET 8 and exactly matches the course. 5 | - The **net9** branch targets .NET 9. 6 | - The **latest-and-greatest** branch also targets .NET 9, and contains changes that were incorporated after recording. Most often these changes are language features that are relatively new and/or in preview, like primary constructors, switch expressions and so on. Most of these changes will probably make it into the main branch when course updates happen, but if you don't want to wait for that you can already check it out - enjoy :-) 7 | 8 | All my courses can be found at https://app.pluralsight.com/profile/author/kevin-dockx 9 | --------------------------------------------------------------------------------