title
stringlengths
3
46
content
stringlengths
0
1.6k
21:1425
[Display(Name = `package infos`)]
21:1426
[StringLength(128, MinimumLength = 10), Required]
21:1427
public string Description { get; set; }= null!;
21:1428
[Display(Name = `price`)]
21:1429
[Range(0, 100000)]
21:1430
public decimal Price { get; set; }
21:1431
[Display(Name = `duration in days`)]
21:1432
[Range(1, 90)]
21:1433
public int DurationInDays { get; set; }
21:1434
[Display(Name = `available from`), Required]
21:1435
public DateTime? StartValidityDate { get; set; }
21:1436
[Display(Name = `available to`), Required]
21:1437
public DateTime? EndValidityDate { get; set; }
21:1438
[Display(Name = `destination`)]
21:1439
public int DestinationId { get; set; }
21:1440
21:1441
The Commands folder contains all commands. As an example, let’s have a look at the command used to modify packages:
21:1442
public class UpdatePackageCommand: ICommand
21:1443
{
21:1444
public UpdatePackageCommand(IPackageFullEditDTO updates)
21:1445
{
21:1446
Updates = updates;
21:1447
}
21:1448
public IPackageFullEditDTO Updates { get; private set; }
21:1449
}
21:1450
21:1451
Its constructor must be invoked with an implementation of the IPackageFullEditDTO DTO interface, which, in our case, is the edit ViewModel we described previously. Command handlers are placed in the Handlers folder. It is worth analyzing the command that updates packages:
21:1452
public class UpdatePackageCommandHandler(IPackageRepository repo, IEventMediator mediator)
21:1453
21:1454
Its principal constructor has automatically injected the IPackageRepository repository and an IEventMediator instance needed to trigger event handlers. The following code also shows the implementation of the standard HandleAsync command handler method:
21:1455
public async Task HandleAsync(UpdatePackageCommand command)
21:1456
{
21:1457
bool done = false;
21:1458
IPackage model;
21:1459
while (!done)
21:1460
{
21:1461
try
21:1462
{
21:1463
model = await repo.GetAsync(command.Updates.Id);
21:1464
if (model == null) return;
21:1465
model.FullUpdate(command.Updates);
21:1466
await mediator.TriggerEvents(model.DomainEvents);
21:1467
await repo.UnitOfWork.SaveEntitiesAsync();
21:1468
done = true;
21:1469
}
21:1470
catch (DbUpdateConcurrencyException)
21:1471
{
21:1472
// add some logging here
21:1473
}
21:1474
}
21:1475
}
21:1476
21:1477
HandleAsync uses the repository to get an instance of the entity to modify. If the entity is not found (it has been deleted), the commands stop its execution. Otherwise, all changes are passed to the retrieved aggregate. Immediately after the update, all events contained in the aggregate are triggered. In particular, if the price has changed, the event handler associated with the price change is executed. The concurrency check declared with the [ConcurrencyCheck] attribute on the EntityVersion property of the Package entity ensures that the package version is updated properly (by incrementing its previous version number by 1), as well as that the price-changed event is passed the right version numbers.
21:1478
Also, event handlers are placed in the Handlers folder. As an example, let’s have a look at the price-changed event handler:
21:1479
public class PackagePriceChangedEventHandler( IPackageEventRepository repo) :
21:1481
{
21:1482
public Task HandleAsync(PackagePriceChangedEvent ev)
21:1483
{
21:1484
repo.New(PackageEventType.CostChanged, ev.PackageId,
21:1485
ev.OldVersion, ev.NewVersion, ev.NewPrice);
21:1486
return Task.CompletedTask;
21:1487
}
21:1488
}
21:1489
21:1490
The principal constructor has automatically injected the IPackageEventRepository repository, which handles the database table and all the events to send to other applications. The HandleAsync implementation simply calls the repository method, which adds a new IPackageEvent to a queue of events to be sent to other microservices.
21:1491
The IPackageEvent records should be extracted by the above queue and sent to all interested microservices by a parallel task, which is not implemented in the GitHub code associated with this section. It can be implemented as a hosted service (thus inheriting from the BackgroundService class) and then added to the DI engine with a call such as builder.Services.AddHostedService<MyHostedService>(), as detailed in the Using generic hosts subsection of Chapter 11, Applying a Microservice Architecture to Your Enterprise Application.
21:1492
We are almost finished! Just the presentation layer is missing, which, in the case of an MVC-based application, consists of controllers and views. The next subsection defines both controllers and views needed by our microservice.
21:1493
Defining controllers and views
21:1494
We need to add two more controllers to the one automatically scaffolded by Visual Studio – namely, AccountController, which takes care of user login/logout and registration, and ManagePackageController, which handles all package-related operations. It is enough to right-click on the Controllers folder and then select Add | Controller. Then, choose the controller name and select the empty MVC controller to avoid the possibility of Visual Studio scaffolding code you don’t need.
21:1495
21:1496
Figure 21.27: Adding AccountController
21:1497
It is worth pointing out that Visual Studio can automatically scaffold all of the UI for managing users if one selects to automatically add authentication when the MVC project is created. However, scaffolded code doesn’t respect any layer or onions architecture: it inserts everything in the MVC project. That’s why we decided to proceed manually.
21:1498
For simplicity, our implementation of AccountController just has login and logout methods, so you can log in just with the initial administrator user. However, you can add further action methods that use the UserManager class to define, update, and delete users.
21:1499
21:1500
Figure 21.28: Login, logout, and authentication
21:1501
The UserManager class can be provided through DI, as shown here:
21:1502
public AccountController(
21:1503
UserManager<IdentityUser<int>> userManager,
21:1504
SignInManager<IdentityUser<int>> signInManager) : Controller
21:1505
21:1506
SignInManager takes care of login/logout operations. The Logout action method is quite simple and is shown here (for more information on authentication in ASP.NET Core, please refer to the Defining the ASP.NET Core pipeline section of Chapter 17, Presenting ASP.NET Core):
21:1507
[HttpPost]
21:1508
public async Task<IActionResult> Logout()
21:1509
{
21:1510
await signInManager.SignOutAsync();
21:1511
return RedirectToAction(nameof(HomeController.Index), `Home`);
21:1512
}
21:1513
21:1514
It just calls the signInManager.SignOutAsync method and then redirects the browser to the home page. To avoid it being called by clicking a link, it is decorated with HttpPost, so it can only be invoked via a form submit.
21:1515
21:1516
All requests that cause modifications must never use a GET verb; otherwise, someone might erroneously trigger those actions either by clicking a link or by writing the wrong URL in the browser. An action triggered by GET might also be exploited by a phishing website that might adequately “camouflage” a link that triggers a dangerous GET action. The GET verb should be used just for retrieving information.
21:1517
21:1518
Login, on the other hand, requires two action methods. The first one is invoked via GET and shows the login form, where the user must place their username and password. It is shown here:
21:1519
[HttpGet]
21:1520
public async Task<IActionResult> Login(string? returnUrl = null)
21:1521
{
21:1522
// Clear the existing external cookie
21:1523
//to ensure a clean login process
21:1524
await HttpContext
21:1525
.SignOutAsync(IdentityConstants.ExternalScheme);