├── .gitignore ├── Finished sample ├── Movies.API │ ├── Contexts │ │ └── MoviesContext.cs │ ├── Controllers │ │ ├── MoviesController.cs │ │ ├── PostersController.cs │ │ └── TrailersController.cs │ ├── Entities │ │ ├── Director.cs │ │ └── Movie.cs │ ├── InternalModels │ │ ├── Poster.cs │ │ └── Trailer.cs │ ├── Migrations │ │ ├── InitialMigration.Designer.cs │ │ ├── InitialMigration.cs │ │ └── MoviesContextModelSnapshot.cs │ ├── Models │ │ ├── Movie.cs │ │ ├── MovieForCreation.cs │ │ ├── MovieForUpdate.cs │ │ ├── Poster.cs │ │ ├── PosterForCreation.cs │ │ ├── Trailer.cs │ │ └── TrailerForCreation.cs │ ├── Movies.API.csproj │ ├── Movies.db │ ├── Profiles │ │ ├── MoviesProfile.cs │ │ ├── PostersProfile.cs │ │ └── TrailersProfile.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Services │ │ ├── IMoviesRepository.cs │ │ ├── IPostersRepository.cs │ │ ├── ITrailersRepository.cs │ │ ├── MoviesRepository.cs │ │ ├── PostersRepository.cs │ │ └── TrailersRepository.cs │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── Movies.Client │ ├── Models │ │ └── GeneratedDtoModels.cs │ ├── Movies.Client.csproj │ ├── MoviesClient.cs │ ├── Program.cs │ ├── RetryPolicyDelegatingHandler.cs │ ├── Return401UnauthorizedResponseHandler.cs │ ├── Services │ │ ├── CRUDService.cs │ │ ├── CancellationService.cs │ │ ├── DealingWithErrorsAndFaultsService.cs │ │ ├── HttpClientFactoryInstanceManagementService.cs │ │ ├── HttpHandlersService.cs │ │ ├── IIntegrationService.cs │ │ ├── PartialUpdateService.cs │ │ └── StreamService.cs │ ├── StreamExtensions.cs │ ├── TestableClassWithApiAccess.cs │ ├── TimeOutDelegatingHandler.cs │ └── UnauthorizedApiAccessException.cs ├── Movies.UnitTests │ ├── Movies.UnitTests.csproj │ └── TestableClassWithApiAccessUnitTests.cs └── Movies.sln ├── README.md └── Starter files ├── Movies.API ├── Contexts │ └── MoviesContext.cs ├── Controllers │ ├── MoviesController.cs │ ├── PostersController.cs │ └── TrailersController.cs ├── Entities │ ├── Director.cs │ └── Movie.cs ├── InternalModels │ ├── Poster.cs │ └── Trailer.cs ├── Migrations │ ├── InitialMigration.Designer.cs │ ├── InitialMigration.cs │ └── MoviesContextModelSnapshot.cs ├── Models │ ├── Movie.cs │ ├── MovieForCreation.cs │ ├── MovieForUpdate.cs │ ├── Poster.cs │ ├── PosterForCreation.cs │ ├── Trailer.cs │ └── TrailerForCreation.cs ├── Movies.API.csproj ├── Movies.db ├── Profiles │ ├── MoviesProfile.cs │ ├── PostersProfile.cs │ └── TrailersProfile.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Services │ ├── IMoviesRepository.cs │ ├── IPostersRepository.cs │ ├── ITrailersRepository.cs │ ├── MoviesRepository.cs │ ├── PostersRepository.cs │ └── TrailersRepository.cs ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── Movies.Client ├── Movies.Client.csproj ├── Program.cs └── Services │ ├── CRUDService.cs │ ├── CancellationService.cs │ ├── DealingWithErrorsAndFaultsService.cs │ ├── HttpClientFactoryInstanceManagementService.cs │ ├── HttpHandlersService.cs │ ├── IIntegrationService.cs │ ├── PartialUpdateService.cs │ └── StreamService.cs └── Movies.sln /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # 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 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Contexts/MoviesContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Movies.API.Entities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Movies.API.Contexts 9 | { 10 | public class MoviesContext : DbContext 11 | { 12 | public DbSet Movies { get; set; } 13 | 14 | public MoviesContext(DbContextOptions options) 15 | : base(options) 16 | { 17 | } 18 | 19 | // seed the database with data 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | modelBuilder.Entity().HasData( 23 | new Director() 24 | { 25 | Id = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 26 | FirstName = "Quentin", 27 | LastName = "Tarantino" 28 | }, 29 | new Director() 30 | { 31 | Id = Guid.Parse("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 32 | FirstName = "Joel", 33 | LastName = "Coen" 34 | }, 35 | new Director() 36 | { 37 | Id = Guid.Parse("c19099ed-94db-44ba-885b-0ad7205d5e40"), 38 | FirstName = "Martin", 39 | LastName = "Scorsese" 40 | }, 41 | new Director() 42 | { 43 | Id = Guid.Parse("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 44 | FirstName = "David", 45 | LastName = "Fincher" 46 | }, 47 | new Director() 48 | { 49 | Id = Guid.Parse("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 50 | FirstName = "Bryan", 51 | LastName = "Singer" 52 | }, 53 | new Director() 54 | { 55 | Id = Guid.Parse("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 56 | FirstName = "James", 57 | LastName = "Cameron" 58 | }); 59 | 60 | modelBuilder.Entity().HasData( 61 | new Movie 62 | { 63 | Id = Guid.Parse("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), 64 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 65 | Title = "Pulp Fiction", 66 | Description = "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", 67 | ReleaseDate = new DateTimeOffset(new DateTime(1994,11,9)), 68 | Genre = "Crime, Drama" 69 | }, 70 | new Movie 71 | { 72 | Id = Guid.Parse("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), 73 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 74 | Title = "Jackie Brown", 75 | Description = "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", 76 | ReleaseDate = new DateTimeOffset(new DateTime(1997, 12, 25)), 77 | Genre = "Crime, Drama" 78 | }, 79 | new Movie 80 | { 81 | Id = Guid.Parse("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), 82 | DirectorId = Guid.Parse("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 83 | Title = "The Big Lebowski", 84 | Description = "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", 85 | ReleaseDate = new DateTimeOffset(new DateTime(1998, 3, 6)), 86 | Genre = "Comedy, Crime" 87 | }, 88 | new Movie 89 | { 90 | Id = Guid.Parse("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), 91 | DirectorId = Guid.Parse("c19099ed-94db-44ba-885b-0ad7205d5e40"), 92 | Title = "Casino", 93 | Description = "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", 94 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 11, 22)), 95 | Genre = "Crime, Drama" 96 | }, 97 | new Movie 98 | { 99 | Id = Guid.Parse("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), 100 | DirectorId = Guid.Parse("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 101 | Title = "Fight Club", 102 | Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", 103 | ReleaseDate = new DateTimeOffset(new DateTime(1999, 10, 15)), 104 | Genre = "Drama" 105 | }, 106 | new Movie 107 | { 108 | Id = Guid.Parse("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), 109 | DirectorId = Guid.Parse("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 110 | Title = "The Usual Suspects", 111 | Description = "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", 112 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 9, 15)), 113 | Genre = "Crime, Thriller" 114 | }, 115 | new Movie 116 | { 117 | Id = Guid.Parse("26fcbcc4-b7f7-47fc-9382-740c12246b59"), 118 | DirectorId = Guid.Parse("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 119 | Title = "Terminator 2: Judgment Day", 120 | Description = "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", 121 | ReleaseDate = new DateTimeOffset(new DateTime(1991, 7, 3)), 122 | Genre = "Action, Sci-Fi" 123 | }); 124 | 125 | base.OnModelCreating(modelBuilder); 126 | } 127 | 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Controllers/MoviesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using Microsoft.AspNetCore.JsonPatch; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Movies.API.Entities; 9 | using Movies.API.Services; 10 | 11 | namespace Movies.API.Controllers 12 | { 13 | [Route("api/movies")] 14 | [ApiController] 15 | public class MoviesController : ControllerBase 16 | { 17 | private readonly IMoviesRepository _moviesRepository; 18 | private readonly IMapper _mapper; 19 | 20 | public MoviesController(IMoviesRepository moviesRepository, 21 | IMapper mapper) 22 | { 23 | _moviesRepository = moviesRepository ?? throw new ArgumentNullException(nameof(moviesRepository)); 24 | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); 25 | } 26 | 27 | [HttpGet] 28 | public async Task>> GetMovies() 29 | { 30 | var movieEntities = await _moviesRepository.GetMoviesAsync(); 31 | return Ok(_mapper.Map>(movieEntities)); 32 | } 33 | 34 | 35 | [HttpGet("{movieId}", Name = "GetMovie")] 36 | public async Task> GetMovie(Guid movieId) 37 | { 38 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 39 | if (movieEntity == null) 40 | { 41 | return NotFound(); 42 | } 43 | 44 | return Ok(_mapper.Map(movieEntity)); 45 | } 46 | 47 | [HttpPost] 48 | public async Task CreateMovie( 49 | [FromBody] Models.MovieForCreation movieForCreation) 50 | { 51 | // model validation 52 | if (movieForCreation == null) 53 | { 54 | return BadRequest(); 55 | } 56 | 57 | if (!ModelState.IsValid) 58 | { 59 | // return 422 - Unprocessable Entity when validation fails 60 | return new UnprocessableEntityObjectResult(ModelState); 61 | } 62 | 63 | var movieEntity = _mapper.Map(movieForCreation); 64 | _moviesRepository.AddMovie(movieEntity); 65 | 66 | // save the changes 67 | await _moviesRepository.SaveChangesAsync(); 68 | 69 | // Fetch the movie from the data store so the director is included 70 | await _moviesRepository.GetMovieAsync(movieEntity.Id); 71 | 72 | return CreatedAtRoute("GetMovie", 73 | new { movieId = movieEntity.Id }, 74 | _mapper.Map(movieEntity)); 75 | } 76 | 77 | [HttpPut("{movieId}")] 78 | public async Task UpdateMovie(Guid movieId, 79 | [FromBody] Models.MovieForUpdate movieForUpdate) 80 | { 81 | // model validation 82 | if (movieForUpdate == null) 83 | { 84 | //return BadRequest(); 85 | } 86 | 87 | if (!ModelState.IsValid) 88 | { 89 | // return 422 - Unprocessable Entity when validation fails 90 | return new UnprocessableEntityObjectResult(ModelState); 91 | } 92 | 93 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 94 | if (movieEntity == null) 95 | { 96 | return NotFound(); 97 | } 98 | 99 | // map the inputted object into the movie entity 100 | // this ensures properties will get updated 101 | _mapper.Map(movieForUpdate, movieEntity); 102 | 103 | // call into UpdateMovie even though in our implementation 104 | // this doesn't contain code - doing this ensures the code stays 105 | // reliable when other repository implemenations (eg: a mock 106 | // repository) are used. 107 | _moviesRepository.UpdateMovie(movieEntity); 108 | 109 | await _moviesRepository.SaveChangesAsync(); 110 | 111 | // return the updated movie, after mapping it 112 | return Ok(_mapper.Map(movieEntity)); 113 | } 114 | 115 | [HttpPatch("{movieId}")] 116 | public async Task PartiallyUpdateMovie(Guid movieId, 117 | [FromBody] JsonPatchDocument patchDoc) 118 | { 119 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 120 | if (movieEntity == null) 121 | { 122 | return NotFound(); 123 | } 124 | 125 | // the patch is on a DTO, not on the movie entity 126 | var movieToPatch = _mapper.Map(movieEntity); 127 | 128 | patchDoc.ApplyTo(movieToPatch, ModelState); 129 | 130 | if (!ModelState.IsValid) 131 | { 132 | return new UnprocessableEntityObjectResult(ModelState); 133 | } 134 | 135 | // map back to the entity, and save 136 | _mapper.Map(movieToPatch, movieEntity); 137 | 138 | // call into UpdateMovie even though in our implementation 139 | // this doesn't contain code - doing this ensures the code stays 140 | // reliable when other repository implemenations (eg: a mock 141 | // repository) are used. 142 | _moviesRepository.UpdateMovie(movieEntity); 143 | 144 | await _moviesRepository.SaveChangesAsync(); 145 | 146 | // return the updated movie, after mapping it 147 | return Ok(_mapper.Map(movieEntity)); 148 | } 149 | 150 | [HttpDelete("{movieid}")] 151 | public async Task DeleteMovie(Guid movieId) 152 | { 153 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 154 | if (movieEntity == null) 155 | { 156 | return NotFound(); 157 | } 158 | 159 | _moviesRepository.DeleteMovie(movieEntity); 160 | await _moviesRepository.SaveChangesAsync(); 161 | 162 | return NoContent(); 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Controllers/PostersController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Movies.API.InternalModels; 4 | using Movies.API.Services; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace Movies.API.Controllers 11 | { 12 | [Route("api/movies/{movieId}/posters")] 13 | [ApiController] 14 | public class PostersController : ControllerBase 15 | { 16 | private readonly IPostersRepository _postersRepository; 17 | private readonly IMapper _mapper; 18 | 19 | public PostersController(IPostersRepository postersRepository, 20 | IMapper mapper) 21 | { 22 | _postersRepository = postersRepository ?? throw new ArgumentNullException(nameof(postersRepository)); 23 | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); 24 | } 25 | 26 | [HttpGet("{posterId}", Name = "GetPoster")] 27 | public async Task> GetPoster(Guid movieId, Guid posterId) 28 | { 29 | var poster = await _postersRepository.GetPosterAsync(movieId, posterId); 30 | if (poster == null) 31 | { 32 | return NotFound(); 33 | } 34 | 35 | return Ok(_mapper.Map(poster)); 36 | } 37 | 38 | [HttpPost] 39 | public async Task CreatePoster(Guid movieId, 40 | [FromBody] Models.PosterForCreation posterForCreation) 41 | { 42 | // model validation 43 | if (posterForCreation == null) 44 | { 45 | return BadRequest(); 46 | } 47 | 48 | if (!ModelState.IsValid) 49 | { 50 | // return 422 - Unprocessable Entity when validation fails 51 | return new UnprocessableEntityObjectResult(ModelState); 52 | } 53 | 54 | var poster = _mapper.Map(posterForCreation); 55 | var createdPoster = await _postersRepository.AddPoster(movieId, poster); 56 | 57 | // no need to save, in this type of repo the poster is 58 | // immediately persisted. 59 | 60 | // map the poster from the repository to a shared model poster 61 | return CreatedAtRoute("GetPoster", 62 | new { movieId, posterId = createdPoster.Id }, 63 | _mapper.Map(createdPoster)); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Controllers/TrailersController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Movies.API.InternalModels; 4 | using Movies.API.Services; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace Movies.API.Controllers 11 | { 12 | [Route("api/movies/{movieId}/trailers")] 13 | [ApiController] 14 | public class TrailersController : ControllerBase 15 | { 16 | private readonly ITrailersRepository _trailersRepository; 17 | private readonly IMapper _mapper; 18 | 19 | public TrailersController(ITrailersRepository trailersRepository, 20 | IMapper mapper) 21 | { 22 | _trailersRepository = trailersRepository ?? throw new ArgumentNullException(nameof(trailersRepository)); 23 | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); 24 | } 25 | 26 | [HttpGet("{trailerId}", Name = "GetTrailer")] 27 | public async Task> GetTrailer(Guid movieId, Guid trailerId) 28 | { 29 | var trailer = await _trailersRepository.GetTrailerAsync(movieId, trailerId); 30 | if (trailer == null) 31 | { 32 | return NotFound(); 33 | } 34 | 35 | return Ok(_mapper.Map(trailer)); 36 | } 37 | 38 | [HttpPost] 39 | public async Task CreateTrailer(Guid movieId, 40 | [FromBody] Models.TrailerForCreation trailerForCreation) 41 | { 42 | // model validation 43 | if (trailerForCreation == null) 44 | { 45 | return BadRequest(); 46 | } 47 | 48 | if (!ModelState.IsValid) 49 | { 50 | // return 422 - Unprocessable Entity when validation fails 51 | return new UnprocessableEntityObjectResult(ModelState); 52 | } 53 | 54 | var trailer = _mapper.Map(trailerForCreation); 55 | var createdTrailer = await _trailersRepository.AddTrailer(movieId, trailer); 56 | 57 | // no need to save, in this type of repo the trailer is 58 | // immediately persisted. 59 | 60 | // map the trailer from the repository to a shared model trailer 61 | return CreatedAtRoute("GetTrailer", 62 | new { movieId, trailerId = createdTrailer.Id }, 63 | _mapper.Map(createdTrailer)); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Entities/Director.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Movies.API.Entities 9 | { 10 | [Table("Directors")] 11 | public class Director 12 | { 13 | [Key] 14 | public Guid Id { get; set; } 15 | 16 | [Required] 17 | [MaxLength(200)] 18 | public string FirstName { get; set; } 19 | 20 | [Required] 21 | [MaxLength(200)] 22 | public string LastName { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Entities/Movie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Movies.API.Entities 9 | { 10 | [Table("Movies")] 11 | public class Movie 12 | { 13 | [Key] 14 | public Guid Id { get; set; } 15 | 16 | [Required] 17 | [MaxLength(200)] 18 | public string Title { get; set; } 19 | 20 | [MaxLength(2000)] 21 | public string Description { get; set; } 22 | 23 | [MaxLength(200)] 24 | public string Genre { get; set; } 25 | 26 | [Required] 27 | public DateTimeOffset ReleaseDate { get; set; } 28 | 29 | [Required] 30 | public Guid DirectorId { get; set; } 31 | public Director Director { get; set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/InternalModels/Poster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.InternalModels 8 | { 9 | public class Poster 10 | { 11 | [Required] 12 | public Guid Id { get; set; } 13 | 14 | [Required] 15 | public Guid MovieId { get; set; } 16 | 17 | [Required] 18 | [MaxLength(200)] 19 | public string Name { get; set; } 20 | 21 | [Required] 22 | public byte[] Bytes { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/InternalModels/Trailer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.InternalModels 8 | { 9 | public class Trailer 10 | { 11 | [Required] 12 | public Guid Id { get; set; } 13 | 14 | [Required] 15 | public Guid MovieId { get; set; } 16 | 17 | [Required] 18 | [MaxLength(200)] 19 | public string Name { get; set; } 20 | 21 | [MaxLength(1000)] 22 | public string Description { get; set; } 23 | 24 | [Required] 25 | public byte[] Bytes { get; set; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Migrations/InitialMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Movies.API.Contexts; 8 | 9 | namespace Movies.API.Migrations 10 | { 11 | [DbContext(typeof(MoviesContext))] 12 | [Migration("20210413080151_InitialMigration")] 13 | partial class InitialMigration 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "5.0.4"); 20 | 21 | modelBuilder.Entity("Movies.API.Entities.Director", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd() 25 | .HasColumnType("TEXT"); 26 | 27 | b.Property("FirstName") 28 | .IsRequired() 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("LastName") 33 | .IsRequired() 34 | .HasMaxLength(200) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Directors"); 40 | 41 | b.HasData( 42 | new 43 | { 44 | Id = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 45 | FirstName = "Quentin", 46 | LastName = "Tarantino" 47 | }, 48 | new 49 | { 50 | Id = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 51 | FirstName = "Joel", 52 | LastName = "Coen" 53 | }, 54 | new 55 | { 56 | Id = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 57 | FirstName = "Martin", 58 | LastName = "Scorsese" 59 | }, 60 | new 61 | { 62 | Id = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 63 | FirstName = "David", 64 | LastName = "Fincher" 65 | }, 66 | new 67 | { 68 | Id = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 69 | FirstName = "Bryan", 70 | LastName = "Singer" 71 | }, 72 | new 73 | { 74 | Id = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 75 | FirstName = "James", 76 | LastName = "Cameron" 77 | }); 78 | }); 79 | 80 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 81 | { 82 | b.Property("Id") 83 | .ValueGeneratedOnAdd() 84 | .HasColumnType("TEXT"); 85 | 86 | b.Property("Description") 87 | .HasMaxLength(2000) 88 | .HasColumnType("TEXT"); 89 | 90 | b.Property("DirectorId") 91 | .HasColumnType("TEXT"); 92 | 93 | b.Property("Genre") 94 | .HasMaxLength(200) 95 | .HasColumnType("TEXT"); 96 | 97 | b.Property("ReleaseDate") 98 | .HasColumnType("TEXT"); 99 | 100 | b.Property("Title") 101 | .IsRequired() 102 | .HasMaxLength(200) 103 | .HasColumnType("TEXT"); 104 | 105 | b.HasKey("Id"); 106 | 107 | b.HasIndex("DirectorId"); 108 | 109 | b.ToTable("Movies"); 110 | 111 | b.HasData( 112 | new 113 | { 114 | Id = new Guid("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), 115 | Description = "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", 116 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 117 | Genre = "Crime, Drama", 118 | ReleaseDate = new DateTimeOffset(new DateTime(1994, 11, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 119 | Title = "Pulp Fiction" 120 | }, 121 | new 122 | { 123 | Id = new Guid("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), 124 | Description = "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", 125 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 126 | Genre = "Crime, Drama", 127 | ReleaseDate = new DateTimeOffset(new DateTime(1997, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 128 | Title = "Jackie Brown" 129 | }, 130 | new 131 | { 132 | Id = new Guid("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), 133 | Description = "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", 134 | DirectorId = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 135 | Genre = "Comedy, Crime", 136 | ReleaseDate = new DateTimeOffset(new DateTime(1998, 3, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 137 | Title = "The Big Lebowski" 138 | }, 139 | new 140 | { 141 | Id = new Guid("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), 142 | Description = "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", 143 | DirectorId = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 144 | Genre = "Crime, Drama", 145 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 11, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 146 | Title = "Casino" 147 | }, 148 | new 149 | { 150 | Id = new Guid("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), 151 | Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", 152 | DirectorId = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 153 | Genre = "Drama", 154 | ReleaseDate = new DateTimeOffset(new DateTime(1999, 10, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 155 | Title = "Fight Club" 156 | }, 157 | new 158 | { 159 | Id = new Guid("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), 160 | Description = "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", 161 | DirectorId = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 162 | Genre = "Crime, Thriller", 163 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 9, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 164 | Title = "The Usual Suspects" 165 | }, 166 | new 167 | { 168 | Id = new Guid("26fcbcc4-b7f7-47fc-9382-740c12246b59"), 169 | Description = "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", 170 | DirectorId = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 171 | Genre = "Action, Sci-Fi", 172 | ReleaseDate = new DateTimeOffset(new DateTime(1991, 7, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 173 | Title = "Terminator 2: Judgment Day" 174 | }); 175 | }); 176 | 177 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 178 | { 179 | b.HasOne("Movies.API.Entities.Director", "Director") 180 | .WithMany() 181 | .HasForeignKey("DirectorId") 182 | .OnDelete(DeleteBehavior.Cascade) 183 | .IsRequired(); 184 | 185 | b.Navigation("Director"); 186 | }); 187 | #pragma warning restore 612, 618 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Migrations/InitialMigration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace Movies.API.Migrations 5 | { 6 | public partial class InitialMigration : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Directors", 12 | columns: table => new 13 | { 14 | Id = table.Column(type: "TEXT", nullable: false), 15 | FirstName = table.Column(type: "TEXT", maxLength: 200, nullable: false), 16 | LastName = table.Column(type: "TEXT", maxLength: 200, nullable: false) 17 | }, 18 | constraints: table => 19 | { 20 | table.PrimaryKey("PK_Directors", x => x.Id); 21 | }); 22 | 23 | migrationBuilder.CreateTable( 24 | name: "Movies", 25 | columns: table => new 26 | { 27 | Id = table.Column(type: "TEXT", nullable: false), 28 | Title = table.Column(type: "TEXT", maxLength: 200, nullable: false), 29 | Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), 30 | Genre = table.Column(type: "TEXT", maxLength: 200, nullable: true), 31 | ReleaseDate = table.Column(type: "TEXT", nullable: false), 32 | DirectorId = table.Column(type: "TEXT", nullable: false) 33 | }, 34 | constraints: table => 35 | { 36 | table.PrimaryKey("PK_Movies", x => x.Id); 37 | table.ForeignKey( 38 | name: "FK_Movies_Directors_DirectorId", 39 | column: x => x.DirectorId, 40 | principalTable: "Directors", 41 | principalColumn: "Id", 42 | onDelete: ReferentialAction.Cascade); 43 | }); 44 | 45 | migrationBuilder.InsertData( 46 | table: "Directors", 47 | columns: new[] { "Id", "FirstName", "LastName" }, 48 | values: new object[] { new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), "Quentin", "Tarantino" }); 49 | 50 | migrationBuilder.InsertData( 51 | table: "Directors", 52 | columns: new[] { "Id", "FirstName", "LastName" }, 53 | values: new object[] { new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), "Joel", "Coen" }); 54 | 55 | migrationBuilder.InsertData( 56 | table: "Directors", 57 | columns: new[] { "Id", "FirstName", "LastName" }, 58 | values: new object[] { new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), "Martin", "Scorsese" }); 59 | 60 | migrationBuilder.InsertData( 61 | table: "Directors", 62 | columns: new[] { "Id", "FirstName", "LastName" }, 63 | values: new object[] { new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), "David", "Fincher" }); 64 | 65 | migrationBuilder.InsertData( 66 | table: "Directors", 67 | columns: new[] { "Id", "FirstName", "LastName" }, 68 | values: new object[] { new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), "Bryan", "Singer" }); 69 | 70 | migrationBuilder.InsertData( 71 | table: "Directors", 72 | columns: new[] { "Id", "FirstName", "LastName" }, 73 | values: new object[] { new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), "James", "Cameron" }); 74 | 75 | migrationBuilder.InsertData( 76 | table: "Movies", 77 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 78 | values: new object[] { new Guid("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), "Crime, Drama", new DateTimeOffset(new DateTime(1994, 11, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "Pulp Fiction" }); 79 | 80 | migrationBuilder.InsertData( 81 | table: "Movies", 82 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 83 | values: new object[] { new Guid("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), "Crime, Drama", new DateTimeOffset(new DateTime(1997, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "Jackie Brown" }); 84 | 85 | migrationBuilder.InsertData( 86 | table: "Movies", 87 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 88 | values: new object[] { new Guid("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), "Comedy, Crime", new DateTimeOffset(new DateTime(1998, 3, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "The Big Lebowski" }); 89 | 90 | migrationBuilder.InsertData( 91 | table: "Movies", 92 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 93 | values: new object[] { new Guid("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), "Crime, Drama", new DateTimeOffset(new DateTime(1995, 11, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "Casino" }); 94 | 95 | migrationBuilder.InsertData( 96 | table: "Movies", 97 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 98 | values: new object[] { new Guid("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), "Drama", new DateTimeOffset(new DateTime(1999, 10, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), "Fight Club" }); 99 | 100 | migrationBuilder.InsertData( 101 | table: "Movies", 102 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 103 | values: new object[] { new Guid("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), "Crime, Thriller", new DateTimeOffset(new DateTime(1995, 9, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), "The Usual Suspects" }); 104 | 105 | migrationBuilder.InsertData( 106 | table: "Movies", 107 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 108 | values: new object[] { new Guid("26fcbcc4-b7f7-47fc-9382-740c12246b59"), "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), "Action, Sci-Fi", new DateTimeOffset(new DateTime(1991, 7, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), "Terminator 2: Judgment Day" }); 109 | 110 | migrationBuilder.CreateIndex( 111 | name: "IX_Movies_DirectorId", 112 | table: "Movies", 113 | column: "DirectorId"); 114 | } 115 | 116 | protected override void Down(MigrationBuilder migrationBuilder) 117 | { 118 | migrationBuilder.DropTable( 119 | name: "Movies"); 120 | 121 | migrationBuilder.DropTable( 122 | name: "Directors"); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Migrations/MoviesContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using Movies.API.Contexts; 7 | 8 | namespace Movies.API.Migrations 9 | { 10 | [DbContext(typeof(MoviesContext))] 11 | partial class MoviesContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "5.0.4"); 18 | 19 | modelBuilder.Entity("Movies.API.Entities.Director", b => 20 | { 21 | b.Property("Id") 22 | .ValueGeneratedOnAdd() 23 | .HasColumnType("TEXT"); 24 | 25 | b.Property("FirstName") 26 | .IsRequired() 27 | .HasMaxLength(200) 28 | .HasColumnType("TEXT"); 29 | 30 | b.Property("LastName") 31 | .IsRequired() 32 | .HasMaxLength(200) 33 | .HasColumnType("TEXT"); 34 | 35 | b.HasKey("Id"); 36 | 37 | b.ToTable("Directors"); 38 | 39 | b.HasData( 40 | new 41 | { 42 | Id = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 43 | FirstName = "Quentin", 44 | LastName = "Tarantino" 45 | }, 46 | new 47 | { 48 | Id = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 49 | FirstName = "Joel", 50 | LastName = "Coen" 51 | }, 52 | new 53 | { 54 | Id = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 55 | FirstName = "Martin", 56 | LastName = "Scorsese" 57 | }, 58 | new 59 | { 60 | Id = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 61 | FirstName = "David", 62 | LastName = "Fincher" 63 | }, 64 | new 65 | { 66 | Id = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 67 | FirstName = "Bryan", 68 | LastName = "Singer" 69 | }, 70 | new 71 | { 72 | Id = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 73 | FirstName = "James", 74 | LastName = "Cameron" 75 | }); 76 | }); 77 | 78 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 79 | { 80 | b.Property("Id") 81 | .ValueGeneratedOnAdd() 82 | .HasColumnType("TEXT"); 83 | 84 | b.Property("Description") 85 | .HasMaxLength(2000) 86 | .HasColumnType("TEXT"); 87 | 88 | b.Property("DirectorId") 89 | .HasColumnType("TEXT"); 90 | 91 | b.Property("Genre") 92 | .HasMaxLength(200) 93 | .HasColumnType("TEXT"); 94 | 95 | b.Property("ReleaseDate") 96 | .HasColumnType("TEXT"); 97 | 98 | b.Property("Title") 99 | .IsRequired() 100 | .HasMaxLength(200) 101 | .HasColumnType("TEXT"); 102 | 103 | b.HasKey("Id"); 104 | 105 | b.HasIndex("DirectorId"); 106 | 107 | b.ToTable("Movies"); 108 | 109 | b.HasData( 110 | new 111 | { 112 | Id = new Guid("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), 113 | Description = "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", 114 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 115 | Genre = "Crime, Drama", 116 | ReleaseDate = new DateTimeOffset(new DateTime(1994, 11, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 117 | Title = "Pulp Fiction" 118 | }, 119 | new 120 | { 121 | Id = new Guid("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), 122 | Description = "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", 123 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 124 | Genre = "Crime, Drama", 125 | ReleaseDate = new DateTimeOffset(new DateTime(1997, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 126 | Title = "Jackie Brown" 127 | }, 128 | new 129 | { 130 | Id = new Guid("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), 131 | Description = "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", 132 | DirectorId = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 133 | Genre = "Comedy, Crime", 134 | ReleaseDate = new DateTimeOffset(new DateTime(1998, 3, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 135 | Title = "The Big Lebowski" 136 | }, 137 | new 138 | { 139 | Id = new Guid("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), 140 | Description = "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", 141 | DirectorId = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 142 | Genre = "Crime, Drama", 143 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 11, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 144 | Title = "Casino" 145 | }, 146 | new 147 | { 148 | Id = new Guid("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), 149 | Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", 150 | DirectorId = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 151 | Genre = "Drama", 152 | ReleaseDate = new DateTimeOffset(new DateTime(1999, 10, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 153 | Title = "Fight Club" 154 | }, 155 | new 156 | { 157 | Id = new Guid("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), 158 | Description = "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", 159 | DirectorId = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 160 | Genre = "Crime, Thriller", 161 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 9, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 162 | Title = "The Usual Suspects" 163 | }, 164 | new 165 | { 166 | Id = new Guid("26fcbcc4-b7f7-47fc-9382-740c12246b59"), 167 | Description = "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", 168 | DirectorId = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 169 | Genre = "Action, Sci-Fi", 170 | ReleaseDate = new DateTimeOffset(new DateTime(1991, 7, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 171 | Title = "Terminator 2: Judgment Day" 172 | }); 173 | }); 174 | 175 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 176 | { 177 | b.HasOne("Movies.API.Entities.Director", "Director") 178 | .WithMany() 179 | .HasForeignKey("DirectorId") 180 | .OnDelete(DeleteBehavior.Cascade) 181 | .IsRequired(); 182 | 183 | b.Navigation("Director"); 184 | }); 185 | #pragma warning restore 612, 618 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/Movie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace Movies.API.Models 5 | { 6 | public class Movie 7 | { 8 | public Guid Id { get; set; } 9 | public string Title { get; set; } 10 | public string Description { get; set; } 11 | public string Genre { get; set; } 12 | public DateTimeOffset ReleaseDate { get; set; } 13 | public string Director { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/MovieForCreation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class MovieForCreation 9 | { 10 | [Required] 11 | [MaxLength(200)] 12 | public string Title { get; set; } 13 | 14 | [MaxLength(2000)] 15 | [MinLength(10)] 16 | public string Description { get; set; } 17 | 18 | [MaxLength(200)] 19 | public string Genre { get; set; } 20 | 21 | [Required] 22 | public DateTimeOffset? ReleaseDate { get; set; } 23 | 24 | [Required] 25 | public Guid? DirectorId { get; set; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/MovieForUpdate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class MovieForUpdate 9 | { 10 | [Required] 11 | [MaxLength(200)] 12 | public string Title { get; set; } 13 | 14 | [MaxLength(2000)] 15 | public string Description { get; set; } 16 | 17 | [MaxLength(200)] 18 | public string Genre { get; set; } 19 | 20 | [Required] 21 | public DateTimeOffset ReleaseDate { get; set; } 22 | 23 | [Required] 24 | public Guid DirectorId { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/Poster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Movies.API.Models 6 | { 7 | public class Poster 8 | { 9 | public Guid Id { get; set; } 10 | public Guid MovieId { get; set; } 11 | public string Name { get; set; } 12 | public byte[] Bytes { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/PosterForCreation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class PosterForCreation 9 | { 10 | [Required] 11 | [MaxLength(200)] 12 | public string Name { get; set; } 13 | 14 | [Required] 15 | public byte[] Bytes { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/Trailer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Movies.API.Models 6 | { 7 | public class Trailer 8 | { 9 | public Guid Id { get; set; } 10 | public Guid MovieId { get; set; } 11 | public string Name { get; set; } 12 | public string Description { get; set; } 13 | public byte[] Bytes { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Models/TrailerForCreation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class TrailerForCreation 9 | { 10 | [Required] 11 | public Guid MovieId { get; set; } 12 | 13 | [Required] 14 | [MaxLength(200)] 15 | public string Name { get; set; } 16 | 17 | [MaxLength(1000)] 18 | public string Description { get; set; } 19 | 20 | [Required] 21 | public byte[] Bytes { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Movies.API.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 9.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Movies.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KevinDockx/UsingHttpClientInDotNet/75cb69ea14621cf221bbee885064c781f03d311c/Finished sample/Movies.API/Movies.db -------------------------------------------------------------------------------- /Finished sample/Movies.API/Profiles/MoviesProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System.Collections.Generic; 3 | 4 | namespace Movies.API 5 | { 6 | /// 7 | /// AutoMapper profile for working with Movie objects 8 | /// 9 | public class MoviesProfile : Profile 10 | { 11 | public MoviesProfile() 12 | { 13 | CreateMap() 14 | .ForMember(dest => dest.Director, opt => opt.MapFrom(src => 15 | $"{src.Director.FirstName} {src.Director.LastName}")); 16 | 17 | CreateMap(); 18 | 19 | CreateMap().ReverseMap(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Profiles/PostersProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace Movies.API.Profiles 4 | { 5 | /// 6 | /// AutoMapper profile for working with Poster objects 7 | /// 8 | public class PostersProfile : Profile 9 | { 10 | public PostersProfile() 11 | { 12 | CreateMap(); 13 | CreateMap(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Profiles/TrailersProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace Movies.API.Profiles 4 | { 5 | /// 6 | /// AutoMapper profile for working with Trailer objects 7 | /// 8 | public class TrailersProfile : Profile 9 | { 10 | public TrailersProfile() 11 | { 12 | CreateMap(); 13 | CreateMap(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using Movies.API.Contexts; 13 | 14 | namespace Movies.API 15 | { 16 | public class Program 17 | { 18 | public static void Main(string[] args) 19 | { 20 | var host = CreateWebHostBuilder(args).Build(); 21 | 22 | // For demo purposes: clear the database 23 | // and refill it with dummy data 24 | using (var scope = host.Services.CreateScope()) 25 | { 26 | try 27 | { 28 | var context = scope.ServiceProvider.GetService(); 29 | // delete the DB if it exists 30 | context.Database.EnsureDeleted(); 31 | // migrate the DB - this will also seed the DB with dummy data 32 | context.Database.Migrate(); 33 | } 34 | catch (Exception ex) 35 | { 36 | var logger = scope.ServiceProvider.GetRequiredService>(); 37 | logger.LogError(ex, "An error occurred while migrating the database."); 38 | } 39 | } 40 | 41 | // run the web app 42 | host.Run(); 43 | } 44 | 45 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 46 | WebHost.CreateDefaultBuilder(args) 47 | .UseStartup(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:57863", 7 | "sslPort": 0 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchUrl": "http://localhost:57863", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Movies.API": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "api/values", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | }, 26 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Finished sample/Movies.API/Services/IMoviesRepository.cs: -------------------------------------------------------------------------------- 1 | using Movies.API.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.Services 8 | { 9 | public interface IMoviesRepository 10 | { 11 | Task GetMovieAsync(Guid movieId); 12 | 13 | Task> GetMoviesAsync(); 14 | 15 | void UpdateMovie(Movie movieToUpdate); 16 | 17 | void AddMovie(Movie movieToAdd); 18 | 19 | void DeleteMovie(Movie movieToDelete); 20 | 21 | Task SaveChangesAsync(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Services/IPostersRepository.cs: -------------------------------------------------------------------------------- 1 | using Movies.API.InternalModels; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.Services 8 | { 9 | public interface IPostersRepository 10 | { 11 | Task GetPosterAsync(Guid movieId, Guid posterId); 12 | 13 | Task AddPoster(Guid movieId, Poster posterToAdd); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Services/ITrailersRepository.cs: -------------------------------------------------------------------------------- 1 | using Movies.API.InternalModels; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.Services 8 | { 9 | public interface ITrailersRepository 10 | { 11 | Task GetTrailerAsync(Guid movieId, Guid trailerId); 12 | 13 | Task AddTrailer(Guid movieId, Trailer trailerToAdd); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Services/MoviesRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Movies.API.Contexts; 3 | using Movies.API.Entities; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.API.Services 10 | { 11 | public class MoviesRepository : IMoviesRepository, IDisposable 12 | { 13 | private MoviesContext _context; 14 | 15 | public MoviesRepository(MoviesContext context) 16 | { 17 | _context = context ?? throw new ArgumentNullException(nameof(context)); 18 | } 19 | 20 | public async Task GetMovieAsync(Guid movieId) 21 | { 22 | return await _context.Movies.Include(m => m.Director) 23 | .FirstOrDefaultAsync(m => m.Id == movieId); 24 | } 25 | 26 | public async Task> GetMoviesAsync() 27 | { 28 | return await _context.Movies.Include(m => m.Director).ToListAsync(); 29 | } 30 | 31 | public void UpdateMovie(Movie movieToUpdate) 32 | { 33 | // no code required, entity tracked by context. Including 34 | // this is best practice to ensure other implementations of the 35 | // contract (eg a mock version) can execute code on update 36 | // when needed. 37 | } 38 | 39 | public void AddMovie(Movie movieToAdd) 40 | { 41 | if (movieToAdd == null) 42 | { 43 | throw new ArgumentNullException(nameof(movieToAdd)); 44 | } 45 | 46 | _context.Add(movieToAdd); 47 | } 48 | 49 | public void DeleteMovie(Movie movieToDelete) 50 | { 51 | if (movieToDelete == null) 52 | { 53 | throw new ArgumentNullException(nameof(movieToDelete)); 54 | } 55 | 56 | _context.Remove(movieToDelete); 57 | } 58 | 59 | public async Task SaveChangesAsync() 60 | { 61 | // return true if 1 or more entities were changed 62 | return (await _context.SaveChangesAsync() > 0); 63 | } 64 | 65 | public void Dispose() 66 | { 67 | Dispose(true); 68 | GC.SuppressFinalize(this); 69 | } 70 | 71 | protected virtual void Dispose(bool disposing) 72 | { 73 | if (disposing) 74 | { 75 | if (_context != null) 76 | { 77 | _context.Dispose(); 78 | _context = null; 79 | } 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Services/PostersRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Movies.API.Contexts; 7 | using Movies.API.InternalModels; 8 | 9 | namespace Movies.API.Services 10 | { 11 | public class PostersRepository : IPostersRepository, IDisposable 12 | { 13 | private MoviesContext _context; 14 | 15 | public PostersRepository(MoviesContext context) 16 | { 17 | _context = context ?? throw new ArgumentNullException(nameof(context)); 18 | 19 | } 20 | 21 | public async Task GetPosterAsync(Guid movieId, Guid posterId) 22 | { 23 | // Generate the name from the movie title. 24 | var movie = await _context.Movies 25 | .FirstOrDefaultAsync(m => m.Id == movieId); 26 | 27 | if (movie == null) 28 | { 29 | throw new Exception($"Movie with id {movieId} not found."); 30 | } 31 | 32 | // generate a movie poster of 500KB 33 | var random = new Random(); 34 | var generatedBytes = new byte[524288]; 35 | random.NextBytes(generatedBytes); 36 | 37 | return new Poster() 38 | { 39 | Bytes = generatedBytes, 40 | Id = posterId, 41 | MovieId = movieId, 42 | Name = $"{movie.Title} poster number {DateTime.UtcNow.Ticks}" 43 | }; 44 | } 45 | 46 | public async Task AddPoster(Guid movieId, Poster posterToAdd) 47 | { 48 | // don't do anything: we're just faking this. Simply return the poster 49 | // after setting the ids 50 | posterToAdd.MovieId = movieId; 51 | posterToAdd.Id = Guid.NewGuid(); 52 | return await Task.FromResult(posterToAdd); 53 | } 54 | 55 | public void Dispose() 56 | { 57 | Dispose(true); 58 | GC.SuppressFinalize(this); 59 | } 60 | 61 | 62 | protected virtual void Dispose(bool disposing) 63 | { 64 | if (disposing) 65 | { 66 | if (_context != null) 67 | { 68 | _context.Dispose(); 69 | _context = null; 70 | } 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Services/TrailersRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Movies.API.Contexts; 7 | using Movies.API.InternalModels; 8 | 9 | namespace Movies.API.Services 10 | { 11 | public class TrailersRepository : ITrailersRepository, IDisposable 12 | { 13 | private MoviesContext _context; 14 | 15 | public TrailersRepository(MoviesContext context) 16 | { 17 | _context = context ?? throw new ArgumentNullException(nameof(context)); 18 | 19 | } 20 | 21 | public async Task GetTrailerAsync(Guid movieId, Guid trailerId) 22 | { 23 | // Generate the name from the movie title. 24 | var movie = await _context.Movies 25 | .FirstOrDefaultAsync(m => m.Id == movieId); 26 | 27 | if (movie == null) 28 | { 29 | throw new Exception($"Movie with id {movieId} not found."); 30 | } 31 | 32 | // generate a trailer (byte array) between 50 and 100MB 33 | var random = new Random(); 34 | var generatedByteLength = random.Next(52428800, 104857600); 35 | var generatedBytes = new byte[generatedByteLength]; 36 | random.NextBytes(generatedBytes); 37 | 38 | return new Trailer() 39 | { 40 | Bytes = generatedBytes, 41 | Id = trailerId, 42 | MovieId = movieId, 43 | Name = $"{movie.Title} trailer number {DateTime.UtcNow.Ticks}", 44 | Description = $"{movie.Title} trailer description {DateTime.UtcNow.Ticks}" 45 | }; 46 | } 47 | 48 | public async Task AddTrailer(Guid movieId, Trailer trailerToAdd) 49 | { 50 | // don't do anything: we're just faking this. Simply return the trailer 51 | // after setting the ids 52 | trailerToAdd.MovieId = movieId; 53 | trailerToAdd.Id = Guid.NewGuid(); 54 | return await Task.FromResult(trailerToAdd); 55 | } 56 | 57 | public void Dispose() 58 | { 59 | Dispose(true); 60 | GC.SuppressFinalize(this); 61 | } 62 | 63 | protected virtual void Dispose(bool disposing) 64 | { 65 | if (disposing) 66 | { 67 | if (_context != null) 68 | { 69 | _context.Dispose(); 70 | _context = null; 71 | } 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/Startup.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.AspNetCore.Mvc.Formatters; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Hosting; 10 | using Microsoft.OpenApi.Models; 11 | using Movies.API.Contexts; 12 | using Movies.API.Services; 13 | using Newtonsoft.Json.Serialization; 14 | using Swashbuckle.AspNetCore.Swagger; 15 | using System; 16 | 17 | namespace Movies.API 18 | { 19 | public class Startup 20 | { 21 | public Startup(IConfiguration configuration) 22 | { 23 | Configuration = configuration; 24 | } 25 | 26 | public IConfiguration Configuration { get; } 27 | 28 | // This method gets called by the runtime. Use this method to add services to the container. 29 | public void ConfigureServices(IServiceCollection services) 30 | { 31 | services.AddControllers(options => 32 | { 33 | // Return a 406 when an unsupported media type was requested 34 | options.ReturnHttpNotAcceptable = true; 35 | 36 | // Add XML formatters 37 | //options.OutputFormatters.Add(new XmlSerializerOutputFormatter()); 38 | //options.InputFormatters.Add(new XmlSerializerInputFormatter(options)); 39 | 40 | // Set XML as default format instead of JSON - the first formatter in the 41 | // list is the default, so we insert the input/output formatters at 42 | // position 0 43 | //options.OutputFormatters.Insert(0, new XmlSerializerOutputFormatter()); 44 | //options.InputFormatters.Insert(0, new XmlSerializerInputFormatter(options)); 45 | }).AddNewtonsoftJson(setupAction => 46 | { 47 | setupAction.SerializerSettings.ContractResolver = 48 | new CamelCasePropertyNamesContractResolver(); 49 | }); 50 | 51 | // add support for compressing responses (eg gzip) 52 | services.AddResponseCompression(); 53 | 54 | // suppress automatic model state validation when using the 55 | // ApiController attribute (as it will return a 400 Bad Request 56 | // instead of the more correct 422 Unprocessable Entity when 57 | // validation errors are encountered) 58 | services.Configure(options => 59 | { 60 | options.SuppressModelStateInvalidFilter = true; 61 | }); 62 | 63 | // register the DbContext on the container, getting the connection string from 64 | // appSettings (note: use this during development; in a production environment, 65 | // it's better to store the connection string in an environment variable) 66 | var connectionString = Configuration["ConnectionStrings:MoviesDBConnectionString"]; 67 | services.AddDbContext(o => o.UseSqlite(connectionString)); 68 | 69 | services.AddScoped(); 70 | services.AddScoped(); 71 | services.AddScoped(); 72 | 73 | services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); 74 | 75 | services.AddSwaggerGen(c => 76 | { 77 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "Movies API", Version = "v1" }); 78 | }); 79 | } 80 | 81 | 82 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 83 | { 84 | if (env.IsDevelopment()) 85 | { 86 | app.UseDeveloperExceptionPage(); 87 | } 88 | 89 | // use response compression (client should pass through 90 | // Accept-Encoding) 91 | app.UseResponseCompression(); 92 | 93 | // Enable middleware to serve generated Swagger as a JSON endpoint. 94 | app.UseSwagger(); 95 | 96 | // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 97 | // specifying the Swagger JSON endpoint. 98 | app.UseSwaggerUI(c => 99 | { 100 | c.SwaggerEndpoint("swagger/v1/swagger.json", "Movies API (v1)"); 101 | // serve UI at root 102 | c.RoutePrefix = string.Empty; 103 | }); 104 | 105 | app.UseRouting(); 106 | 107 | app.UseAuthorization(); 108 | 109 | app.UseEndpoints(endpoints => 110 | { 111 | endpoints.MapControllers(); 112 | }); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Finished sample/Movies.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information" 5 | } 6 | }, 7 | "AllowedHosts": "*", 8 | "ConnectionStrings": { 9 | "MoviesDBConnectionString": "Data Source=Movies.db;" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Movies.Client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 9.0 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | all 25 | runtime; build; native; contentfiles; analyzers; buildtransitive 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/MoviesClient.cs: -------------------------------------------------------------------------------- 1 | using Marvin.StreamExtensions; 2 | using Movies.Client.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | namespace Movies.Client 13 | { 14 | public class MoviesClient 15 | { 16 | public MoviesClient(HttpClient client) 17 | { 18 | _client = client; 19 | _client.BaseAddress = new Uri("http://localhost:57863"); 20 | _client.Timeout = new TimeSpan(0, 0, 30); 21 | _client.DefaultRequestHeaders.Clear(); 22 | } 23 | 24 | private HttpClient _client; 25 | 26 | public async Task> GetMovies(CancellationToken cancellationToken) 27 | { 28 | var request = new HttpRequestMessage( 29 | HttpMethod.Get, 30 | "api/movies"); 31 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 32 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 33 | 34 | using (var response = await _client.SendAsync(request, 35 | HttpCompletionOption.ResponseHeadersRead, 36 | cancellationToken)) 37 | { 38 | var stream = await response.Content.ReadAsStreamAsync(); 39 | response.EnsureSuccessStatusCode(); 40 | return stream.ReadAndDeserializeFromJson>(); 41 | } 42 | } 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using Movies.Client.Services; 5 | using System; 6 | using System.Net.Http; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.Client 10 | { 11 | class Program 12 | { 13 | static async Task Main(string[] args) 14 | { 15 | 16 | using IHost host = CreateHostBuilder(args).Build(); 17 | var serviceProvider = host.Services; 18 | 19 | // For demo purposes: overall catch-all to log any exception that might 20 | // happen to the console & wait for key input afterwards so we can easily 21 | // inspect the issue. 22 | try 23 | { 24 | var logger = host.Services.GetRequiredService>(); 25 | logger.LogInformation("Host created."); 26 | 27 | // Run our IntegrationService containing all samples and 28 | // await this call to ensure the application doesn't 29 | // prematurely exit. 30 | await serviceProvider.GetService().Run(); 31 | } 32 | catch (Exception generalException) 33 | { 34 | // log the exception 35 | var logger = serviceProvider.GetService>(); 36 | logger.LogError(generalException, 37 | "An exception happened while running the integration service."); 38 | } 39 | 40 | Console.ReadKey(); 41 | 42 | await host.RunAsync(); 43 | } 44 | 45 | private static IHostBuilder CreateHostBuilder(string[] args) 46 | { 47 | return Host.CreateDefaultBuilder(args).ConfigureServices( 48 | (serviceCollection) => ConfigureServices(serviceCollection)); 49 | } 50 | 51 | private static void ConfigureServices(IServiceCollection serviceCollection) 52 | { 53 | // add loggers 54 | serviceCollection.AddLogging(configure => configure.AddDebug().AddConsole()); 55 | 56 | serviceCollection.AddHttpClient("MoviesClient", client => 57 | { 58 | client.BaseAddress = new Uri("http://localhost:57863"); 59 | client.Timeout = new TimeSpan(0, 0, 30); 60 | client.DefaultRequestHeaders.Clear(); 61 | }).AddHttpMessageHandler(handler => 62 | new TimeOutDelegatingHandler(TimeSpan.FromSeconds(20))) 63 | .AddHttpMessageHandler(handler => 64 | new RetryPolicyDelegatingHandler(2)) 65 | .ConfigurePrimaryHttpMessageHandler(handler => 66 | new HttpClientHandler() 67 | { 68 | AutomaticDecompression = System.Net.DecompressionMethods.GZip 69 | }); 70 | 71 | //serviceCollection.AddHttpClient(client => 72 | //{ 73 | // client.BaseAddress = new Uri("http://localhost:57863"); 74 | // client.Timeout = new TimeSpan(0, 0, 30); 75 | // client.DefaultRequestHeaders.Clear(); 76 | //} 77 | //).ConfigurePrimaryHttpMessageHandler(handler => 78 | //new HttpClientHandler() 79 | //{ 80 | // AutomaticDecompression = System.Net.DecompressionMethods.GZip 81 | //}); 82 | 83 | serviceCollection.AddHttpClient() 84 | .ConfigurePrimaryHttpMessageHandler(handler => 85 | new HttpClientHandler() 86 | { 87 | AutomaticDecompression = System.Net.DecompressionMethods.GZip 88 | }); 89 | 90 | 91 | // register the integration service on our container with a 92 | // scoped lifetime 93 | 94 | // For the CRUD demos 95 | // serviceCollection.AddScoped(); 96 | 97 | // For the partial update demos 98 | // serviceCollection.AddScoped(); 99 | 100 | // For the stream demos 101 | // serviceCollection.AddScoped(); 102 | 103 | // For the cancellation demos 104 | // serviceCollection.AddScoped(); 105 | 106 | // For the HttpClientFactory demos 107 | // serviceCollection.AddScoped(); 108 | 109 | // For the dealing with errors and faults demos 110 | // serviceCollection.AddScoped(); 111 | 112 | // For the custom http handlers demos 113 | serviceCollection.AddScoped(); 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/RetryPolicyDelegatingHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.Client 10 | { 11 | public class RetryPolicyDelegatingHandler : DelegatingHandler 12 | { 13 | private readonly int _maximumAmountOfRetries = 3; 14 | 15 | public RetryPolicyDelegatingHandler(int maximumAmountOfRetries) 16 | : base() 17 | { 18 | _maximumAmountOfRetries = maximumAmountOfRetries; 19 | } 20 | public RetryPolicyDelegatingHandler(HttpMessageHandler innerHandler, 21 | int maximumAmountOfRetries) 22 | : base(innerHandler) 23 | { 24 | _maximumAmountOfRetries = maximumAmountOfRetries; 25 | } 26 | 27 | protected override async Task SendAsync( 28 | HttpRequestMessage request, CancellationToken cancellationToken) 29 | { 30 | HttpResponseMessage response = null; 31 | for (int i = 0; i < _maximumAmountOfRetries; i++) 32 | { 33 | response = await base.SendAsync(request, cancellationToken); 34 | 35 | if (response.IsSuccessStatusCode) 36 | { 37 | return response; 38 | } 39 | } 40 | return response; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Return401UnauthorizedResponseHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.Client 10 | { 11 | public class Return401UnauthorizedResponseHandler : HttpMessageHandler 12 | { 13 | protected override Task SendAsync( 14 | HttpRequestMessage request, CancellationToken cancellationToken) 15 | { 16 | var response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 17 | return Task.FromResult(response); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/CRUDService.cs: -------------------------------------------------------------------------------- 1 | using Movies.Client.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | using System.Net.Http.Headers; 9 | using System.Xml.Serialization; 10 | using System.IO; 11 | 12 | namespace Movies.Client.Services 13 | { 14 | public class CRUDService : IIntegrationService 15 | { 16 | private static HttpClient _httpClient = new HttpClient(); 17 | 18 | public CRUDService() 19 | { 20 | _httpClient.BaseAddress = new Uri("http://localhost:57863"); 21 | _httpClient.Timeout = new TimeSpan(0, 0, 30); 22 | _httpClient.DefaultRequestHeaders.Clear(); 23 | //_httpClient.DefaultRequestHeaders.Accept.Add( 24 | // new MediaTypeWithQualityHeaderValue("application/json")); 25 | //_httpClient.DefaultRequestHeaders.Accept.Add( 26 | // new MediaTypeWithQualityHeaderValue("application/xml", 0.9)); 27 | } 28 | 29 | public async Task Run() 30 | { 31 | //await GetResource(); 32 | //await GetResourceThroughHttpRequestMessage(); 33 | //await CreateResource(); 34 | //await UpdateResource(); 35 | await DeleteResource(); 36 | } 37 | 38 | public async Task GetResource() 39 | { 40 | var response = await _httpClient.GetAsync("api/movies"); 41 | response.EnsureSuccessStatusCode(); 42 | 43 | var movies = new List(); 44 | var content = await response.Content.ReadAsStringAsync(); 45 | if (response.Content.Headers.ContentType.MediaType == "application/json") 46 | { 47 | movies = JsonSerializer.Deserialize>(content, 48 | new JsonSerializerOptions() 49 | { 50 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 51 | }); 52 | } 53 | else if (response.Content.Headers.ContentType.MediaType == "application/xml") 54 | { 55 | var serializer = new XmlSerializer(typeof(List)); 56 | movies = (List)serializer.Deserialize(new StringReader(content)); 57 | } 58 | 59 | // do something with the movies list 60 | } 61 | 62 | public async Task GetResourceThroughHttpRequestMessage() 63 | { 64 | var request = new HttpRequestMessage(HttpMethod.Get, "api/movies"); 65 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 66 | 67 | var response = await _httpClient.SendAsync(request); 68 | response.EnsureSuccessStatusCode(); 69 | 70 | var content = await response.Content.ReadAsStringAsync(); 71 | 72 | var movies = JsonSerializer.Deserialize>(content, 73 | new JsonSerializerOptions 74 | { 75 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 76 | }); 77 | } 78 | 79 | public async Task CreateResource() 80 | { 81 | var movieToCreate = new MovieForCreation() 82 | { 83 | Title = "Reservoir Dogs", 84 | Description = "After a simple jewelry heist goes terribly wrong, the " + 85 | "surviving criminals begin to suspect that one of them is a police informant.", 86 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 87 | ReleaseDate = new DateTimeOffset(new DateTime(1992, 9, 2)), 88 | Genre = "Crime, Drama" 89 | }; 90 | 91 | var serializedMovieToCreate = JsonSerializer.Serialize(movieToCreate); 92 | 93 | var request = new HttpRequestMessage(HttpMethod.Post, "api/movies"); 94 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 95 | 96 | request.Content = new StringContent(serializedMovieToCreate); 97 | request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 98 | 99 | var response = await _httpClient.SendAsync(request); 100 | response.EnsureSuccessStatusCode(); 101 | 102 | var content = await response.Content.ReadAsStringAsync(); 103 | 104 | var createdMovie = JsonSerializer.Deserialize(content, 105 | new JsonSerializerOptions 106 | { 107 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 108 | }); 109 | } 110 | 111 | public async Task UpdateResource() 112 | { 113 | var movieToUpdate = new MovieForUpdate() 114 | { 115 | Title = "Pulp Fiction", 116 | Description = "The movie with Zed.", 117 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 118 | ReleaseDate = new DateTimeOffset(new DateTime(1992, 9, 2)), 119 | Genre = "Crime, Drama" 120 | }; 121 | 122 | var serializedMovieToUpdate = JsonSerializer.Serialize(movieToUpdate); 123 | 124 | var request = new HttpRequestMessage( 125 | HttpMethod.Put, "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"); 126 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 127 | request.Content = new StringContent(serializedMovieToUpdate); 128 | request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 129 | 130 | var response = await _httpClient.SendAsync(request); 131 | response.EnsureSuccessStatusCode(); 132 | 133 | var content = await response.Content.ReadAsStringAsync(); 134 | var updatedMovie = JsonSerializer.Deserialize(content, 135 | new JsonSerializerOptions 136 | { 137 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 138 | }); 139 | } 140 | 141 | public async Task DeleteResource() 142 | { 143 | var request = new HttpRequestMessage(HttpMethod.Delete, 144 | "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"); 145 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 146 | 147 | var response = await _httpClient.SendAsync(request); 148 | response.EnsureSuccessStatusCode(); 149 | 150 | var content = await response.Content.ReadAsStringAsync(); 151 | } 152 | 153 | private async Task PostResourceShortcut() 154 | { 155 | var movieToCreate = new MovieForCreation() 156 | { 157 | Title = "Reservoir Dogs", 158 | Description = "After a simple jewelry heist goes terribly wrong, the " + 159 | "surviving criminals begin to suspect that one of them is a police informant.", 160 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 161 | ReleaseDate = new DateTimeOffset(new DateTime(1992, 9, 2)), 162 | Genre = "Crime, Drama" 163 | }; 164 | 165 | var response = await _httpClient.PostAsync( 166 | "api/movies", 167 | new StringContent( 168 | JsonSerializer.Serialize(movieToCreate), 169 | Encoding.UTF8, 170 | "application/json")); 171 | 172 | response.EnsureSuccessStatusCode(); 173 | 174 | var content = await response.Content.ReadAsStringAsync(); 175 | var createdMovie = JsonSerializer.Deserialize(content, 176 | new JsonSerializerOptions 177 | { 178 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 179 | }); 180 | } 181 | 182 | private async Task PutResourceShortcut() 183 | { 184 | var movieToUpdate = new MovieForUpdate() 185 | { 186 | Title = "Pulp Fiction", 187 | Description = "The movie with Zed.", 188 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 189 | ReleaseDate = new DateTimeOffset(new DateTime(1992, 9, 2)), 190 | Genre = "Crime, Drama" 191 | }; 192 | 193 | var response = await _httpClient.PutAsync( 194 | "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b", 195 | new StringContent( 196 | JsonSerializer.Serialize(movieToUpdate), 197 | System.Text.Encoding.UTF8, 198 | "application/json")); 199 | 200 | response.EnsureSuccessStatusCode(); 201 | 202 | var content = await response.Content.ReadAsStringAsync(); 203 | var updatedMovie = JsonSerializer.Deserialize(content, 204 | new JsonSerializerOptions 205 | { 206 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase 207 | }); 208 | } 209 | 210 | private async Task DeleteResourceShortcut() 211 | { 212 | var response = await _httpClient.DeleteAsync( 213 | "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"); 214 | response.EnsureSuccessStatusCode(); 215 | 216 | var content = await response.Content.ReadAsStringAsync(); 217 | } 218 | 219 | } 220 | } -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/CancellationService.cs: -------------------------------------------------------------------------------- 1 | using Movies.Client.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Marvin.StreamExtensions; 9 | using System.Threading; 10 | 11 | namespace Movies.Client.Services 12 | { 13 | public class CancellationService : IIntegrationService 14 | { 15 | private static HttpClient _httpClient = new HttpClient( 16 | new HttpClientHandler() 17 | { 18 | AutomaticDecompression = System.Net.DecompressionMethods.GZip 19 | }); 20 | 21 | private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); 22 | 23 | public CancellationService() 24 | { 25 | // set up HttpClient instance 26 | _httpClient.BaseAddress = new Uri("http://localhost:57863"); 27 | _httpClient.Timeout = new TimeSpan(0, 0, 2); 28 | _httpClient.DefaultRequestHeaders.Clear(); 29 | } 30 | 31 | public async Task Run() 32 | { 33 | _cancellationTokenSource.CancelAfter(1000); 34 | // await GetTrailerAndCancel(_cancellationTokenSource.Token); 35 | await GetTrailerAndHandleTimeout(); 36 | } 37 | 38 | private async Task GetTrailerAndHandleTimeout() 39 | { 40 | var request = new HttpRequestMessage( 41 | HttpMethod.Get, 42 | $"api/movies/d8663e5e-7494-4f81-8739-6e0de1bea7ee/trailers/{Guid.NewGuid()}"); 43 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 44 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 45 | try 46 | { 47 | using (var response = await _httpClient.SendAsync(request, 48 | HttpCompletionOption.ResponseHeadersRead)) 49 | { 50 | var stream = await response.Content.ReadAsStreamAsync(); 51 | 52 | response.EnsureSuccessStatusCode(); 53 | var trailer = stream.ReadAndDeserializeFromJson(); 54 | } 55 | } 56 | catch (OperationCanceledException ocException) 57 | { 58 | Console.WriteLine($"An operation was cancelled with message {ocException.Message}."); 59 | // additional cleanup, ... 60 | } 61 | } 62 | 63 | private async Task GetTrailerAndCancel(CancellationToken cancellationToken) 64 | { 65 | var request = new HttpRequestMessage( 66 | HttpMethod.Get, 67 | $"api/movies/d8663e5e-7494-4f81-8739-6e0de1bea7ee/trailers/{Guid.NewGuid()}"); 68 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 69 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 70 | 71 | try 72 | { 73 | using (var response = await _httpClient.SendAsync(request, 74 | HttpCompletionOption.ResponseHeadersRead, 75 | cancellationToken)) 76 | { 77 | var stream = await response.Content.ReadAsStreamAsync(); 78 | 79 | response.EnsureSuccessStatusCode(); 80 | var trailer = stream.ReadAndDeserializeFromJson(); 81 | } 82 | } 83 | catch (OperationCanceledException ocException) 84 | { 85 | Console.WriteLine($"An operation was cancelled with message {ocException.Message}."); 86 | // additional cleanup, ... 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/DealingWithErrorsAndFaultsService.cs: -------------------------------------------------------------------------------- 1 | using Marvin.StreamExtensions; 2 | using Movies.Client.Models; 3 | using Newtonsoft.Json; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | namespace Movies.Client.Services 13 | { 14 | public class DealingWithErrorsAndFaultsService : IIntegrationService 15 | { 16 | private readonly IHttpClientFactory _httpClientFactory; 17 | private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); 18 | 19 | public DealingWithErrorsAndFaultsService(IHttpClientFactory httpClientFactory, 20 | MoviesClient moviesClient) 21 | { 22 | _httpClientFactory = httpClientFactory; 23 | } 24 | 25 | public async Task Run() 26 | { 27 | // await GetMovieAndDealWithInvalidResponses(_cancellationTokenSource.Token); 28 | await PostMovieAndHandleValdationErrors(_cancellationTokenSource.Token); 29 | } 30 | 31 | private async Task PostMovieAndHandleValdationErrors( 32 | CancellationToken cancellationToken) 33 | { 34 | var httpClient = _httpClientFactory.CreateClient("MoviesClient"); 35 | 36 | var movieForCreation = new MovieForCreation() 37 | { 38 | Title = "Pulp Fiction" 39 | }; 40 | 41 | var serializedMovieForCreation = JsonConvert.SerializeObject(movieForCreation); 42 | 43 | using (var request = new HttpRequestMessage( 44 | HttpMethod.Post, 45 | "api/movies")) 46 | { 47 | request.Headers.Accept.Add( 48 | new MediaTypeWithQualityHeaderValue("application/json")); 49 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 50 | request.Content = new StringContent(serializedMovieForCreation); 51 | request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 52 | 53 | using (var response = await httpClient.SendAsync(request, 54 | HttpCompletionOption.ResponseHeadersRead, 55 | cancellationToken)) 56 | { 57 | var stream = await response.Content.ReadAsStreamAsync(); 58 | 59 | if (!response.IsSuccessStatusCode) 60 | { 61 | if (response.StatusCode == System.Net.HttpStatusCode.UnprocessableEntity) 62 | { 63 | // read out the response body and log it to the console window 64 | var validationErrors = stream.ReadAndDeserializeFromJson(); 65 | Console.WriteLine(validationErrors); 66 | return; 67 | } 68 | else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) 69 | { 70 | // trigger a login flow 71 | return; 72 | } 73 | response.EnsureSuccessStatusCode(); 74 | } 75 | 76 | var movie = stream.ReadAndDeserializeFromJson(); 77 | } 78 | } 79 | } 80 | 81 | 82 | private async Task GetMovieAndDealWithInvalidResponses(CancellationToken cancellationToken) 83 | { 84 | var httpClient = _httpClientFactory.CreateClient("MoviesClient"); 85 | 86 | var request = new HttpRequestMessage( 87 | HttpMethod.Get, 88 | "api/movies/030a43b0-f9a5-405a-811c-bf342524b2be"); 89 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 90 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 91 | 92 | using (var response = await httpClient.SendAsync(request, 93 | HttpCompletionOption.ResponseHeadersRead, 94 | cancellationToken)) 95 | { 96 | if (!response.IsSuccessStatusCode) 97 | { 98 | // inspect the status code 99 | if (response.StatusCode == System.Net.HttpStatusCode.NotFound) 100 | { 101 | // show this to the user 102 | Console.WriteLine("The requested movie cannot be found."); 103 | return; 104 | } 105 | else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) 106 | { 107 | // trigger a login flow 108 | return; 109 | } 110 | 111 | response.EnsureSuccessStatusCode(); 112 | } 113 | 114 | var stream = await response.Content.ReadAsStreamAsync(); 115 | 116 | var movie = stream.ReadAndDeserializeFromJson(); 117 | } 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/HttpClientFactoryInstanceManagementService.cs: -------------------------------------------------------------------------------- 1 | using Marvin.StreamExtensions; 2 | using Movies.Client.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net.Http; 6 | using System.Net.Http.Headers; 7 | using System.Text; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace Movies.Client.Services 12 | { 13 | public class HttpClientFactoryInstanceManagementService : IIntegrationService 14 | { 15 | private readonly CancellationTokenSource _cancellationTokenSource = 16 | new CancellationTokenSource(); 17 | private readonly IHttpClientFactory _httpClientFactory; 18 | private readonly MoviesClient _moviesClient; 19 | 20 | public HttpClientFactoryInstanceManagementService(IHttpClientFactory httpClientFactory, 21 | MoviesClient moviesClient) 22 | { 23 | _httpClientFactory = httpClientFactory 24 | ?? throw new ArgumentNullException(nameof(httpClientFactory)); 25 | _moviesClient = moviesClient 26 | ?? throw new ArgumentNullException(nameof(moviesClient)); 27 | } 28 | 29 | public async Task Run() 30 | { 31 | // await TestDisposeHttpClient(_cancellationTokenSource.Token); 32 | // await TestReuseHttpClient(_cancellationTokenSource.Token); 33 | // await GetMoviesWithHttpClientFromFactory(_cancellationTokenSource.Token); 34 | // await GetMoviesWithNamedHttpClientFromFactory(_cancellationTokenSource.Token); 35 | // await GetMoviesWithTypedHttpClientFromFactory(_cancellationTokenSource.Token); 36 | await GetMoviesViaMoviesClient(_cancellationTokenSource.Token); 37 | } 38 | 39 | private async Task GetMoviesViaMoviesClient(CancellationToken cancellationToken) 40 | { 41 | var movies = await _moviesClient.GetMovies(cancellationToken); 42 | } 43 | 44 | //private async Task GetMoviesWithTypedHttpClientFromFactory(CancellationToken cancellationToken) 45 | //{ 46 | // var request = new HttpRequestMessage( 47 | // HttpMethod.Get, 48 | // "api/movies"); 49 | // request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 50 | // request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 51 | 52 | // using (var response = await _moviesClient.Client.SendAsync(request, 53 | // HttpCompletionOption.ResponseHeadersRead, 54 | // cancellationToken)) 55 | // { 56 | // var stream = await response.Content.ReadAsStreamAsync(); 57 | // response.EnsureSuccessStatusCode(); 58 | // var movies = stream.ReadAndDeserializeFromJson>(); 59 | // } 60 | //} 61 | 62 | private async Task GetMoviesWithNamedHttpClientFromFactory(CancellationToken cancellationToken) 63 | { 64 | var httpClient = _httpClientFactory.CreateClient("MoviesClient"); 65 | 66 | var request = new HttpRequestMessage( 67 | HttpMethod.Get, 68 | "api/movies"); 69 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 70 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 71 | 72 | using (var response = await httpClient.SendAsync(request, 73 | HttpCompletionOption.ResponseHeadersRead, 74 | cancellationToken)) 75 | { 76 | var stream = await response.Content.ReadAsStreamAsync(); 77 | response.EnsureSuccessStatusCode(); 78 | var movies = stream.ReadAndDeserializeFromJson>(); 79 | } 80 | } 81 | 82 | private async Task GetMoviesWithHttpClientFromFactory(CancellationToken cancellationToken) 83 | { 84 | var httpClient = _httpClientFactory.CreateClient(); 85 | 86 | var request = new HttpRequestMessage( 87 | HttpMethod.Get, 88 | "http://localhost:57863/api/movies"); 89 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 90 | 91 | using (var response = await httpClient.SendAsync(request, 92 | HttpCompletionOption.ResponseHeadersRead, 93 | cancellationToken)) 94 | { 95 | var stream = await response.Content.ReadAsStreamAsync(); 96 | response.EnsureSuccessStatusCode(); 97 | var movies = stream.ReadAndDeserializeFromJson>(); 98 | } 99 | } 100 | 101 | private async Task TestDisposeHttpClient(CancellationToken cancellationToken) 102 | { 103 | for (var i = 0; i < 10; i++) 104 | { 105 | using (var httpClient = new HttpClient()) 106 | { 107 | var request = new HttpRequestMessage( 108 | HttpMethod.Get, 109 | "https://www.google.com"); 110 | 111 | using (var response = await httpClient.SendAsync(request, 112 | HttpCompletionOption.ResponseHeadersRead, 113 | cancellationToken)) 114 | { 115 | var stream = await response.Content.ReadAsStreamAsync(); 116 | response.EnsureSuccessStatusCode(); 117 | 118 | Console.WriteLine($"Request completed with status code {response.StatusCode}"); 119 | } 120 | } 121 | } 122 | } 123 | 124 | private async Task TestReuseHttpClient(CancellationToken cancellationToken) 125 | { 126 | var httpClient = new HttpClient(); 127 | 128 | for (int i = 0; i < 10; i++) 129 | { 130 | var request = new HttpRequestMessage( 131 | HttpMethod.Get, 132 | "https://www.google.com"); 133 | 134 | using (var response = await httpClient.SendAsync(request, 135 | HttpCompletionOption.ResponseHeadersRead, 136 | cancellationToken)) 137 | { 138 | var stream = await response.Content.ReadAsStreamAsync(); 139 | response.EnsureSuccessStatusCode(); 140 | 141 | Console.WriteLine($"Request completed with status code {response.StatusCode}"); 142 | } 143 | } 144 | } 145 | 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/HttpHandlersService.cs: -------------------------------------------------------------------------------- 1 | using Marvin.StreamExtensions; 2 | using Movies.Client.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net.Http; 6 | using System.Net.Http.Headers; 7 | using System.Text; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace Movies.Client.Services 12 | { 13 | public class HttpHandlersService : IIntegrationService 14 | { 15 | private static HttpClient _notSoNicelyInstantiatedHttpClient = 16 | new HttpClient( 17 | new RetryPolicyDelegatingHandler( 18 | new HttpClientHandler() 19 | { AutomaticDecompression = System.Net.DecompressionMethods.GZip }, 20 | 2)); 21 | 22 | 23 | private readonly IHttpClientFactory _httpClientFactory; 24 | private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); 25 | 26 | public HttpHandlersService(IHttpClientFactory httpClientFactory, 27 | MoviesClient moviesClient) 28 | { 29 | _httpClientFactory = httpClientFactory; 30 | } 31 | 32 | public async Task Run() 33 | { 34 | await GetMoviesWithRetryPolicy(_cancellationTokenSource.Token); 35 | } 36 | 37 | private async Task GetMoviesWithRetryPolicy(CancellationToken cancellationToken) 38 | { 39 | var httpClient = _httpClientFactory.CreateClient("MoviesClient"); 40 | 41 | //var request = new HttpRequestMessage( 42 | // HttpMethod.Get, 43 | // "api/movies/030a43b0-f9a5-405a-811c-bf342524b2be"); 44 | var request = new HttpRequestMessage( 45 | HttpMethod.Get, 46 | "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"); 47 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 48 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 49 | 50 | using (var response = await httpClient.SendAsync(request, 51 | HttpCompletionOption.ResponseHeadersRead, 52 | cancellationToken)) 53 | { 54 | var stream = await response.Content.ReadAsStreamAsync(); 55 | 56 | if (!response.IsSuccessStatusCode) 57 | { 58 | // inspect the status code 59 | if (response.StatusCode == System.Net.HttpStatusCode.NotFound) 60 | { 61 | // show this to the user 62 | Console.WriteLine("The requested movie cannot be found."); 63 | return; 64 | } 65 | response.EnsureSuccessStatusCode(); 66 | } 67 | var movie = stream.ReadAndDeserializeFromJson(); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/IIntegrationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public interface IIntegrationService 9 | { 10 | Task Run(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/Services/PartialUpdateService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.JsonPatch; 2 | using Movies.Client.Models; 3 | using Newtonsoft.Json; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace Movies.Client.Services 12 | { 13 | public class PartialUpdateService : IIntegrationService 14 | { 15 | private static HttpClient _httpClient = new HttpClient(); 16 | 17 | public PartialUpdateService() 18 | { 19 | // set up HttpClient instance 20 | _httpClient.BaseAddress = new Uri("http://localhost:57863"); 21 | _httpClient.Timeout = new TimeSpan(0, 0, 30); 22 | _httpClient.DefaultRequestHeaders.Clear(); 23 | } 24 | 25 | public async Task Run() 26 | { 27 | // await PatchResource(); 28 | await PatchResourceShortcut(); 29 | } 30 | 31 | public async Task PatchResource() 32 | { 33 | var patchDoc = new JsonPatchDocument(); 34 | patchDoc.Replace(m => m.Title, "Updated title"); 35 | patchDoc.Remove(m => m.Description); 36 | 37 | var serializedChangeSet = JsonConvert.SerializeObject(patchDoc); 38 | var request = new HttpRequestMessage(HttpMethod.Patch, 39 | "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"); 40 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 41 | request.Content = new StringContent(serializedChangeSet); 42 | request.Content.Headers.ContentType = 43 | new MediaTypeHeaderValue("application/json-patch+json"); 44 | 45 | var response = await _httpClient.SendAsync(request); 46 | response.EnsureSuccessStatusCode(); 47 | 48 | var content = await response.Content.ReadAsStringAsync(); 49 | var updatedMovie = JsonConvert.DeserializeObject(content); 50 | } 51 | 52 | public async Task PatchResourceShortcut() 53 | { 54 | var patchDoc = new JsonPatchDocument(); 55 | patchDoc.Replace(m => m.Title, "Updated title"); 56 | patchDoc.Remove(m => m.Description); 57 | 58 | var response = await _httpClient.PatchAsync( 59 | "api/movies/5b1c2b4d-48c7-402a-80c3-cc796ad49c6b", 60 | new StringContent( 61 | JsonConvert.SerializeObject(patchDoc), 62 | Encoding.UTF8, 63 | "application/json-patch+json")); 64 | 65 | response.EnsureSuccessStatusCode(); 66 | 67 | var content = await response.Content.ReadAsStringAsync(); 68 | var updatedMovie = JsonConvert.DeserializeObject(content); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Finished sample/Movies.Client/StreamExtensions.cs: -------------------------------------------------------------------------------- 1 | //using Newtonsoft.Json; 2 | //using System; 3 | //using System.Collections.Generic; 4 | //using System.IO; 5 | //using System.Linq; 6 | //using System.Text; 7 | //using System.Threading.Tasks; 8 | 9 | //namespace Movies.Client 10 | //{ 11 | // public static class StreamExtensions 12 | // { 13 | // public static T ReadAndDeserializeFromJson(this Stream stream) 14 | // { 15 | // if (stream == null) 16 | // { 17 | // throw new ArgumentNullException(nameof(stream)); 18 | // } 19 | 20 | // if (!stream.CanRead) 21 | // { 22 | // throw new NotSupportedException("Can't read from this stream."); 23 | // } 24 | 25 | // using (var streamReader = new StreamReader(stream)) 26 | // { 27 | // using (var jsonTextReader = new JsonTextReader(streamReader)) 28 | // { 29 | // var jsonSerializer = new JsonSerializer(); 30 | // return jsonSerializer.Deserialize(jsonTextReader); 31 | // } 32 | // } 33 | // } 34 | 35 | // public static void SerializeToJsonAndWrite(this Stream stream, T objectToWrite) 36 | // { 37 | // if (stream == null) 38 | // { 39 | // throw new ArgumentNullException(nameof(stream)); 40 | // } 41 | 42 | // if (!stream.CanWrite) 43 | // { 44 | // throw new NotSupportedException("Can't write to this stream."); 45 | // } 46 | 47 | // using (var streamWriter = new StreamWriter(stream, new UTF8Encoding(), 8192, true)) 48 | // { 49 | // using (var jsonTextWriter = new JsonTextWriter(streamWriter)) 50 | // { 51 | // var jsonSerializer = new JsonSerializer(); 52 | // jsonSerializer.Serialize(jsonTextWriter, objectToWrite); 53 | // jsonTextWriter.Flush(); 54 | // } 55 | // } 56 | // } 57 | 58 | 59 | // } 60 | //} 61 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/TestableClassWithApiAccess.cs: -------------------------------------------------------------------------------- 1 | using Marvin.StreamExtensions; 2 | using Movies.Client.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | namespace Movies.Client 13 | { 14 | public class TestableClassWithApiAccess 15 | { 16 | private readonly HttpClient _httpClient; 17 | 18 | public TestableClassWithApiAccess(HttpClient httpClient) 19 | { 20 | _httpClient = httpClient; 21 | } 22 | 23 | public async Task GetMovie(CancellationToken cancellationToken) 24 | { 25 | var request = new HttpRequestMessage( 26 | HttpMethod.Get, 27 | "api/movies/030a43b0-f9a5-405a-811c-bf342524b2be"); 28 | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 29 | request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); 30 | 31 | using (var response = await _httpClient.SendAsync(request, 32 | HttpCompletionOption.ResponseHeadersRead, 33 | cancellationToken)) 34 | { 35 | var stream = await response.Content.ReadAsStreamAsync(); 36 | 37 | if (!response.IsSuccessStatusCode) 38 | { 39 | // inspect the status code 40 | if (response.StatusCode == System.Net.HttpStatusCode.NotFound) 41 | { 42 | // show this to the user 43 | Console.WriteLine("The requested movie cannot be found."); 44 | return null; 45 | } 46 | else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) 47 | { 48 | // trigger a login flow 49 | throw new UnauthorizedApiAccessException(); 50 | } 51 | 52 | response.EnsureSuccessStatusCode(); 53 | } 54 | return stream.ReadAndDeserializeFromJson(); 55 | } 56 | } 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/TimeOutDelegatingHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.Client 10 | { 11 | public class TimeOutDelegatingHandler : DelegatingHandler 12 | { 13 | private readonly TimeSpan _timeOut = TimeSpan.FromSeconds(100); 14 | 15 | public TimeOutDelegatingHandler(TimeSpan timeOut) 16 | : base() 17 | { 18 | _timeOut = timeOut; 19 | } 20 | 21 | public TimeOutDelegatingHandler(HttpMessageHandler innerHandler, 22 | TimeSpan timeOut) 23 | : base(innerHandler) 24 | { 25 | _timeOut = timeOut; 26 | } 27 | 28 | protected override async Task SendAsync( 29 | HttpRequestMessage request, 30 | CancellationToken cancellationToken) 31 | { 32 | using (var linkedCancellationTokenSource = 33 | CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) 34 | { 35 | linkedCancellationTokenSource.CancelAfter(_timeOut); 36 | try 37 | { 38 | return await base.SendAsync(request, linkedCancellationTokenSource.Token); 39 | } 40 | catch (OperationCanceledException ex) 41 | { 42 | if (!cancellationToken.IsCancellationRequested) 43 | { 44 | throw new TimeoutException("The request timed out.", ex); 45 | } 46 | throw; 47 | } 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Finished sample/Movies.Client/UnauthorizedApiAccessException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.Serialization; 3 | 4 | namespace Movies.Client 5 | { 6 | [Serializable] 7 | public class UnauthorizedApiAccessException : Exception 8 | { 9 | public UnauthorizedApiAccessException() 10 | { 11 | } 12 | 13 | public UnauthorizedApiAccessException(string message) : base(message) 14 | { 15 | } 16 | 17 | public UnauthorizedApiAccessException(string message, Exception innerException) : base(message, innerException) 18 | { 19 | } 20 | 21 | protected UnauthorizedApiAccessException(SerializationInfo info, StreamingContext context) : base(info, context) 22 | { 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Finished sample/Movies.UnitTests/Movies.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | all 16 | 17 | 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | all 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Finished sample/Movies.UnitTests/TestableClassWithApiAccessUnitTests.cs: -------------------------------------------------------------------------------- 1 | using Moq; 2 | using Moq.Protected; 3 | using Movies.Client; 4 | using System; 5 | using System.Net; 6 | using System.Net.Http; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | using Xunit; 10 | 11 | namespace Movies.UnitTests 12 | { 13 | public class TestableClassWithApiAccessUnitTests 14 | { 15 | [Fact] 16 | public async void GetMovie_On401Response_MustThrowUnauthorizedApiAccessException() 17 | { 18 | var httpClient = new HttpClient(new Return401UnauthorizedResponseHandler()) 19 | { 20 | BaseAddress = new Uri("http://localhost:57863") 21 | }; 22 | 23 | var testableClass = new TestableClassWithApiAccess(httpClient); 24 | 25 | await Assert.ThrowsAsync( 26 | () => testableClass.GetMovie(CancellationToken.None)); 27 | } 28 | 29 | [Fact] 30 | public async void GetMovie_On401Response_MustThrowUnauthorizedApiAccessException_WithMoq() 31 | { 32 | var unauthorizedResponseHttpMessageHandlerMock = new Mock(); 33 | unauthorizedResponseHttpMessageHandlerMock 34 | .Protected() 35 | .Setup>( 36 | "SendAsync", 37 | ItExpr.IsAny(), 38 | ItExpr.IsAny() 39 | ) 40 | .ReturnsAsync(new HttpResponseMessage() 41 | { 42 | StatusCode = HttpStatusCode.Unauthorized 43 | }); 44 | 45 | var httpClient = new HttpClient(unauthorizedResponseHttpMessageHandlerMock.Object) 46 | { 47 | BaseAddress = new Uri("http://localhost:57863") 48 | }; 49 | 50 | var testableClass = new TestableClassWithApiAccess(httpClient); 51 | 52 | await Assert.ThrowsAsync( 53 | () => testableClass.GetMovie(CancellationToken.None)); 54 | } 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Finished sample/Movies.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30717.126 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Movies.Client", "Movies.Client\Movies.Client.csproj", "{C0FA8F85-2A8D-45A4-905C-6665B21E4E91}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Movies.API", "Movies.API\Movies.API.csproj", "{8614CB18-9723-4EC7-8D41-D34BDECAD0ED}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01 Client", "01 Client", "{C2BDCED0-499B-4001-8D36-DFB0DBE624B4}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02 Server", "02 Server", "{CC16F37C-017E-4782-B335-12A2125D09E2}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03 Unit Tests", "03 Unit Tests", "{BB714726-65BE-4B97-AFF5-A374010AE994}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Movies.UnitTests", "Movies.UnitTests\Movies.UnitTests.csproj", "{A4DEAC96-5302-4556-99F4-DAFA13D496E3}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {A4DEAC96-5302-4556-99F4-DAFA13D496E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {A4DEAC96-5302-4556-99F4-DAFA13D496E3}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {A4DEAC96-5302-4556-99F4-DAFA13D496E3}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {A4DEAC96-5302-4556-99F4-DAFA13D496E3}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(NestedProjects) = preSolution 41 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91} = {C2BDCED0-499B-4001-8D36-DFB0DBE624B4} 42 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED} = {CC16F37C-017E-4782-B335-12A2125D09E2} 43 | {A4DEAC96-5302-4556-99F4-DAFA13D496E3} = {BB714726-65BE-4B97-AFF5-A374010AE994} 44 | EndGlobalSection 45 | GlobalSection(ExtensibilityGlobals) = postSolution 46 | SolutionGuid = {CF9D6D81-D749-4D51-AB81-EED468744611} 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Using HttpClient to Consume APIs in .NET 2 | Fully functioning finished sample code for my Using HttpClient to Consume APIs in .NET course over at Pluralsight. Code can be used as-is, or in conjunction with the course. 3 | 4 | Covers (amongst others): 5 | - simple CRUD 6 | - streams 7 | - compression 8 | - request cancelling 9 | - custom message handlers 10 | - unit testing 11 | - HttpClientFactory 12 | - ... 13 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Contexts/MoviesContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Movies.API.Entities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Movies.API.Contexts 9 | { 10 | public class MoviesContext : DbContext 11 | { 12 | public DbSet Movies { get; set; } 13 | 14 | public MoviesContext(DbContextOptions options) 15 | : base(options) 16 | { 17 | } 18 | 19 | // seed the database with data 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | modelBuilder.Entity().HasData( 23 | new Director() 24 | { 25 | Id = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 26 | FirstName = "Quentin", 27 | LastName = "Tarantino" 28 | }, 29 | new Director() 30 | { 31 | Id = Guid.Parse("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 32 | FirstName = "Joel", 33 | LastName = "Coen" 34 | }, 35 | new Director() 36 | { 37 | Id = Guid.Parse("c19099ed-94db-44ba-885b-0ad7205d5e40"), 38 | FirstName = "Martin", 39 | LastName = "Scorsese" 40 | }, 41 | new Director() 42 | { 43 | Id = Guid.Parse("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 44 | FirstName = "David", 45 | LastName = "Fincher" 46 | }, 47 | new Director() 48 | { 49 | Id = Guid.Parse("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 50 | FirstName = "Bryan", 51 | LastName = "Singer" 52 | }, 53 | new Director() 54 | { 55 | Id = Guid.Parse("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 56 | FirstName = "James", 57 | LastName = "Cameron" 58 | }); 59 | 60 | modelBuilder.Entity().HasData( 61 | new Movie 62 | { 63 | Id = Guid.Parse("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), 64 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 65 | Title = "Pulp Fiction", 66 | Description = "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", 67 | ReleaseDate = new DateTimeOffset(new DateTime(1994,11,9)), 68 | Genre = "Crime, Drama" 69 | }, 70 | new Movie 71 | { 72 | Id = Guid.Parse("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), 73 | DirectorId = Guid.Parse("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 74 | Title = "Jackie Brown", 75 | Description = "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", 76 | ReleaseDate = new DateTimeOffset(new DateTime(1997, 12, 25)), 77 | Genre = "Crime, Drama" 78 | }, 79 | new Movie 80 | { 81 | Id = Guid.Parse("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), 82 | DirectorId = Guid.Parse("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 83 | Title = "The Big Lebowski", 84 | Description = "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", 85 | ReleaseDate = new DateTimeOffset(new DateTime(1998, 3, 6)), 86 | Genre = "Comedy, Crime" 87 | }, 88 | new Movie 89 | { 90 | Id = Guid.Parse("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), 91 | DirectorId = Guid.Parse("c19099ed-94db-44ba-885b-0ad7205d5e40"), 92 | Title = "Casino", 93 | Description = "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", 94 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 11, 22)), 95 | Genre = "Crime, Drama" 96 | }, 97 | new Movie 98 | { 99 | Id = Guid.Parse("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), 100 | DirectorId = Guid.Parse("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 101 | Title = "Fight Club", 102 | Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", 103 | ReleaseDate = new DateTimeOffset(new DateTime(1999, 10, 15)), 104 | Genre = "Drama" 105 | }, 106 | new Movie 107 | { 108 | Id = Guid.Parse("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), 109 | DirectorId = Guid.Parse("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 110 | Title = "The Usual Suspects", 111 | Description = "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", 112 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 9, 15)), 113 | Genre = "Crime, Thriller" 114 | }, 115 | new Movie 116 | { 117 | Id = Guid.Parse("26fcbcc4-b7f7-47fc-9382-740c12246b59"), 118 | DirectorId = Guid.Parse("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 119 | Title = "Terminator 2: Judgment Day", 120 | Description = "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", 121 | ReleaseDate = new DateTimeOffset(new DateTime(1991, 7, 3)), 122 | Genre = "Action, Sci-Fi" 123 | }); 124 | 125 | base.OnModelCreating(modelBuilder); 126 | } 127 | 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Controllers/MoviesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AutoMapper; 6 | using Microsoft.AspNetCore.JsonPatch; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Movies.API.Entities; 9 | using Movies.API.Services; 10 | 11 | namespace Movies.API.Controllers 12 | { 13 | [Route("api/movies")] 14 | [ApiController] 15 | public class MoviesController : ControllerBase 16 | { 17 | private readonly IMoviesRepository _moviesRepository; 18 | private readonly IMapper _mapper; 19 | 20 | public MoviesController(IMoviesRepository moviesRepository, 21 | IMapper mapper) 22 | { 23 | _moviesRepository = moviesRepository ?? throw new ArgumentNullException(nameof(moviesRepository)); 24 | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); 25 | } 26 | 27 | [HttpGet] 28 | public async Task>> GetMovies() 29 | { 30 | var movieEntities = await _moviesRepository.GetMoviesAsync(); 31 | return Ok(_mapper.Map>(movieEntities)); 32 | } 33 | 34 | 35 | [HttpGet("{movieId}", Name = "GetMovie")] 36 | public async Task> GetMovie(Guid movieId) 37 | { 38 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 39 | if (movieEntity == null) 40 | { 41 | return NotFound(); 42 | } 43 | 44 | return Ok(_mapper.Map(movieEntity)); 45 | } 46 | 47 | [HttpPost] 48 | public async Task CreateMovie( 49 | [FromBody] Models.MovieForCreation movieForCreation) 50 | { 51 | // model validation 52 | if (movieForCreation == null) 53 | { 54 | return BadRequest(); 55 | } 56 | 57 | if (!ModelState.IsValid) 58 | { 59 | // return 422 - Unprocessable Entity when validation fails 60 | return new UnprocessableEntityObjectResult(ModelState); 61 | } 62 | 63 | var movieEntity = _mapper.Map(movieForCreation); 64 | _moviesRepository.AddMovie(movieEntity); 65 | 66 | // save the changes 67 | await _moviesRepository.SaveChangesAsync(); 68 | 69 | // Fetch the movie from the data store so the director is included 70 | await _moviesRepository.GetMovieAsync(movieEntity.Id); 71 | 72 | return CreatedAtRoute("GetMovie", 73 | new { movieId = movieEntity.Id }, 74 | _mapper.Map(movieEntity)); 75 | } 76 | 77 | [HttpPut("{movieId}")] 78 | public async Task UpdateMovie(Guid movieId, 79 | [FromBody] Models.MovieForUpdate movieForUpdate) 80 | { 81 | // model validation 82 | if (movieForUpdate == null) 83 | { 84 | //return BadRequest(); 85 | } 86 | 87 | if (!ModelState.IsValid) 88 | { 89 | // return 422 - Unprocessable Entity when validation fails 90 | return new UnprocessableEntityObjectResult(ModelState); 91 | } 92 | 93 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 94 | if (movieEntity == null) 95 | { 96 | return NotFound(); 97 | } 98 | 99 | // map the inputted object into the movie entity 100 | // this ensures properties will get updated 101 | _mapper.Map(movieForUpdate, movieEntity); 102 | 103 | // call into UpdateMovie even though in our implementation 104 | // this doesn't contain code - doing this ensures the code stays 105 | // reliable when other repository implemenations (eg: a mock 106 | // repository) are used. 107 | _moviesRepository.UpdateMovie(movieEntity); 108 | 109 | await _moviesRepository.SaveChangesAsync(); 110 | 111 | // return the updated movie, after mapping it 112 | return Ok(_mapper.Map(movieEntity)); 113 | } 114 | 115 | [HttpPatch("{movieId}")] 116 | public async Task PartiallyUpdateMovie(Guid movieId, 117 | [FromBody] JsonPatchDocument patchDoc) 118 | { 119 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 120 | if (movieEntity == null) 121 | { 122 | return NotFound(); 123 | } 124 | 125 | // the patch is on a DTO, not on the movie entity 126 | var movieToPatch = _mapper.Map(movieEntity); 127 | 128 | patchDoc.ApplyTo(movieToPatch, ModelState); 129 | 130 | if (!ModelState.IsValid) 131 | { 132 | return new UnprocessableEntityObjectResult(ModelState); 133 | } 134 | 135 | // map back to the entity, and save 136 | _mapper.Map(movieToPatch, movieEntity); 137 | 138 | // call into UpdateMovie even though in our implementation 139 | // this doesn't contain code - doing this ensures the code stays 140 | // reliable when other repository implemenations (eg: a mock 141 | // repository) are used. 142 | _moviesRepository.UpdateMovie(movieEntity); 143 | 144 | await _moviesRepository.SaveChangesAsync(); 145 | 146 | // return the updated movie, after mapping it 147 | return Ok(_mapper.Map(movieEntity)); 148 | } 149 | 150 | [HttpDelete("{movieid}")] 151 | public async Task DeleteMovie(Guid movieId) 152 | { 153 | var movieEntity = await _moviesRepository.GetMovieAsync(movieId); 154 | if (movieEntity == null) 155 | { 156 | return NotFound(); 157 | } 158 | 159 | _moviesRepository.DeleteMovie(movieEntity); 160 | await _moviesRepository.SaveChangesAsync(); 161 | 162 | return NoContent(); 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Controllers/PostersController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Movies.API.InternalModels; 4 | using Movies.API.Services; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace Movies.API.Controllers 11 | { 12 | [Route("api/movies/{movieId}/posters")] 13 | [ApiController] 14 | public class PostersController : ControllerBase 15 | { 16 | private readonly IPostersRepository _postersRepository; 17 | private readonly IMapper _mapper; 18 | 19 | public PostersController(IPostersRepository postersRepository, 20 | IMapper mapper) 21 | { 22 | _postersRepository = postersRepository ?? throw new ArgumentNullException(nameof(postersRepository)); 23 | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); 24 | } 25 | 26 | [HttpGet("{posterId}", Name = "GetPoster")] 27 | public async Task> GetPoster(Guid movieId, Guid posterId) 28 | { 29 | var poster = await _postersRepository.GetPosterAsync(movieId, posterId); 30 | if (poster == null) 31 | { 32 | return NotFound(); 33 | } 34 | 35 | return Ok(_mapper.Map(poster)); 36 | } 37 | 38 | [HttpPost] 39 | public async Task CreatePoster(Guid movieId, 40 | [FromBody] Models.PosterForCreation posterForCreation) 41 | { 42 | // model validation 43 | if (posterForCreation == null) 44 | { 45 | return BadRequest(); 46 | } 47 | 48 | if (!ModelState.IsValid) 49 | { 50 | // return 422 - Unprocessable Entity when validation fails 51 | return new UnprocessableEntityObjectResult(ModelState); 52 | } 53 | 54 | var poster = _mapper.Map(posterForCreation); 55 | var createdPoster = await _postersRepository.AddPoster(movieId, poster); 56 | 57 | // no need to save, in this type of repo the poster is 58 | // immediately persisted. 59 | 60 | // map the poster from the repository to a shared model poster 61 | return CreatedAtRoute("GetPoster", 62 | new { movieId, posterId = createdPoster.Id }, 63 | _mapper.Map(createdPoster)); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Controllers/TrailersController.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Movies.API.InternalModels; 4 | using Movies.API.Services; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace Movies.API.Controllers 11 | { 12 | [Route("api/movies/{movieId}/trailers")] 13 | [ApiController] 14 | public class TrailersController : ControllerBase 15 | { 16 | private readonly ITrailersRepository _trailersRepository; 17 | private readonly IMapper _mapper; 18 | 19 | public TrailersController(ITrailersRepository trailersRepository, 20 | IMapper mapper) 21 | { 22 | _trailersRepository = trailersRepository ?? throw new ArgumentNullException(nameof(trailersRepository)); 23 | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); 24 | } 25 | 26 | [HttpGet("{trailerId}", Name = "GetTrailer")] 27 | public async Task> GetTrailer(Guid movieId, Guid trailerId) 28 | { 29 | var trailer = await _trailersRepository.GetTrailerAsync(movieId, trailerId); 30 | if (trailer == null) 31 | { 32 | return NotFound(); 33 | } 34 | 35 | return Ok(_mapper.Map(trailer)); 36 | } 37 | 38 | [HttpPost] 39 | public async Task CreateTrailer(Guid movieId, 40 | [FromBody] Models.TrailerForCreation trailerForCreation) 41 | { 42 | // model validation 43 | if (trailerForCreation == null) 44 | { 45 | return BadRequest(); 46 | } 47 | 48 | if (!ModelState.IsValid) 49 | { 50 | // return 422 - Unprocessable Entity when validation fails 51 | return new UnprocessableEntityObjectResult(ModelState); 52 | } 53 | 54 | var trailer = _mapper.Map(trailerForCreation); 55 | var createdTrailer = await _trailersRepository.AddTrailer(movieId, trailer); 56 | 57 | // no need to save, in this type of repo the trailer is 58 | // immediately persisted. 59 | 60 | // map the trailer from the repository to a shared model trailer 61 | return CreatedAtRoute("GetTrailer", 62 | new { movieId, trailerId = createdTrailer.Id }, 63 | _mapper.Map(createdTrailer)); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Entities/Director.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Movies.API.Entities 9 | { 10 | [Table("Directors")] 11 | public class Director 12 | { 13 | [Key] 14 | public Guid Id { get; set; } 15 | 16 | [Required] 17 | [MaxLength(200)] 18 | public string FirstName { get; set; } 19 | 20 | [Required] 21 | [MaxLength(200)] 22 | public string LastName { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Entities/Movie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Movies.API.Entities 9 | { 10 | [Table("Movies")] 11 | public class Movie 12 | { 13 | [Key] 14 | public Guid Id { get; set; } 15 | 16 | [Required] 17 | [MaxLength(200)] 18 | public string Title { get; set; } 19 | 20 | [MaxLength(2000)] 21 | public string Description { get; set; } 22 | 23 | [MaxLength(200)] 24 | public string Genre { get; set; } 25 | 26 | [Required] 27 | public DateTimeOffset ReleaseDate { get; set; } 28 | 29 | [Required] 30 | public Guid DirectorId { get; set; } 31 | public Director Director { get; set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Starter files/Movies.API/InternalModels/Poster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.InternalModels 8 | { 9 | public class Poster 10 | { 11 | [Required] 12 | public Guid Id { get; set; } 13 | 14 | [Required] 15 | public Guid MovieId { get; set; } 16 | 17 | [Required] 18 | [MaxLength(200)] 19 | public string Name { get; set; } 20 | 21 | [Required] 22 | public byte[] Bytes { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Starter files/Movies.API/InternalModels/Trailer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.InternalModels 8 | { 9 | public class Trailer 10 | { 11 | [Required] 12 | public Guid Id { get; set; } 13 | 14 | [Required] 15 | public Guid MovieId { get; set; } 16 | 17 | [Required] 18 | [MaxLength(200)] 19 | public string Name { get; set; } 20 | 21 | [MaxLength(1000)] 22 | public string Description { get; set; } 23 | 24 | [Required] 25 | public byte[] Bytes { get; set; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Migrations/InitialMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Movies.API.Contexts; 8 | 9 | namespace Movies.API.Migrations 10 | { 11 | [DbContext(typeof(MoviesContext))] 12 | [Migration("20210413080151_InitialMigration")] 13 | partial class InitialMigration 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "5.0.4"); 20 | 21 | modelBuilder.Entity("Movies.API.Entities.Director", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd() 25 | .HasColumnType("TEXT"); 26 | 27 | b.Property("FirstName") 28 | .IsRequired() 29 | .HasMaxLength(200) 30 | .HasColumnType("TEXT"); 31 | 32 | b.Property("LastName") 33 | .IsRequired() 34 | .HasMaxLength(200) 35 | .HasColumnType("TEXT"); 36 | 37 | b.HasKey("Id"); 38 | 39 | b.ToTable("Directors"); 40 | 41 | b.HasData( 42 | new 43 | { 44 | Id = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 45 | FirstName = "Quentin", 46 | LastName = "Tarantino" 47 | }, 48 | new 49 | { 50 | Id = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 51 | FirstName = "Joel", 52 | LastName = "Coen" 53 | }, 54 | new 55 | { 56 | Id = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 57 | FirstName = "Martin", 58 | LastName = "Scorsese" 59 | }, 60 | new 61 | { 62 | Id = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 63 | FirstName = "David", 64 | LastName = "Fincher" 65 | }, 66 | new 67 | { 68 | Id = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 69 | FirstName = "Bryan", 70 | LastName = "Singer" 71 | }, 72 | new 73 | { 74 | Id = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 75 | FirstName = "James", 76 | LastName = "Cameron" 77 | }); 78 | }); 79 | 80 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 81 | { 82 | b.Property("Id") 83 | .ValueGeneratedOnAdd() 84 | .HasColumnType("TEXT"); 85 | 86 | b.Property("Description") 87 | .HasMaxLength(2000) 88 | .HasColumnType("TEXT"); 89 | 90 | b.Property("DirectorId") 91 | .HasColumnType("TEXT"); 92 | 93 | b.Property("Genre") 94 | .HasMaxLength(200) 95 | .HasColumnType("TEXT"); 96 | 97 | b.Property("ReleaseDate") 98 | .HasColumnType("TEXT"); 99 | 100 | b.Property("Title") 101 | .IsRequired() 102 | .HasMaxLength(200) 103 | .HasColumnType("TEXT"); 104 | 105 | b.HasKey("Id"); 106 | 107 | b.HasIndex("DirectorId"); 108 | 109 | b.ToTable("Movies"); 110 | 111 | b.HasData( 112 | new 113 | { 114 | Id = new Guid("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), 115 | Description = "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", 116 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 117 | Genre = "Crime, Drama", 118 | ReleaseDate = new DateTimeOffset(new DateTime(1994, 11, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 119 | Title = "Pulp Fiction" 120 | }, 121 | new 122 | { 123 | Id = new Guid("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), 124 | Description = "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", 125 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 126 | Genre = "Crime, Drama", 127 | ReleaseDate = new DateTimeOffset(new DateTime(1997, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 128 | Title = "Jackie Brown" 129 | }, 130 | new 131 | { 132 | Id = new Guid("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), 133 | Description = "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", 134 | DirectorId = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 135 | Genre = "Comedy, Crime", 136 | ReleaseDate = new DateTimeOffset(new DateTime(1998, 3, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 137 | Title = "The Big Lebowski" 138 | }, 139 | new 140 | { 141 | Id = new Guid("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), 142 | Description = "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", 143 | DirectorId = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 144 | Genre = "Crime, Drama", 145 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 11, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 146 | Title = "Casino" 147 | }, 148 | new 149 | { 150 | Id = new Guid("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), 151 | Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", 152 | DirectorId = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 153 | Genre = "Drama", 154 | ReleaseDate = new DateTimeOffset(new DateTime(1999, 10, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 155 | Title = "Fight Club" 156 | }, 157 | new 158 | { 159 | Id = new Guid("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), 160 | Description = "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", 161 | DirectorId = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 162 | Genre = "Crime, Thriller", 163 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 9, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 164 | Title = "The Usual Suspects" 165 | }, 166 | new 167 | { 168 | Id = new Guid("26fcbcc4-b7f7-47fc-9382-740c12246b59"), 169 | Description = "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", 170 | DirectorId = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 171 | Genre = "Action, Sci-Fi", 172 | ReleaseDate = new DateTimeOffset(new DateTime(1991, 7, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 173 | Title = "Terminator 2: Judgment Day" 174 | }); 175 | }); 176 | 177 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 178 | { 179 | b.HasOne("Movies.API.Entities.Director", "Director") 180 | .WithMany() 181 | .HasForeignKey("DirectorId") 182 | .OnDelete(DeleteBehavior.Cascade) 183 | .IsRequired(); 184 | 185 | b.Navigation("Director"); 186 | }); 187 | #pragma warning restore 612, 618 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Migrations/InitialMigration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace Movies.API.Migrations 5 | { 6 | public partial class InitialMigration : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Directors", 12 | columns: table => new 13 | { 14 | Id = table.Column(type: "TEXT", nullable: false), 15 | FirstName = table.Column(type: "TEXT", maxLength: 200, nullable: false), 16 | LastName = table.Column(type: "TEXT", maxLength: 200, nullable: false) 17 | }, 18 | constraints: table => 19 | { 20 | table.PrimaryKey("PK_Directors", x => x.Id); 21 | }); 22 | 23 | migrationBuilder.CreateTable( 24 | name: "Movies", 25 | columns: table => new 26 | { 27 | Id = table.Column(type: "TEXT", nullable: false), 28 | Title = table.Column(type: "TEXT", maxLength: 200, nullable: false), 29 | Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), 30 | Genre = table.Column(type: "TEXT", maxLength: 200, nullable: true), 31 | ReleaseDate = table.Column(type: "TEXT", nullable: false), 32 | DirectorId = table.Column(type: "TEXT", nullable: false) 33 | }, 34 | constraints: table => 35 | { 36 | table.PrimaryKey("PK_Movies", x => x.Id); 37 | table.ForeignKey( 38 | name: "FK_Movies_Directors_DirectorId", 39 | column: x => x.DirectorId, 40 | principalTable: "Directors", 41 | principalColumn: "Id", 42 | onDelete: ReferentialAction.Cascade); 43 | }); 44 | 45 | migrationBuilder.InsertData( 46 | table: "Directors", 47 | columns: new[] { "Id", "FirstName", "LastName" }, 48 | values: new object[] { new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), "Quentin", "Tarantino" }); 49 | 50 | migrationBuilder.InsertData( 51 | table: "Directors", 52 | columns: new[] { "Id", "FirstName", "LastName" }, 53 | values: new object[] { new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), "Joel", "Coen" }); 54 | 55 | migrationBuilder.InsertData( 56 | table: "Directors", 57 | columns: new[] { "Id", "FirstName", "LastName" }, 58 | values: new object[] { new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), "Martin", "Scorsese" }); 59 | 60 | migrationBuilder.InsertData( 61 | table: "Directors", 62 | columns: new[] { "Id", "FirstName", "LastName" }, 63 | values: new object[] { new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), "David", "Fincher" }); 64 | 65 | migrationBuilder.InsertData( 66 | table: "Directors", 67 | columns: new[] { "Id", "FirstName", "LastName" }, 68 | values: new object[] { new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), "Bryan", "Singer" }); 69 | 70 | migrationBuilder.InsertData( 71 | table: "Directors", 72 | columns: new[] { "Id", "FirstName", "LastName" }, 73 | values: new object[] { new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), "James", "Cameron" }); 74 | 75 | migrationBuilder.InsertData( 76 | table: "Movies", 77 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 78 | values: new object[] { new Guid("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), "Crime, Drama", new DateTimeOffset(new DateTime(1994, 11, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "Pulp Fiction" }); 79 | 80 | migrationBuilder.InsertData( 81 | table: "Movies", 82 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 83 | values: new object[] { new Guid("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), "Crime, Drama", new DateTimeOffset(new DateTime(1997, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "Jackie Brown" }); 84 | 85 | migrationBuilder.InsertData( 86 | table: "Movies", 87 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 88 | values: new object[] { new Guid("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), "Comedy, Crime", new DateTimeOffset(new DateTime(1998, 3, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "The Big Lebowski" }); 89 | 90 | migrationBuilder.InsertData( 91 | table: "Movies", 92 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 93 | values: new object[] { new Guid("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), "Crime, Drama", new DateTimeOffset(new DateTime(1995, 11, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), "Casino" }); 94 | 95 | migrationBuilder.InsertData( 96 | table: "Movies", 97 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 98 | values: new object[] { new Guid("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), "Drama", new DateTimeOffset(new DateTime(1999, 10, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), "Fight Club" }); 99 | 100 | migrationBuilder.InsertData( 101 | table: "Movies", 102 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 103 | values: new object[] { new Guid("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), "Crime, Thriller", new DateTimeOffset(new DateTime(1995, 9, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), "The Usual Suspects" }); 104 | 105 | migrationBuilder.InsertData( 106 | table: "Movies", 107 | columns: new[] { "Id", "Description", "DirectorId", "Genre", "ReleaseDate", "Title" }, 108 | values: new object[] { new Guid("26fcbcc4-b7f7-47fc-9382-740c12246b59"), "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), "Action, Sci-Fi", new DateTimeOffset(new DateTime(1991, 7, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), "Terminator 2: Judgment Day" }); 109 | 110 | migrationBuilder.CreateIndex( 111 | name: "IX_Movies_DirectorId", 112 | table: "Movies", 113 | column: "DirectorId"); 114 | } 115 | 116 | protected override void Down(MigrationBuilder migrationBuilder) 117 | { 118 | migrationBuilder.DropTable( 119 | name: "Movies"); 120 | 121 | migrationBuilder.DropTable( 122 | name: "Directors"); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Migrations/MoviesContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using Movies.API.Contexts; 7 | 8 | namespace Movies.API.Migrations 9 | { 10 | [DbContext(typeof(MoviesContext))] 11 | partial class MoviesContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "5.0.4"); 18 | 19 | modelBuilder.Entity("Movies.API.Entities.Director", b => 20 | { 21 | b.Property("Id") 22 | .ValueGeneratedOnAdd() 23 | .HasColumnType("TEXT"); 24 | 25 | b.Property("FirstName") 26 | .IsRequired() 27 | .HasMaxLength(200) 28 | .HasColumnType("TEXT"); 29 | 30 | b.Property("LastName") 31 | .IsRequired() 32 | .HasMaxLength(200) 33 | .HasColumnType("TEXT"); 34 | 35 | b.HasKey("Id"); 36 | 37 | b.ToTable("Directors"); 38 | 39 | b.HasData( 40 | new 41 | { 42 | Id = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 43 | FirstName = "Quentin", 44 | LastName = "Tarantino" 45 | }, 46 | new 47 | { 48 | Id = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 49 | FirstName = "Joel", 50 | LastName = "Coen" 51 | }, 52 | new 53 | { 54 | Id = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 55 | FirstName = "Martin", 56 | LastName = "Scorsese" 57 | }, 58 | new 59 | { 60 | Id = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 61 | FirstName = "David", 62 | LastName = "Fincher" 63 | }, 64 | new 65 | { 66 | Id = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 67 | FirstName = "Bryan", 68 | LastName = "Singer" 69 | }, 70 | new 71 | { 72 | Id = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 73 | FirstName = "James", 74 | LastName = "Cameron" 75 | }); 76 | }); 77 | 78 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 79 | { 80 | b.Property("Id") 81 | .ValueGeneratedOnAdd() 82 | .HasColumnType("TEXT"); 83 | 84 | b.Property("Description") 85 | .HasMaxLength(2000) 86 | .HasColumnType("TEXT"); 87 | 88 | b.Property("DirectorId") 89 | .HasColumnType("TEXT"); 90 | 91 | b.Property("Genre") 92 | .HasMaxLength(200) 93 | .HasColumnType("TEXT"); 94 | 95 | b.Property("ReleaseDate") 96 | .HasColumnType("TEXT"); 97 | 98 | b.Property("Title") 99 | .IsRequired() 100 | .HasMaxLength(200) 101 | .HasColumnType("TEXT"); 102 | 103 | b.HasKey("Id"); 104 | 105 | b.HasIndex("DirectorId"); 106 | 107 | b.ToTable("Movies"); 108 | 109 | b.HasData( 110 | new 111 | { 112 | Id = new Guid("5b1c2b4d-48c7-402a-80c3-cc796ad49c6b"), 113 | Description = "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", 114 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 115 | Genre = "Crime, Drama", 116 | ReleaseDate = new DateTimeOffset(new DateTime(1994, 11, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 117 | Title = "Pulp Fiction" 118 | }, 119 | new 120 | { 121 | Id = new Guid("6e87f657-f2c1-4d90-9b37-cbe43cc6adb9"), 122 | Description = "A middle-aged woman finds herself in the middle of a huge conflict that will either make her a profit or cost her life.", 123 | DirectorId = new Guid("d28888e9-2ba9-473a-a40f-e38cb54f9b35"), 124 | Genre = "Crime, Drama", 125 | ReleaseDate = new DateTimeOffset(new DateTime(1997, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 126 | Title = "Jackie Brown" 127 | }, 128 | new 129 | { 130 | Id = new Guid("d8663e5e-7494-4f81-8739-6e0de1bea7ee"), 131 | Description = "The Dude (Lebowski), mistaken for a millionaire Lebowski, seeks restitution for his ruined rug and enlists his bowling buddies to help get it.", 132 | DirectorId = new Guid("da2fd609-d754-4feb-8acd-c4f9ff13ba96"), 133 | Genre = "Comedy, Crime", 134 | ReleaseDate = new DateTimeOffset(new DateTime(1998, 3, 6, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 135 | Title = "The Big Lebowski" 136 | }, 137 | new 138 | { 139 | Id = new Guid("f9a16fee-4c49-41bb-87a1-bbaad0cd1174"), 140 | Description = "A tale of greed, deception, money, power, and murder occur between two best friends: a mafia enforcer and a casino executive, compete against each other over a gambling empire, and over a fast living and fast loving socialite.", 141 | DirectorId = new Guid("c19099ed-94db-44ba-885b-0ad7205d5e40"), 142 | Genre = "Crime, Drama", 143 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 11, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), 144 | Title = "Casino" 145 | }, 146 | new 147 | { 148 | Id = new Guid("bb6a100a-053f-4bf8-b271-60ce3aae6eb5"), 149 | Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.", 150 | DirectorId = new Guid("0c4dc798-b38b-4a1c-905c-a9e76dbef17b"), 151 | Genre = "Drama", 152 | ReleaseDate = new DateTimeOffset(new DateTime(1999, 10, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 153 | Title = "Fight Club" 154 | }, 155 | new 156 | { 157 | Id = new Guid("3d2880ae-5ba6-417c-845d-f4ebfd4bcac7"), 158 | Description = "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.", 159 | DirectorId = new Guid("937b1ba1-7969-4324-9ab5-afb0e4d875e6"), 160 | Genre = "Crime, Thriller", 161 | ReleaseDate = new DateTimeOffset(new DateTime(1995, 9, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 162 | Title = "The Usual Suspects" 163 | }, 164 | new 165 | { 166 | Id = new Guid("26fcbcc4-b7f7-47fc-9382-740c12246b59"), 167 | Description = "A cyborg, identical to the one who failed to kill Sarah Connor, must now protect her teenage son, John Connor, from a more advanced and powerful cyborg.", 168 | DirectorId = new Guid("7a2fbc72-bb33-49de-bd23-c78fceb367fc"), 169 | Genre = "Action, Sci-Fi", 170 | ReleaseDate = new DateTimeOffset(new DateTime(1991, 7, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 2, 0, 0, 0)), 171 | Title = "Terminator 2: Judgment Day" 172 | }); 173 | }); 174 | 175 | modelBuilder.Entity("Movies.API.Entities.Movie", b => 176 | { 177 | b.HasOne("Movies.API.Entities.Director", "Director") 178 | .WithMany() 179 | .HasForeignKey("DirectorId") 180 | .OnDelete(DeleteBehavior.Cascade) 181 | .IsRequired(); 182 | 183 | b.Navigation("Director"); 184 | }); 185 | #pragma warning restore 612, 618 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/Movie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace Movies.API.Models 5 | { 6 | public class Movie 7 | { 8 | public Guid Id { get; set; } 9 | public string Title { get; set; } 10 | public string Description { get; set; } 11 | public string Genre { get; set; } 12 | public DateTimeOffset ReleaseDate { get; set; } 13 | public string Director { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/MovieForCreation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class MovieForCreation 9 | { 10 | [Required] 11 | [MaxLength(200)] 12 | public string Title { get; set; } 13 | 14 | [MaxLength(2000)] 15 | [MinLength(10)] 16 | public string Description { get; set; } 17 | 18 | [MaxLength(200)] 19 | public string Genre { get; set; } 20 | 21 | [Required] 22 | public DateTimeOffset? ReleaseDate { get; set; } 23 | 24 | [Required] 25 | public Guid? DirectorId { get; set; } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/MovieForUpdate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class MovieForUpdate 9 | { 10 | [Required] 11 | [MaxLength(200)] 12 | public string Title { get; set; } 13 | 14 | [MaxLength(2000)] 15 | public string Description { get; set; } 16 | 17 | [MaxLength(200)] 18 | public string Genre { get; set; } 19 | 20 | [Required] 21 | public DateTimeOffset ReleaseDate { get; set; } 22 | 23 | [Required] 24 | public Guid DirectorId { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/Poster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Movies.API.Models 6 | { 7 | public class Poster 8 | { 9 | public Guid Id { get; set; } 10 | public Guid MovieId { get; set; } 11 | public string Name { get; set; } 12 | public byte[] Bytes { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/PosterForCreation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class PosterForCreation 9 | { 10 | [Required] 11 | [MaxLength(200)] 12 | public string Name { get; set; } 13 | 14 | [Required] 15 | public byte[] Bytes { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/Trailer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Movies.API.Models 6 | { 7 | public class Trailer 8 | { 9 | public Guid Id { get; set; } 10 | public Guid MovieId { get; set; } 11 | public string Name { get; set; } 12 | public string Description { get; set; } 13 | public byte[] Bytes { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Models/TrailerForCreation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Movies.API.Models 7 | { 8 | public class TrailerForCreation 9 | { 10 | [Required] 11 | public Guid MovieId { get; set; } 12 | 13 | [Required] 14 | [MaxLength(200)] 15 | public string Name { get; set; } 16 | 17 | [MaxLength(1000)] 18 | public string Description { get; set; } 19 | 20 | [Required] 21 | public byte[] Bytes { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Movies.API.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 9.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Movies.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KevinDockx/UsingHttpClientInDotNet/75cb69ea14621cf221bbee885064c781f03d311c/Starter files/Movies.API/Movies.db -------------------------------------------------------------------------------- /Starter files/Movies.API/Profiles/MoviesProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System.Collections.Generic; 3 | 4 | namespace Movies.API 5 | { 6 | /// 7 | /// AutoMapper profile for working with Movie objects 8 | /// 9 | public class MoviesProfile : Profile 10 | { 11 | public MoviesProfile() 12 | { 13 | CreateMap() 14 | .ForMember(dest => dest.Director, opt => opt.MapFrom(src => 15 | $"{src.Director.FirstName} {src.Director.LastName}")); 16 | 17 | CreateMap(); 18 | 19 | CreateMap().ReverseMap(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Profiles/PostersProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace Movies.API.Profiles 4 | { 5 | /// 6 | /// AutoMapper profile for working with Poster objects 7 | /// 8 | public class PostersProfile : Profile 9 | { 10 | public PostersProfile() 11 | { 12 | CreateMap(); 13 | CreateMap(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Profiles/TrailersProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace Movies.API.Profiles 4 | { 5 | /// 6 | /// AutoMapper profile for working with Trailer objects 7 | /// 8 | public class TrailersProfile : Profile 9 | { 10 | public TrailersProfile() 11 | { 12 | CreateMap(); 13 | CreateMap(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using Movies.API.Contexts; 13 | 14 | namespace Movies.API 15 | { 16 | public class Program 17 | { 18 | public static void Main(string[] args) 19 | { 20 | var host = CreateWebHostBuilder(args).Build(); 21 | 22 | // For demo purposes: clear the database 23 | // and refill it with dummy data 24 | using (var scope = host.Services.CreateScope()) 25 | { 26 | try 27 | { 28 | var context = scope.ServiceProvider.GetService(); 29 | // delete the DB if it exists 30 | context.Database.EnsureDeleted(); 31 | // migrate the DB - this will also seed the DB with dummy data 32 | context.Database.Migrate(); 33 | } 34 | catch (Exception ex) 35 | { 36 | var logger = scope.ServiceProvider.GetRequiredService>(); 37 | logger.LogError(ex, "An error occurred while migrating the database."); 38 | } 39 | } 40 | 41 | // run the web app 42 | host.Run(); 43 | } 44 | 45 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 46 | WebHost.CreateDefaultBuilder(args) 47 | .UseStartup(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:57863", 7 | "sslPort": 0 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "http://localhost:57863", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "Movies.API": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "api/values", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | }, 27 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Starter files/Movies.API/Services/IMoviesRepository.cs: -------------------------------------------------------------------------------- 1 | using Movies.API.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.Services 8 | { 9 | public interface IMoviesRepository 10 | { 11 | Task GetMovieAsync(Guid movieId); 12 | 13 | Task> GetMoviesAsync(); 14 | 15 | void UpdateMovie(Movie movieToUpdate); 16 | 17 | void AddMovie(Movie movieToAdd); 18 | 19 | void DeleteMovie(Movie movieToDelete); 20 | 21 | Task SaveChangesAsync(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Services/IPostersRepository.cs: -------------------------------------------------------------------------------- 1 | using Movies.API.InternalModels; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.Services 8 | { 9 | public interface IPostersRepository 10 | { 11 | Task GetPosterAsync(Guid movieId, Guid posterId); 12 | 13 | Task AddPoster(Guid movieId, Poster posterToAdd); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Services/ITrailersRepository.cs: -------------------------------------------------------------------------------- 1 | using Movies.API.InternalModels; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Movies.API.Services 8 | { 9 | public interface ITrailersRepository 10 | { 11 | Task GetTrailerAsync(Guid movieId, Guid trailerId); 12 | 13 | Task AddTrailer(Guid movieId, Trailer trailerToAdd); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Services/MoviesRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Movies.API.Contexts; 3 | using Movies.API.Entities; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.API.Services 10 | { 11 | public class MoviesRepository : IMoviesRepository, IDisposable 12 | { 13 | private MoviesContext _context; 14 | 15 | public MoviesRepository(MoviesContext context) 16 | { 17 | _context = context ?? throw new ArgumentNullException(nameof(context)); 18 | } 19 | 20 | public async Task GetMovieAsync(Guid movieId) 21 | { 22 | return await _context.Movies.Include(m => m.Director) 23 | .FirstOrDefaultAsync(m => m.Id == movieId); 24 | } 25 | 26 | public async Task> GetMoviesAsync() 27 | { 28 | return await _context.Movies.Include(m => m.Director).ToListAsync(); 29 | } 30 | 31 | public void UpdateMovie(Movie movieToUpdate) 32 | { 33 | // no code required, entity tracked by context. Including 34 | // this is best practice to ensure other implementations of the 35 | // contract (eg a mock version) can execute code on update 36 | // when needed. 37 | } 38 | 39 | public void AddMovie(Movie movieToAdd) 40 | { 41 | if (movieToAdd == null) 42 | { 43 | throw new ArgumentNullException(nameof(movieToAdd)); 44 | } 45 | 46 | _context.Add(movieToAdd); 47 | } 48 | 49 | public void DeleteMovie(Movie movieToDelete) 50 | { 51 | if (movieToDelete == null) 52 | { 53 | throw new ArgumentNullException(nameof(movieToDelete)); 54 | } 55 | 56 | _context.Remove(movieToDelete); 57 | } 58 | 59 | public async Task SaveChangesAsync() 60 | { 61 | // return true if 1 or more entities were changed 62 | return (await _context.SaveChangesAsync() > 0); 63 | } 64 | 65 | public void Dispose() 66 | { 67 | Dispose(true); 68 | GC.SuppressFinalize(this); 69 | } 70 | 71 | protected virtual void Dispose(bool disposing) 72 | { 73 | if (disposing) 74 | { 75 | if (_context != null) 76 | { 77 | _context.Dispose(); 78 | _context = null; 79 | } 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Services/PostersRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Movies.API.Contexts; 7 | using Movies.API.InternalModels; 8 | 9 | namespace Movies.API.Services 10 | { 11 | public class PostersRepository : IPostersRepository, IDisposable 12 | { 13 | private MoviesContext _context; 14 | 15 | public PostersRepository(MoviesContext context) 16 | { 17 | _context = context ?? throw new ArgumentNullException(nameof(context)); 18 | 19 | } 20 | 21 | public async Task GetPosterAsync(Guid movieId, Guid posterId) 22 | { 23 | // Generate the name from the movie title. 24 | var movie = await _context.Movies 25 | .FirstOrDefaultAsync(m => m.Id == movieId); 26 | 27 | if (movie == null) 28 | { 29 | throw new Exception($"Movie with id {movieId} not found."); 30 | } 31 | 32 | // generate a movie poster of 500KB 33 | var random = new Random(); 34 | var generatedBytes = new byte[524288]; 35 | random.NextBytes(generatedBytes); 36 | 37 | return new Poster() 38 | { 39 | Bytes = generatedBytes, 40 | Id = posterId, 41 | MovieId = movieId, 42 | Name = $"{movie.Title} poster number {DateTime.UtcNow.Ticks}" 43 | }; 44 | } 45 | 46 | public async Task AddPoster(Guid movieId, Poster posterToAdd) 47 | { 48 | // don't do anything: we're just faking this. Simply return the poster 49 | // after setting the ids 50 | posterToAdd.MovieId = movieId; 51 | posterToAdd.Id = Guid.NewGuid(); 52 | return await Task.FromResult(posterToAdd); 53 | } 54 | 55 | public void Dispose() 56 | { 57 | Dispose(true); 58 | GC.SuppressFinalize(this); 59 | } 60 | 61 | 62 | protected virtual void Dispose(bool disposing) 63 | { 64 | if (disposing) 65 | { 66 | if (_context != null) 67 | { 68 | _context.Dispose(); 69 | _context = null; 70 | } 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Services/TrailersRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using Movies.API.Contexts; 7 | using Movies.API.InternalModels; 8 | 9 | namespace Movies.API.Services 10 | { 11 | public class TrailersRepository : ITrailersRepository, IDisposable 12 | { 13 | private MoviesContext _context; 14 | 15 | public TrailersRepository(MoviesContext context) 16 | { 17 | _context = context ?? throw new ArgumentNullException(nameof(context)); 18 | 19 | } 20 | 21 | public async Task GetTrailerAsync(Guid movieId, Guid trailerId) 22 | { 23 | // Generate the name from the movie title. 24 | var movie = await _context.Movies 25 | .FirstOrDefaultAsync(m => m.Id == movieId); 26 | 27 | if (movie == null) 28 | { 29 | throw new Exception($"Movie with id {movieId} not found."); 30 | } 31 | 32 | // generate a trailer (byte array) between 50 and 100MB 33 | var random = new Random(); 34 | var generatedByteLength = random.Next(52428800, 104857600); 35 | var generatedBytes = new byte[generatedByteLength]; 36 | random.NextBytes(generatedBytes); 37 | 38 | return new Trailer() 39 | { 40 | Bytes = generatedBytes, 41 | Id = trailerId, 42 | MovieId = movieId, 43 | Name = $"{movie.Title} trailer number {DateTime.UtcNow.Ticks}", 44 | Description = $"{movie.Title} trailer description {DateTime.UtcNow.Ticks}" 45 | }; 46 | } 47 | 48 | public async Task AddTrailer(Guid movieId, Trailer trailerToAdd) 49 | { 50 | // don't do anything: we're just faking this. Simply return the trailer 51 | // after setting the ids 52 | trailerToAdd.MovieId = movieId; 53 | trailerToAdd.Id = Guid.NewGuid(); 54 | return await Task.FromResult(trailerToAdd); 55 | } 56 | 57 | public void Dispose() 58 | { 59 | Dispose(true); 60 | GC.SuppressFinalize(this); 61 | } 62 | 63 | protected virtual void Dispose(bool disposing) 64 | { 65 | if (disposing) 66 | { 67 | if (_context != null) 68 | { 69 | _context.Dispose(); 70 | _context = null; 71 | } 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Starter files/Movies.API/Startup.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.AspNetCore.Mvc.Formatters; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Hosting; 10 | using Microsoft.OpenApi.Models; 11 | using Movies.API.Contexts; 12 | using Movies.API.Services; 13 | using Newtonsoft.Json.Serialization; 14 | using Swashbuckle.AspNetCore.Swagger; 15 | using System; 16 | 17 | namespace Movies.API 18 | { 19 | public class Startup 20 | { 21 | public Startup(IConfiguration configuration) 22 | { 23 | Configuration = configuration; 24 | } 25 | 26 | public IConfiguration Configuration { get; } 27 | 28 | // This method gets called by the runtime. Use this method to add services to the container. 29 | public void ConfigureServices(IServiceCollection services) 30 | { 31 | services.AddControllers(options => 32 | { 33 | // Return a 406 when an unsupported media type was requested 34 | options.ReturnHttpNotAcceptable = true; 35 | 36 | // Add XML formatters 37 | options.OutputFormatters.Add(new XmlSerializerOutputFormatter()); 38 | options.InputFormatters.Add(new XmlSerializerInputFormatter(options)); 39 | 40 | // Set XML as default format instead of JSON - the first formatter in the 41 | // list is the default, so we insert the input/output formatters at 42 | // position 0 43 | //options.OutputFormatters.Insert(0,new XmlSerializerOutputFormatter()); 44 | //options.InputFormatters.Insert(0, new XmlSerializerInputFormatter(options)); 45 | }).AddNewtonsoftJson(setupAction => 46 | { 47 | setupAction.SerializerSettings.ContractResolver = 48 | new CamelCasePropertyNamesContractResolver(); 49 | }); 50 | 51 | // add support for compressing responses (eg gzip) 52 | services.AddResponseCompression(); 53 | 54 | // suppress automatic model state validation when using the 55 | // ApiController attribute (as it will return a 400 Bad Request 56 | // instead of the more correct 422 Unprocessable Entity when 57 | // validation errors are encountered) 58 | services.Configure(options => 59 | { 60 | options.SuppressModelStateInvalidFilter = true; 61 | }); 62 | 63 | // register the DbContext on the container, getting the connection string from 64 | // appSettings (note: use this during development; in a production environment, 65 | // it's better to store the connection string in an environment variable) 66 | var connectionString = Configuration["ConnectionStrings:MoviesDBConnectionString"]; 67 | services.AddDbContext(o => o.UseSqlite(connectionString)); 68 | 69 | services.AddScoped(); 70 | services.AddScoped(); 71 | services.AddScoped(); 72 | 73 | services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); 74 | 75 | services.AddSwaggerGen(c => 76 | { 77 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "Movies API", Version = "v1" }); 78 | }); 79 | } 80 | 81 | 82 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 83 | { 84 | if (env.IsDevelopment()) 85 | { 86 | app.UseDeveloperExceptionPage(); 87 | } 88 | 89 | // use response compression (client should pass through 90 | // Accept-Encoding) 91 | app.UseResponseCompression(); 92 | 93 | // Enable middleware to serve generated Swagger as a JSON endpoint. 94 | app.UseSwagger(); 95 | 96 | // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 97 | // specifying the Swagger JSON endpoint. 98 | app.UseSwaggerUI(c => 99 | { 100 | c.SwaggerEndpoint("swagger/v1/swagger.json", "Movies API (v1)"); 101 | // serve UI at root 102 | c.RoutePrefix = string.Empty; 103 | }); 104 | 105 | app.UseRouting(); 106 | 107 | app.UseAuthorization(); 108 | 109 | app.UseEndpoints(endpoints => 110 | { 111 | endpoints.MapControllers(); 112 | }); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Starter files/Movies.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Starter files/Movies.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information" 5 | } 6 | }, 7 | "AllowedHosts": "*", 8 | "ConnectionStrings": { 9 | "MoviesDBConnectionString": "Data Source=Movies.db;" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Movies.Client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 9.0 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using Movies.Client.Services; 5 | using System; 6 | using System.Net.Http; 7 | using System.Threading.Tasks; 8 | 9 | namespace Movies.Client 10 | { 11 | class Program 12 | { 13 | static async Task Main(string[] args) 14 | { 15 | 16 | using IHost host = CreateHostBuilder(args).Build(); 17 | var serviceProvider = host.Services; 18 | 19 | // For demo purposes: overall catch-all to log any exception that might 20 | // happen to the console & wait for key input afterwards so we can easily 21 | // inspect the issue. 22 | try 23 | { 24 | var logger = host.Services.GetRequiredService>(); 25 | logger.LogInformation("Host created."); 26 | 27 | // Run our IntegrationService containing all samples and 28 | // await this call to ensure the application doesn't 29 | // prematurely exit. 30 | await serviceProvider.GetService().Run(); 31 | } 32 | catch (Exception generalException) 33 | { 34 | // log the exception 35 | var logger = serviceProvider.GetService>(); 36 | logger.LogError(generalException, 37 | "An exception happened while running the integration service."); 38 | } 39 | 40 | Console.ReadKey(); 41 | 42 | await host.RunAsync(); 43 | } 44 | 45 | private static IHostBuilder CreateHostBuilder(string[] args) 46 | { 47 | return Host.CreateDefaultBuilder(args).ConfigureServices( 48 | (serviceCollection) => ConfigureServices(serviceCollection)); 49 | } 50 | 51 | private static void ConfigureServices(IServiceCollection serviceCollection) 52 | { 53 | // add loggers 54 | serviceCollection.AddLogging(configure => configure.AddDebug().AddConsole()); 55 | 56 | // register the integration service on our container with a 57 | // scoped lifetime 58 | 59 | // For the CRUD demos 60 | serviceCollection.AddScoped(); 61 | 62 | // For the partial update demos 63 | // serviceCollection.AddScoped(); 64 | 65 | // For the stream demos 66 | // serviceCollection.AddScoped(); 67 | 68 | // For the cancellation demos 69 | // serviceCollection.AddScoped(); 70 | 71 | // For the HttpClientFactory demos 72 | // serviceCollection.AddScoped(); 73 | 74 | // For the dealing with errors and faults demos 75 | // serviceCollection.AddScoped(); 76 | 77 | // For the custom http handlers demos 78 | // serviceCollection.AddScoped(); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/CRUDService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class CRUDService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/CancellationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class CancellationService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/DealingWithErrorsAndFaultsService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class DealingWithErrorsAndFaultsService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/HttpClientFactoryInstanceManagementService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class HttpClientFactoryInstanceManagementService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/HttpHandlersService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class HttpHandlersService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/IIntegrationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public interface IIntegrationService 9 | { 10 | Task Run(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/PartialUpdateService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class PartialUpdateService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.Client/Services/StreamService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Movies.Client.Services 7 | { 8 | public class StreamService : IIntegrationService 9 | { 10 | public async Task Run() 11 | { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Starter files/Movies.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30717.126 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Movies.Client", "Movies.Client\Movies.Client.csproj", "{C0FA8F85-2A8D-45A4-905C-6665B21E4E91}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Movies.API", "Movies.API\Movies.API.csproj", "{8614CB18-9723-4EC7-8D41-D34BDECAD0ED}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01 Client", "01 Client", "{C2BDCED0-499B-4001-8D36-DFB0DBE624B4}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02 Server", "02 Server", "{CC16F37C-017E-4782-B335-12A2125D09E2}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {C0FA8F85-2A8D-45A4-905C-6665B21E4E91} = {C2BDCED0-499B-4001-8D36-DFB0DBE624B4} 34 | {8614CB18-9723-4EC7-8D41-D34BDECAD0ED} = {CC16F37C-017E-4782-B335-12A2125D09E2} 35 | EndGlobalSection 36 | GlobalSection(ExtensibilityGlobals) = postSolution 37 | SolutionGuid = {CF9D6D81-D749-4D51-AB81-EED468744611} 38 | EndGlobalSection 39 | EndGlobal 40 | --------------------------------------------------------------------------------