Web Application Development Tutorial - Part 8: Authors: Application Layer

About This Tutorial

In this tutorial series, you will build an ABP based web application named Acme.BookStore. This application is used to manage a list of books and their authors. It is developed using the following technologies:

  • Entity Framework Core as the ORM provider.
  • MVC / Razor Pages as the UI Framework.

This tutorial is organized as the following parts;

Download the Source Code

This tutorials has multiple versions based on your UI and Database preferences. We’ve prepared two combinations of the source code to be downloaded:

Introduction

This part explains to create an application layer for the Author entity created before.

IAuthorAppService

We will first create the application service interface and the related DTOs. Create a new interface, named IAuthorAppService, in the Authors namespace (folder) of the Acme.BookStore.Application.Contracts project:

  1. using System;
  2. using System.Threading.Tasks;
  3. using Volo.Abp.Application.Dtos;
  4. using Volo.Abp.Application.Services;
  5. namespace Acme.BookStore.Authors
  6. {
  7. public interface IAuthorAppService : IApplicationService
  8. {
  9. Task<AuthorDto> GetAsync(Guid id);
  10. Task<PagedResultDto<AuthorDto>> GetListAsync(GetAuthorListDto input);
  11. Task<AuthorDto> CreateAsync(CreateAuthorDto input);
  12. Task UpdateAsync(Guid id, UpdateAuthorDto input);
  13. Task DeleteAsync(Guid id);
  14. }
  15. }
  • IApplicationService is a conventional interface that is inherited by all the application services, so the ABP Framework can identify the service.
  • Defined standard methods to perform CRUD operations on the Author entity.
  • PagedResultDto is a pre-defined DTO class in the ABP Framework. It has an Items collection and a TotalCount property to return a paged result.
  • Preferred to return an AuthorDto (for the newly created author) from the CreateAsync method, while it is not used by this application - just to show a different usage.

This interface is using the DTOs defined below (create them for your project).

AuthorDto

  1. using System;
  2. using Volo.Abp.Application.Dtos;
  3. namespace Acme.BookStore.Authors
  4. {
  5. public class AuthorDto : EntityDto<Guid>
  6. {
  7. public string Name { get; set; }
  8. public DateTime BirthDate { get; set; }
  9. public string ShortBio { get; set; }
  10. }
  11. }
  • EntityDto<T> simply has an Id property with the given generic argument. You could create an Id property yourself instead of inheriting the EntityDto<T>.

GetAuthorListDto

  1. using Volo.Abp.Application.Dtos;
  2. namespace Acme.BookStore.Authors
  3. {
  4. public class GetAuthorListDto : PagedAndSortedResultRequestDto
  5. {
  6. public string Filter { get; set; }
  7. }
  8. }
  • Filter is used to search authors. It can be null (or empty string) to get all the authors.
  • PagedAndSortedResultRequestDto has the standard paging and sorting properties: int MaxResultCount, int SkipCount and string Sorting.

ABP Framework has such base DTO classes to simplify and standardize your DTOs. See the DTO documentation for all.

CreateAuthorDto

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace Acme.BookStore.Authors
  4. {
  5. public class CreateAuthorDto
  6. {
  7. [Required]
  8. [StringLength(AuthorConsts.MaxNameLength)]
  9. public string Name { get; set; }
  10. [Required]
  11. public DateTime BirthDate { get; set; }
  12. public string ShortBio { get; set; }
  13. }
  14. }

Data annotation attributes can be used to validate the DTO. See the validation document for details.

UpdateAuthorDto

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. namespace Acme.BookStore.Authors
  4. {
  5. public class UpdateAuthorDto
  6. {
  7. [Required]
  8. [StringLength(AuthorConsts.MaxNameLength)]
  9. public string Name { get; set; }
  10. [Required]
  11. public DateTime BirthDate { get; set; }
  12. public string ShortBio { get; set; }
  13. }
  14. }

We could share (re-use) the same DTO among the create and the update operations. While you can do it, we prefer to create different DTOs for these operations since we see they generally be different by the time. So, code duplication is reasonable here compared to a tightly coupled design.

AuthorAppService

It is time to implement the IAuthorAppService interface. Create a new class, named AuthorAppService in the Authors namespace (folder) of the Acme.BookStore.Application project:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Acme.BookStore.Permissions;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Volo.Abp.Application.Dtos;
  8. namespace Acme.BookStore.Authors
  9. {
  10. [Authorize(BookStorePermissions.Authors.Default)]
  11. public class AuthorAppService : BookStoreAppService, IAuthorAppService
  12. {
  13. private readonly IAuthorRepository _authorRepository;
  14. private readonly AuthorManager _authorManager;
  15. public AuthorAppService(
  16. IAuthorRepository authorRepository,
  17. AuthorManager authorManager)
  18. {
  19. _authorRepository = authorRepository;
  20. _authorManager = authorManager;
  21. }
  22. //...SERVICE METHODS WILL COME HERE...
  23. }
  24. }
  • [Authorize(BookStorePermissions.Authors.Default)] is a declarative way to check a permission (policy) to authorize the current user. See the authorization document for more. BookStorePermissions class will be updated below, don’t worry for the compile error for now.
  • Derived from the BookStoreAppService, which is a simple base class comes with the startup template. It is derived from the standard ApplicationService class.
  • Implemented the IAuthorAppService which was defined above.
  • Injected the IAuthorRepository and AuthorManager to use in the service methods.

Now, we will introduce the service methods one by one. Copy the explained method into the AuthorAppService class.

GetAsync

  1. public async Task<AuthorDto> GetAsync(Guid id)
  2. {
  3. var author = await _authorRepository.GetAsync(id);
  4. return ObjectMapper.Map<Author, AuthorDto>(author);
  5. }

This method simply gets the Author entity by its Id, converts to the AuthorDto using the object to object mapper. This requires to configure the AutoMapper, which will be explained later.

GetListAsync

  1. public async Task<PagedResultDto<AuthorDto>> GetListAsync(GetAuthorListDto input)
  2. {
  3. if (input.Sorting.IsNullOrWhiteSpace())
  4. {
  5. input.Sorting = nameof(Author.Name);
  6. }
  7. var authors = await _authorRepository.GetListAsync(
  8. input.SkipCount,
  9. input.MaxResultCount,
  10. input.Sorting,
  11. input.Filter
  12. );
  13. var totalCount = await AsyncExecuter.CountAsync(
  14. _authorRepository.WhereIf(
  15. !input.Filter.IsNullOrWhiteSpace(),
  16. author => author.Name.Contains(input.Filter)
  17. )
  18. );
  19. return new PagedResultDto<AuthorDto>(
  20. totalCount,
  21. ObjectMapper.Map<List<Author>, List<AuthorDto>>(authors)
  22. );
  23. }
  • Default sorting is “by author name” which is done in the beginning of the method in case of it wasn’t sent by the client.
  • Used the IAuthorRepository.GetListAsync to get a paged, sorted and filtered list of authors from the database. We had implemented it in the previous part of this tutorial. Again, it actually was not needed to create such a method since we could directly query over the repository, but wanted to demonstrate how to create custom repository methods.
  • Directly queried from the AuthorRepository while getting the count of the authors. We preferred to use the AsyncExecuter service which allows us to perform async queries without depending on the EF Core. However, you could depend on the EF Core package and directly use the _authorRepository.WhereIf(...).ToListAsync() method. See the repository document to read the alternative approaches and the discussion.
  • Finally, returning a paged result by mapping the list of Authors to a list of AuthorDtos.

CreateAsync

  1. [Authorize(BookStorePermissions.Authors.Create)]
  2. public async Task<AuthorDto> CreateAsync(CreateAuthorDto input)
  3. {
  4. var author = await _authorManager.CreateAsync(
  5. input.Name,
  6. input.BirthDate,
  7. input.ShortBio
  8. );
  9. await _authorRepository.InsertAsync(author);
  10. return ObjectMapper.Map<Author, AuthorDto>(author);
  11. }
  • CreateAsync requires the BookStorePermissions.Authors.Create permission (in addition to the BookStorePermissions.Authors.Default declared for the AuthorAppService class).
  • Used the AuthorManeger (domain service) to create a new author.
  • Used the IAuthorRepository.InsertAsync to insert the new author to the database.
  • Used the ObjectMapper to return an AuthorDto representing the newly created author.

DDD tip: Some developers may find useful to insert the new entity inside the _authorManager.CreateAsync. We think it is a better design to leave it to the application layer since it better knows when to insert it to the database (maybe it requires additional works on the entity before insert, which would require to an additional update if we perform the insert in the domain service). However, it is completely up to you.

UpdateAsync

  1. [Authorize(BookStorePermissions.Authors.Edit)]
  2. public async Task UpdateAsync(Guid id, UpdateAuthorDto input)
  3. {
  4. var author = await _authorRepository.GetAsync(id);
  5. if (author.Name != input.Name)
  6. {
  7. await _authorManager.ChangeNameAsync(author, input.Name);
  8. }
  9. author.BirthDate = input.BirthDate;
  10. author.ShortBio = input.ShortBio;
  11. await _authorRepository.UpdateAsync(author);
  12. }
  • UpdateAsync requires the additional BookStorePermissions.Authors.Edit permission.
  • Used the IAuthorRepository.GetAsync to get the author entity from the database. GetAsync throws EntityNotFoundException if there is no author with the given id, which results a 404 HTTP status code in a web application. It is a good practice to always bring the entity on an update operation.
  • Used the AuthorManager.ChangeNameAsync (domain service method) to change the author name if it was requested to change by the client.
  • Directly updated the BirthDate and ShortBio since there is not any business rule to change these properties, they accept any value.
  • Finally, called the IAuthorRepository.UpdateAsync method to update the entity on the database.

EF Core tip: Entity Framework Core has a change tracking system and automatically saves any change to an entity at the end of the unit of work (You can simply think that the ABP Framework automatically calls SaveChanges at the end of the method). So, it will work as expected even if you don’t call the _authorRepository.UpdateAsync(...) in the end of the method. If you don’t consider to change the EF Core later, you can just remove this line.

DeleteAsync

  1. [Authorize(BookStorePermissions.Authors.Delete)]
  2. public async Task DeleteAsync(Guid id)
  3. {
  4. await _authorRepository.DeleteAsync(id);
  5. }
  • DeleteAsync requires the additional BookStorePermissions.Authors.Delete permission.
  • It simply uses the DeleteAsync method of the repository.

Permission Definitions

You can’t compile the code since it is expecting some constants declared in the BookStorePermissions class.

Open the BookStorePermissions class inside the Acme.BookStore.Application.Contracts project (in the Permissions folder) and change the content as shown below:

  1. namespace Acme.BookStore.Permissions
  2. {
  3. public static class BookStorePermissions
  4. {
  5. public const string GroupName = "BookStore";
  6. public static class Books
  7. {
  8. public const string Default = GroupName + ".Books";
  9. public const string Create = Default + ".Create";
  10. public const string Edit = Default + ".Edit";
  11. public const string Delete = Default + ".Delete";
  12. }
  13. // *** ADDED a NEW NESTED CLASS ***
  14. public static class Authors
  15. {
  16. public const string Default = GroupName + ".Authors";
  17. public const string Create = Default + ".Create";
  18. public const string Edit = Default + ".Edit";
  19. public const string Delete = Default + ".Delete";
  20. }
  21. }
  22. }

Then open the BookStorePermissionDefinitionProvider in the same project and add the following lines at the end of the Define method:

  1. var authorsPermission = bookStoreGroup.AddPermission(
  2. BookStorePermissions.Authors.Default, L("Permission:Authors"));
  3. authorsPermission.AddChild(
  4. BookStorePermissions.Authors.Create, L("Permission:Authors.Create"));
  5. authorsPermission.AddChild(
  6. BookStorePermissions.Authors.Edit, L("Permission:Authors.Edit"));
  7. authorsPermission.AddChild(
  8. BookStorePermissions.Authors.Delete, L("Permission:Authors.Delete"));

Finally, add the following entries to the Localization/BookStore/en.json inside the Acme.BookStore.Domain.Shared project, to localize the permission names:

  1. "Permission:Authors": "Author Management",
  2. "Permission:Authors.Create": "Creating new authors",
  3. "Permission:Authors.Edit": "Editing the authors",
  4. "Permission:Authors.Delete": "Deleting the authors"

Object to Object Mapping

AuthorAppService is using the ObjectMapper to convert the Author objects to AuthorDto objects. So, we need to define this mapping in the AutoMapper configuration.

Open the BookStoreApplicationAutoMapperProfile class inside the Acme.BookStore.Application project and add the following line to the constructor:

  1. CreateMap<Author, AuthorDto>();

Data Seeder

As just done for the books before, it would be good to have some initial author entities in the database. This will be good while running the application first time, but also it is very useful for the automated tests.

Open the BookStoreDataSeederContributor in the Acme.BookStore.Domain project and change the file content with the code below:

  1. using System;
  2. using System.Threading.Tasks;
  3. using Acme.BookStore.Authors;
  4. using Acme.BookStore.Books;
  5. using Volo.Abp.Data;
  6. using Volo.Abp.DependencyInjection;
  7. using Volo.Abp.Domain.Repositories;
  8. namespace Acme.BookStore
  9. {
  10. public class BookStoreDataSeederContributor
  11. : IDataSeedContributor, ITransientDependency
  12. {
  13. private readonly IRepository<Book, Guid> _bookRepository;
  14. private readonly IAuthorRepository _authorRepository;
  15. private readonly AuthorManager _authorManager;
  16. public BookStoreDataSeederContributor(
  17. IRepository<Book, Guid> bookRepository,
  18. IAuthorRepository authorRepository,
  19. AuthorManager authorManager)
  20. {
  21. _bookRepository = bookRepository;
  22. _authorRepository = authorRepository;
  23. _authorManager = authorManager;
  24. }
  25. public async Task SeedAsync(DataSeedContext context)
  26. {
  27. if (await _bookRepository.GetCountAsync() <= 0)
  28. {
  29. await _bookRepository.InsertAsync(
  30. new Book
  31. {
  32. Name = "1984",
  33. Type = BookType.Dystopia,
  34. PublishDate = new DateTime(1949, 6, 8),
  35. Price = 19.84f
  36. },
  37. autoSave: true
  38. );
  39. await _bookRepository.InsertAsync(
  40. new Book
  41. {
  42. Name = "The Hitchhiker's Guide to the Galaxy",
  43. Type = BookType.ScienceFiction,
  44. PublishDate = new DateTime(1995, 9, 27),
  45. Price = 42.0f
  46. },
  47. autoSave: true
  48. );
  49. }
  50. // ADDED SEED DATA FOR AUTHORS
  51. if (await _authorRepository.GetCountAsync() <= 0)
  52. {
  53. await _authorRepository.InsertAsync(
  54. await _authorManager.CreateAsync(
  55. "George Orwell",
  56. new DateTime(1903, 06, 25),
  57. "Orwell produced literary criticism and poetry, fiction and polemical journalism; and is best known for the allegorical novella Animal Farm (1945) and the dystopian novel Nineteen Eighty-Four (1949)."
  58. )
  59. );
  60. await _authorRepository.InsertAsync(
  61. await _authorManager.CreateAsync(
  62. "Douglas Adams",
  63. new DateTime(1952, 03, 11),
  64. "Douglas Adams was an English author, screenwriter, essayist, humorist, satirist and dramatist. Adams was an advocate for environmentalism and conservation, a lover of fast cars, technological innovation and the Apple Macintosh, and a self-proclaimed 'radical atheist'."
  65. )
  66. );
  67. }
  68. }
  69. }
  70. }

You can now run the .DbMigrator console application to migrate the database schema and seed the initial data.

Testing the Author Application Service

Finally, we can write some tests for the IAuthorAppService. Add a new class, named AuthorAppService_Tests in the Authors namespace (folder) of the Acme.BookStore.Application.Tests project:

  1. using System;
  2. using System.Threading.Tasks;
  3. using Shouldly;
  4. using Xunit;
  5. namespace Acme.BookStore.Authors
  6. {
  7. public class AuthorAppService_Tests : BookStoreApplicationTestBase
  8. {
  9. private readonly IAuthorAppService _authorAppService;
  10. public AuthorAppService_Tests()
  11. {
  12. _authorAppService = GetRequiredService<IAuthorAppService>();
  13. }
  14. [Fact]
  15. public async Task Should_Get_All_Authors_Without_Any_Filter()
  16. {
  17. var result = await _authorAppService.GetListAsync(new GetAuthorListDto());
  18. result.TotalCount.ShouldBeGreaterThanOrEqualTo(2);
  19. result.Items.ShouldContain(author => author.Name == "George Orwell");
  20. result.Items.ShouldContain(author => author.Name == "Douglas Adams");
  21. }
  22. [Fact]
  23. public async Task Should_Get_Filtered_Authors()
  24. {
  25. var result = await _authorAppService.GetListAsync(
  26. new GetAuthorListDto {Filter = "George"});
  27. result.TotalCount.ShouldBeGreaterThanOrEqualTo(1);
  28. result.Items.ShouldContain(author => author.Name == "George Orwell");
  29. result.Items.ShouldNotContain(author => author.Name == "Douglas Adams");
  30. }
  31. [Fact]
  32. public async Task Should_Create_A_New_Author()
  33. {
  34. var authorDto = await _authorAppService.CreateAsync(
  35. new CreateAuthorDto
  36. {
  37. Name = "Edward Bellamy",
  38. BirthDate = new DateTime(1850, 05, 22),
  39. ShortBio = "Edward Bellamy was an American author..."
  40. }
  41. );
  42. authorDto.Id.ShouldNotBe(Guid.Empty);
  43. authorDto.Name.ShouldBe("Edward Bellamy");
  44. }
  45. [Fact]
  46. public async Task Should_Not_Allow_To_Create_Duplicate_Author()
  47. {
  48. await Assert.ThrowsAsync<AuthorAlreadyExistsException>(async () =>
  49. {
  50. await _authorAppService.CreateAsync(
  51. new CreateAuthorDto
  52. {
  53. Name = "Douglas Adams",
  54. BirthDate = DateTime.Now,
  55. ShortBio = "..."
  56. }
  57. );
  58. });
  59. }
  60. //TODO: Test other methods...
  61. }
  62. }

Created some tests for the application service methods, which should be clear to understand.

The Next Part

See the next part of this tutorial.