diff --git a/docs/en/Tutorials/Part-1.md b/docs/en/Tutorials/Part-1.md index 53745f9b59..c74f7d8c85 100644 --- a/docs/en/Tutorials/Part-1.md +++ b/docs/en/Tutorials/Part-1.md @@ -1,4 +1,4 @@ -# ASP.NET Core {{UI_Value}} Tutorial - Part 1 +# Web Application Development Tutorial - Part 1: Creating the Server Side ````json //[doc-params] { @@ -29,10 +29,11 @@ In this tutorial series, you will build an ABP based web application named `Acme This tutorial is organized as the following parts; -- **Part-1: Creating the project and book list page (this part)** -- [Part-2: Creating, updating and deleting books](part-2.md) -- [Part-3: Integration tests](part-3.md) -- [Part-4: Authorization](Part-4.md) +- **Part 1: Creating the server side (this part)** +- [Part 2: The book list page](Part-2.md) +- [Part 3: Creating, updating and deleting books](Part-3.md) +- [Part 4: Integration tests](Part-4.md) +- [Part 5: Authorization](Part-5.md) ### Source Code @@ -490,538 +491,6 @@ If you try to execute the `[GET] /api/app/book` API to get a list of books, the That's pretty cool since we haven't written a single line of code to create the API controller, but now we have a fully working REST API! -{{if UI == "MVC"}} +## The Next Part -## Dynamic JavaScript Proxies - -It's common to call the HTTP API endpoints via AJAX from the **JavaScript** side. You can use `$.ajax` or another tool to call the endpoints. However, ABP offers a better way. - -ABP **dynamically** creates **[JavaScript Proxies](../UI/AspNetCore/)** for all API endpoints. So, you can use any **endpoint** just like calling a **JavaScript function**. - -### Testing in Developer Console of the Browser - -You can easily test the JavaScript proxies using your favorite browser's **Developer Console**. Run the application, open your browser's **developer tools** (*shortcut is generally F12*), switch to the **Console** tab, type the following code and press enter: - -````js -acme.bookStore.books.book.getList({}).done(function (result) { console.log(result); }); -```` - -* `acme.bookStore.books` is the namespace of the `BookAppService` converted to [camelCase](https://en.wikipedia.org/wiki/Camel_case). -* `book` is the conventional name for the `BookAppService` (removed `AppService` postfix and converted to camelCase). -* `getList` is the conventional name for the `GetListAsync` method defined in the `CrudAppService` base class (removed `Async` postfix and converted to camelCase). -* `{}` argument is used to send an empty object to the `GetListAsync` method which normally expects an object of type `PagedAndSortedResultRequestDto` that is used to send paging and sorting options to the server (all properties are optional with default values, so you can send an empty object). -* `getList` function returns a `promise`. You can pass a callback to the `then` (or `done`) function to get the result returned from the server. - -Running this code produces the following output: - -![bookstore-javascript-proxy-console](images/bookstore-javascript-proxy-console.png) - -You can see the **book list** returned from the server. You can also check the **network** tab of the developer tools to see the client to server communication: - -![bookstore-getlist-result-network](images/bookstore-getlist-result-network.png) - -Let's **create a new book** using the `create` function: - -````js -acme.bookStore.books.book.create({ - name: 'Foundation', - type: 7, - publishDate: '1951-05-24', - price: 21.5 - }).then(function (result) { - console.log('successfully created the book with id: ' + result.id); - }); -```` - -You should see a message in the console something like that: - -````text -successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246 -```` - -Check the `Books` table in the database to see the new book row. You can try `get`, `update` and `delete` functions yourself. - -We will use these dynamic proxy functions in the next sections to communicate to the server. - -## Create a Books Page - -It's time to create something visible and usable! Instead of classic MVC, we will use the [Razor Pages UI](https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start) approach which is recommended by Microsoft. - -Create `Books` folder under the `Pages` folder of the `Acme.BookStore.Web` project. Add a new Razor Page by right clicking the Books folder then selecting **Add > Razor Page** menu item. Name it as `Index`: - -![bookstore-add-index-page](./images/bookstore-add-index-page-v2.png) - -Open the `Index.cshtml` and change the whole content as shown below: - -````html -@page -@using Acme.BookStore.Web.Pages.Books -@model IndexModel - -

Books

-```` - -`Index.cshtml.cs` content should be like that: - -```csharp -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace Acme.BookStore.Web.Pages.Books -{ - public class IndexModel : PageModel - { - public void OnGet() - { - - } - } -} -``` - -### Add Books Page to the Main Menu - -Open the `BookStoreMenuContributor` class in the `Menus` folder and add the following code to the end of the `ConfigureMainMenuAsync` method: - -````csharp -context.Menu.AddItem( - new ApplicationMenuItem( - "BooksStore", - l["Menu:BookStore"], - icon: "fa fa-book" - ).AddItem( - new ApplicationMenuItem( - "BooksStore.Books", - l["Menu:Books"], - url: "/Books" - ) - ) -); -```` - -{{end}} - -### Localization - -Localization texts are located under the `Localization/BookStore` folder of the `Acme.BookStore.Domain.Shared` project: - -![bookstore-localization-files](./images/bookstore-localization-files-v2.png) - -Open the `en.json` (*the English translations*) file and change the content as below: - -````json -{ - "Culture": "en", - "Texts": { - "Menu:Home": "Home", - "Welcome": "Welcome", - "LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information, visit abp.io.", - "Menu:BookStore": "Book Store", - "Menu:Books": "Books", - "Actions": "Actions", - "Edit": "Edit", - "PublishDate": "Publish date", - "NewBook": "New book", - "Name": "Name", - "Type": "Type", - "Price": "Price", - "CreationTime": "Creation time", - "AreYouSureToDelete": "Are you sure you want to delete this item?", - "Enum:BookType:0": "Undefined", - "Enum:BookType:1": "Adventure", - "Enum:BookType:2": "Biography", - "Enum:BookType:3": "Dystopia", - "Enum:BookType:4": "Fantastic", - "Enum:BookType:5": "Horror", - "Enum:BookType:6": "Science", - "Enum:BookType:7": "Science fiction", - "Enum:BookType:8": "Poetry" - } -} -```` - -* Localization key names are arbitrary. You can set any name. We prefer some conventions for specific text types; - * Add `Menu:` prefix for menu items. - * Use `Enum::` naming convention to localize the enum members. When you do it like that, ABP can automatically localize the enums in some proper cases. - -If a text is not defined in the localization file, it **fallbacks** to the localization key (as ASP.NET Core's standard behavior). - -> ABP's localization system is built on [ASP.NET Core's standard localization](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization) system and extends it in many ways. See the [localization document](../Localization.md) for details. - -{{if UI == "MVC"}} - -Run the project, login to the application with the username `admin` and the password `1q2w3E*` and see the new menu item has been added to the main menu: - -![bookstore-menu-items](./images/bookstore-new-menu-item.png) - -When you click to the Books menu item under the Book Store parent, you are being redirected to the new empty Books Page. - -### Book List - -We will use the [Datatables.net](https://datatables.net/) jQuery library to show the book list. Datatables library completely work via AJAX, it is fast, popular and provides a good user experience. - -> Datatables library is configured in the startup template, so you can directly use it in any page without including any style or script file to your page. - -#### Index.cshtml - -Change the `Pages/Books/Index.cshtml` as following: - -````html -@page -@using Acme.BookStore.Localization -@using Acme.BookStore.Web.Pages.Books -@using Microsoft.Extensions.Localization -@model IndexModel -@inject IStringLocalizer L -@section scripts -{ - -} - - -

@L["Books"]

-
- - - -
-```` - -* `abp-script` [tag helper](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro) is used to add external **scripts** to the page. It has many additional features compared to standard `script` tag. It handles **minification** and **versioning**. See the [bundling & minification document](../UI/AspNetCore/Bundling-Minification.md) for details. -* `abp-card` is a tag helper for Twitter Bootstrap's [card component](https://getbootstrap.com/docs/4.5/components/card/). There are other useful tag helpers provided by the ABP Framework to easily use most of the [bootstrap](https://getbootstrap.com/) components. You could use the regular HTML tags instead of these tag helpers, but using tag helpers reduces HTML code and prevents errors by help the of IntelliSense and compile time type checking. Further information, see the [tag helpers](../UI/AspNetCore/Tag-Helpers/Index.md) document. - -#### Index.js - -Create an `Index.js` file under the `Pages/Books` folder: - -![bookstore-index-js-file](./images/bookstore-index-js-file-v3.png) - -The content of the file is shown below: - -````js -$(function () { - var l = abp.localization.getResource('BookStore'); - - var dataTable = $('#BooksTable').DataTable( - abp.libs.datatables.normalizeConfiguration({ - serverSide: true, - paging: true, - order: [[1, "asc"]], - searching: false, - scrollX: true, - ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), - columnDefs: [ - { - title: l('Name'), - data: "name" - }, - { - title: l('Type'), - data: "type", - render: function (data) { - return l('Enum:BookType:' + data); - } - }, - { - title: l('PublishDate'), - data: "publishDate", - render: function (data) { - return luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }).toLocaleString(); - } - }, - { - title: l('Price'), - data: "price" - }, - { - title: l('CreationTime'), data: "creationTime", - render: function (data) { - return luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }).toLocaleString(luxon.DateTime.DATETIME_SHORT); - } - } - ] - }) - ); -}); -```` - -* `abp.localization.getResource` gets a function that is used to localize text using the same JSON file defined in the server side. In this way, you can share the localization values with the client side. -* `abp.libs.datatables.normalizeConfiguration` is a helper function defined by the ABP Framework. There's no requirement to use it, but it simplifies the [Datatables](https://datatables.net/) configuration by providing conventional default values for missing options. -* `abp.libs.datatables.createAjax` is another helper function to adapt ABP's dynamic JavaScript API proxies to [Datatable](https://datatables.net/)'s expected parameter format -* `acme.bookStore.books.book.getList` is the dynamic JavaScript proxy function introduced before. -* [luxon](https://moment.github.io/luxon/) library is also a standard library that is pre-configured in the solution, so you can use to perform date/time operations easily. - -> See [Datatables documentation](https://datatables.net/manual/) for all configuration options. - -## Run the Final Application - -You can run the application! The final UI of this part is shown below: - -![Book list](images/bookstore-book-list-3.png) - -This is a fully working, server side paged, sorted and localized table of books. - -{{end}} - -{{if UI == "NG"}} - -## Angular UI Development -### Create the books page - -It's time to create something visible and usable! There are some tools that we will use when developing ABP Angular frontend application: - -- [Angular CLI](https://angular.io/cli) will be used to create modules, components and services. -- [Ng Bootstrap](https://ng-bootstrap.github.io/#/home) will be used as the UI component library. -- [ngx-datatable](https://swimlane.gitbook.io/ngx-datatable/) will be used as the datatable library. -- [Visual Studio Code](https://code.visualstudio.com/) will be used as the code editor (you can use your favorite editor). - -### Install NPM packages - -Open a new command line interface (terminal window) and go to your `angular` folder and then run `yarn` command to install NPM packages: - -```bash -yarn -``` - -### BookModule - -Run the following command line to create a new module, named `BookModule`: - -```bash -yarn ng generate module book --routing true -``` - -![Generating books module](./images/bookstore-creating-book-module-terminal.png) - -### Routing - -Open the `app-routing.module.ts` file in `src\app` folder and add a route as shown below: - -```js -const routes: Routes = [ -// ... -// added a new route to the routes array - { - path: 'books', - loadChildren: () => import('./book/book.module').then(m => m.BookModule) - } -] -``` - -* We added a lazy-loaded route. See the [Lazy-Loading Feature Modules](https://angular.io/guide/lazy-loading-ngmodules#lazy-loading-feature-modules). - -Open the `route.provider.ts` file in `src\app` folder and replace the content as below: - -```js -import { RoutesService, eLayoutType } from '@abp/ng.core'; -import { APP_INITIALIZER } from '@angular/core'; - -export const APP_ROUTE_PROVIDER = [ - { provide: APP_INITIALIZER, useFactory: configureRoutes, deps: [RoutesService], multi: true }, -]; - -function configureRoutes(routes: RoutesService) { - return () => { - routes.add([ - //... - // added below element - { - path: '/books', - name: '::Menu:Books', - iconClass: 'fas fa-book', - order: 101, - layout: eLayoutType.application, - }, - ]); - }; -} -``` - -* We added a new route element to show a navigation element labeled "Books" on the menu. - * `path` is the URL of the route. - * `name` is the menu item name. A Localization key can be passed. - * `iconClass` is the icon of the menu item. - * `order` is the order of the menu item. We define 101 to show the route after the "Administration" item. - * `layout` is the layout of the BooksModule's routes. `eLayoutType.application`, `eLayoutType.account` or `eLayoutType.empty` can be defined. - -For more information, see the [RoutesService document](https://docs.abp.io/en/abp/latest/UI/Angular/Modifying-the-Menu.md#via-routesservice). - -#### Book List Component - -Run the command below on the terminal in the root folder to generate a new component, named book-list: - -```bash -yarn ng generate component book/book-list -``` - -![Creating books list](./images/bookstore-creating-book-list-terminal.png) - -Open `book.module.ts` file in the `app\book` folder and replace the content as below: - -```js -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { BookRoutingModule } from './book-routing.module'; -import { BookListComponent } from './book-list/book-list.component'; -import { SharedModule } from '../shared/shared.module'; //<== added this line ==> - -@NgModule({ - declarations: [BookListComponent], - imports: [ - CommonModule, - BookRoutingModule, - SharedModule, //<== added this line ==> - ], -}) -export class BookModule {} -``` - -* We imported `SharedModule` and added to `imports` array. - -Open `book-routing.module.ts` file in the `app\book` folder and replace the content as below: - -```js -import { NgModule } from '@angular/core'; -import { Routes, RouterModule } from '@angular/router'; -import { BookListComponent } from './book-list/book-list.component'; // <== added this line ==> - -// <== replaced routes ==> -const routes: Routes = [ - { - path: '', - component: BookListComponent, - }, -]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule] -}) -export class BookRoutingModule { } -``` - -* We imported `BookListComponent` and replaced `routes` const. - -Run `yarn start` and wait for Angular to serve the application: - -```bash -yarn start -``` - -Open the browser and navigate to http://localhost:4200/books. We'll see **book-list works!** text on the books page: - -![Initial book list page](./images/bookstore-initial-book-list-page.png) - -### Generate Proxies - -ABP CLI provides `generate-proxy` command that generates client proxies for your HTTP APIs to make easy to consume your services from the client side. Before running generate-proxy command, your host must be up and running. See the [CLI documentation](../CLI.md) - -Run the following command in the `angular` folder: - -```bash -abp generate-proxy --module app -``` - -![Generate proxy command](./images/generate-proxy-command.png) - -The generated files looks like below: - -![Generated files](./images/generated-proxies.png) - -### BookListComponent - -Open the `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: - -```js -import { ListService, PagedResultDto } from '@abp/ng.core'; -import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from '../models'; -import { BookService } from '../services'; - -@Component({ - selector: 'app-book-list', - templateUrl: './book-list.component.html', - styleUrls: ['./book-list.component.scss'], - providers: [ListService], -}) -export class BookListComponent implements OnInit { - book = { items: [], totalCount: 0 } as PagedResultDto; - - booksType = BookType; - - constructor(public readonly list: ListService, private bookService: BookService) {} - - ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); - - this.list.hookToQuery(bookStreamCreator).subscribe((response) => { - this.book = response; - }); - } -} -``` - -* We imported and injected the generated `BookService`. -* We implemented the [ListService](https://docs.abp.io/en/abp/latest/UI/Angular/List-Service) that is a utility service to provide easy pagination, sorting, and search implementation. - -Open the `book-list.component.html` file in `app\book\book-list` folder and replace the content as below: - -```html -
-
-
-
-
- {%{{{ '::Menu:Books' | abpLocalization }}}%} -
-
-
-
-
-
- - - - - {%{{{ booksType[row.type] }}}%} - - - - - {%{{{ row.publishDate | date }}}%} - - - - - {%{{{ row.price | currency }}}%} - - - -
-
-``` - -* We added HTML code of book list page. - -Now you can see the final result on your browser: - -![Book list final result](./images/bookstore-book-list.png) - -The file system structure of the project: - -![Book list final result](./images/bookstore-angular-file-tree.png) - -In this tutorial we have applied the rules of official [Angular Style Guide](https://angular.io/guide/styleguide#file-tree). - -{{end}} - -## Next Part - -See the [part 2](Part-2.md) for creating, updating and deleting books. +See the [next part](Part-2.md) of this tutorial. diff --git a/docs/en/Tutorials/Part-2.md b/docs/en/Tutorials/Part-2.md index c744d85229..1a3c2db7fd 100644 --- a/docs/en/Tutorials/Part-2.md +++ b/docs/en/Tutorials/Part-2.md @@ -1,11 +1,10 @@ -# ASP.NET Core {{UI_Value}} Tutorial - Part 2 +# Web Application Development Tutorial - Part 2: The Book List Page ````json //[doc-params] { "UI": ["MVC","NG"] } ```` - {{ if UI == "MVC" DB="ef" @@ -30,10 +29,11 @@ In this tutorial series, you will build an ABP based web application named `Acme This tutorial is organized as the following parts; -- [Part I: Creating the project and book list page](part-1.md) -- **Part-2: Creating, updating and deleting books (this part)** -- [Part-3: Integration tests](part-3.md) -- [Part-4: Authorization](Part-4.md) +- [Part 1: Creating the server side](Part-1.md) +- **Part 2: The book list page (this part)** +- [Part 3: Creating, updating and deleting books](Part-3.md) +- [Part 4: Integration tests](Part-4.md) +- [Part 5: Authorization](Part-5.md) ### Source Code @@ -41,113 +41,178 @@ You can find the completed solution on {{if UI == "MVC"}}[the GitHub repository] {{if UI == "MVC"}} -## Creating a New Book +## Dynamic JavaScript Proxies -In this section, you will learn how to create a new modal dialog form to create a new book. The modal dialog will look like in the image below: +It's common to call the HTTP API endpoints via AJAX from the **JavaScript** side. You can use `$.ajax` or another tool to call the endpoints. However, ABP offers a better way. -![bookstore-create-dialog](./images/bookstore-create-dialog-2.png) +ABP **dynamically** creates **[JavaScript Proxies](../UI/AspNetCore/)** for all API endpoints. So, you can use any **endpoint** just like calling a **JavaScript function**. -### Create the Modal Form +### Testing in Developer Console of the Browser -Create a new razor page, named `CreateModal.cshtml` under the `Pages/Books` folder of the `Acme.BookStore.Web` project. +You can easily test the JavaScript proxies using your favorite browser's **Developer Console**. Run the application, open your browser's **developer tools** (*shortcut is generally F12*), switch to the **Console** tab, type the following code and press enter: -![bookstore-add-create-dialog](./images/bookstore-add-create-dialog-v2.png) +````js +acme.bookStore.books.book.getList({}).done(function (result) { console.log(result); }); +```` -#### CreateModal.cshtml.cs +* `acme.bookStore.books` is the namespace of the `BookAppService` converted to [camelCase](https://en.wikipedia.org/wiki/Camel_case). +* `book` is the conventional name for the `BookAppService` (removed `AppService` postfix and converted to camelCase). +* `getList` is the conventional name for the `GetListAsync` method defined in the `CrudAppService` base class (removed `Async` postfix and converted to camelCase). +* `{}` argument is used to send an empty object to the `GetListAsync` method which normally expects an object of type `PagedAndSortedResultRequestDto` that is used to send paging and sorting options to the server (all properties are optional with default values, so you can send an empty object). +* `getList` function returns a `promise`. You can pass a callback to the `then` (or `done`) function to get the result returned from the server. -Open the `CreateModal.cshtml.cs` file (`CreateModalModel` class) and replace with the following code: +Running this code produces the following output: -````C# -using System.Threading.Tasks; -using Acme.BookStore.Books; -using Microsoft.AspNetCore.Mvc; +![bookstore-javascript-proxy-console](images/bookstore-javascript-proxy-console.png) -namespace Acme.BookStore.Web.Pages.Books -{ - public class CreateModalModel : BookStorePageModel - { - [BindProperty] - public CreateUpdateBookDto Book { get; set; } +You can see the **book list** returned from the server. You can also check the **network** tab of the developer tools to see the client to server communication: - private readonly IBookAppService _bookAppService; +![bookstore-getlist-result-network](images/bookstore-getlist-result-network.png) - public CreateModalModel(IBookAppService bookAppService) - { - _bookAppService = bookAppService; - } +Let's **create a new book** using the `create` function: - public void OnGet() - { - Book = new CreateUpdateBookDto(); - } +````js +acme.bookStore.books.book.create({ + name: 'Foundation', + type: 7, + publishDate: '1951-05-24', + price: 21.5 + }).then(function (result) { + console.log('successfully created the book with id: ' + result.id); + }); +```` - public async Task OnPostAsync() - { - await _bookAppService.CreateAsync(Book); - return NoContent(); - } - } -} +You should see a message in the console something like that: + +````text +successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246 ```` -* This class is derived from the `BookStorePageModel` instead of standard `PageModel`. `BookStorePageModel` indirectly inherits the `PageModel` and adds some common properties & methods that can be shared in your page model classes. -* `[BindProperty]` attribute on the `Book` property binds post request data to this property. -* This class simply injects the `IBookAppService` in the constructor and calls the `CreateAsync` method in the `OnPostAsync` handler. -* It creates a new `CreateUpdateBookDto` object in the `OnGet` method. ASP.NET Core can work without creating a new instance like that. However, it doesn't create an instance for you and if your class has some default value assignments or code execution in the class constructor, they won't work. For this case, we set default values for some of the `CreateUpdateBookDto` properties. +Check the `Books` table in the database to see the new book row. You can try `get`, `update` and `delete` functions yourself. + +We will use these dynamic proxy functions in the next sections to communicate to the server. -#### CreateModal.cshtml +## Create a Books Page -Open the `CreateModal.cshtml` file and paste the code below: +It's time to create something visible and usable! Instead of classic MVC, we will use the [Razor Pages UI](https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start) approach which is recommended by Microsoft. + +Create `Books` folder under the `Pages` folder of the `Acme.BookStore.Web` project. Add a new Razor Page by right clicking the Books folder then selecting **Add > Razor Page** menu item. Name it as `Index`: + +![bookstore-add-index-page](./images/bookstore-add-index-page-v2.png) + +Open the `Index.cshtml` and change the whole content as shown below: ````html @page -@using Acme.BookStore.Localization @using Acme.BookStore.Web.Pages.Books -@using Microsoft.Extensions.Localization -@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal -@model CreateModalModel -@inject IStringLocalizer L -@{ - Layout = null; +@model IndexModel + +

Books

+```` + +`Index.cshtml.cs` content should be like that: + +```csharp +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace Acme.BookStore.Web.Pages.Books +{ + public class IndexModel : PageModel + { + public void OnGet() + { + + } + } } - - - - - - - - - +``` + +### Add Books Page to the Main Menu + +Open the `BookStoreMenuContributor` class in the `Menus` folder and add the following code to the end of the `ConfigureMainMenuAsync` method: + +````csharp +context.Menu.AddItem( + new ApplicationMenuItem( + "BooksStore", + l["Menu:BookStore"], + icon: "fa fa-book" + ).AddItem( + new ApplicationMenuItem( + "BooksStore.Books", + l["Menu:Books"], + url: "/Books" + ) + ) +); ```` -* This modal uses `abp-dynamic-form` [tag helper](../UI/AspNetCore/Tag-Helpers/Dynamic-Forms.md) to automatically create the form from the `CreateBookViewModel` model class. -* `abp-model` attribute indicates the model object where it's the `Book` property in this case. -* `abp-form-content` tag helper is a placeholder to render the form controls (it is optional and needed only if you have added some other content in the `abp-dynamic-form` tag, just like in this page). +{{end}} -> Tip: `Layout` should be `null` just as done in this example since we don't want to include all the layout for the modals when they are loaded via AJAX. +### Localization -### Add the "New book" Button +Localization texts are located under the `Localization/BookStore` folder of the `Acme.BookStore.Domain.Shared` project: -Open the `Pages/Books/Index.cshtml` and set the content of `abp-card-header` tag as below: +![bookstore-localization-files](./images/bookstore-localization-files-v2.png) -````html - - - - @L["Books"] - - - - - - +Open the `en.json` (*the English translations*) file and change the content as below: + +````json +{ + "Culture": "en", + "Texts": { + "Menu:Home": "Home", + "Welcome": "Welcome", + "LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information, visit abp.io.", + "Menu:BookStore": "Book Store", + "Menu:Books": "Books", + "Actions": "Actions", + "Edit": "Edit", + "PublishDate": "Publish date", + "NewBook": "New book", + "Name": "Name", + "Type": "Type", + "Price": "Price", + "CreationTime": "Creation time", + "AreYouSureToDelete": "Are you sure you want to delete this item?", + "Enum:BookType:0": "Undefined", + "Enum:BookType:1": "Adventure", + "Enum:BookType:2": "Biography", + "Enum:BookType:3": "Dystopia", + "Enum:BookType:4": "Fantastic", + "Enum:BookType:5": "Horror", + "Enum:BookType:6": "Science", + "Enum:BookType:7": "Science fiction", + "Enum:BookType:8": "Poetry" + } +} ```` -The final content of the `Index.cshtml` is shown below: +* Localization key names are arbitrary. You can set any name. We prefer some conventions for specific text types; + * Add `Menu:` prefix for menu items. + * Use `Enum::` naming convention to localize the enum members. When you do it like that, ABP can automatically localize the enums in some proper cases. + +If a text is not defined in the localization file, it **fallbacks** to the localization key (as ASP.NET Core's standard behavior). + +> ABP's localization system is built on [ASP.NET Core's standard localization](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization) system and extends it in many ways. See the [localization document](../Localization.md) for details. + +{{if UI == "MVC"}} + +Run the project, login to the application with the username `admin` and the password `1q2w3E*` and see the new menu item has been added to the main menu: + +![bookstore-menu-items](./images/bookstore-new-menu-item.png) + +When you click to the Books menu item under the Book Store parent, you are being redirected to the new empty Books Page. + +### Book List + +We will use the [Datatables.net](https://datatables.net/) jQuery library to show the book list. Datatables library completely work via AJAX, it is fast, popular and provides a good user experience. + +> Datatables library is configured in the startup template, so you can directly use it in any page without including any style or script file to your page. + +#### Index.cshtml + +Change the `Pages/Books/Index.cshtml` as following: ````html @page @@ -158,22 +223,11 @@ The final content of the `Index.cshtml` is shown below: @inject IStringLocalizer L @section scripts { - + } - - - - @L["Books"] - - - - - +

@L["Books"]

@@ -181,30 +235,16 @@ The final content of the `Index.cshtml` is shown below:
```` -This adds a new button called **New book** to the **top-right** of the table: +* `abp-script` [tag helper](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro) is used to add external **scripts** to the page. It has many additional features compared to standard `script` tag. It handles **minification** and **versioning**. See the [bundling & minification document](../UI/AspNetCore/Bundling-Minification.md) for details. +* `abp-card` is a tag helper for Twitter Bootstrap's [card component](https://getbootstrap.com/docs/4.5/components/card/). There are other useful tag helpers provided by the ABP Framework to easily use most of the [bootstrap](https://getbootstrap.com/) components. You could use the regular HTML tags instead of these tag helpers, but using tag helpers reduces HTML code and prevents errors by help the of IntelliSense and compile time type checking. Further information, see the [tag helpers](../UI/AspNetCore/Tag-Helpers/Index.md) document. -![bookstore-new-book-button](./images/bookstore-new-book-button-2.png) +#### Index.js -Open the `Pages/Books/Index.js` and add the following code just after the `Datatable` configuration: +Create an `Index.js` file under the `Pages/Books` folder: -````js -var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); - -createModal.onResult(function () { - dataTable.ajax.reload(); -}); - -$('#NewBookButton').click(function (e) { - e.preventDefault(); - createModal.open(); -}); -```` +![bookstore-index-js-file](./images/bookstore-index-js-file-v3.png) -* `abp.ModalManager` is a helper class to manage modals in the client side. It internally uses Twitter Bootstrap's standard modal, but abstracts many details by providing a simple API. -* `createModal.onResult(...)` used to refresh the data table after creating a new book. -* `createModal.open();` is used to open the model to create a new book. - -The final content of the `Index.js` should be like that: +The content of the file is shown below: ````js $(function () { @@ -258,381 +298,195 @@ $(function () { ] }) ); - - var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); - - createModal.onResult(function () { - dataTable.ajax.reload(); - }); - - $('#NewBookButton').click(function (e) { - e.preventDefault(); - createModal.open(); - }); }); ```` -Now, you can **run the application** and add some new books using the new modal form. +* `abp.localization.getResource` gets a function that is used to localize text using the same JSON file defined in the server side. In this way, you can share the localization values with the client side. +* `abp.libs.datatables.normalizeConfiguration` is a helper function defined by the ABP Framework. There's no requirement to use it, but it simplifies the [Datatables](https://datatables.net/) configuration by providing conventional default values for missing options. +* `abp.libs.datatables.createAjax` is another helper function to adapt ABP's dynamic JavaScript API proxies to [Datatable](https://datatables.net/)'s expected parameter format +* `acme.bookStore.books.book.getList` is the dynamic JavaScript proxy function introduced before. +* [luxon](https://moment.github.io/luxon/) library is also a standard library that is pre-configured in the solution, so you can use to perform date/time operations easily. -## Updating a Book +> See [Datatables documentation](https://datatables.net/manual/) for all configuration options. -Create a new razor page, named `EditModal.cshtml` under the `Pages/Books` folder of the `Acme.BookStore.Web` project: +## Run the Final Application -![bookstore-add-edit-dialog](./images/bookstore-add-edit-dialog.png) +You can run the application! The final UI of this part is shown below: -### EditModal.cshtml.cs +![Book list](images/bookstore-book-list-3.png) -Open the `EditModal.cshtml.cs` file (`EditModalModel` class) and replace with the following code: +This is a fully working, server side paged, sorted and localized table of books. -````csharp -using System; -using System.Threading.Tasks; -using Acme.BookStore.Books; -using Microsoft.AspNetCore.Mvc; +{{end}} -namespace Acme.BookStore.Web.Pages.Books -{ - public class EditModalModel : BookStorePageModel - { - [HiddenInput] - [BindProperty(SupportsGet = true)] - public Guid Id { get; set; } +{{if UI == "NG"}} - [BindProperty] - public CreateUpdateBookDto Book { get; set; } +## Angular UI Development +### Create the books page - private readonly IBookAppService _bookAppService; +It's time to create something visible and usable! There are some tools that we will use when developing ABP Angular frontend application: - public EditModalModel(IBookAppService bookAppService) - { - _bookAppService = bookAppService; - } +- [Angular CLI](https://angular.io/cli) will be used to create modules, components and services. +- [Ng Bootstrap](https://ng-bootstrap.github.io/#/home) will be used as the UI component library. +- [ngx-datatable](https://swimlane.gitbook.io/ngx-datatable/) will be used as the datatable library. +- [Visual Studio Code](https://code.visualstudio.com/) will be used as the code editor (you can use your favorite editor). - public async Task OnGetAsync() - { - var bookDto = await _bookAppService.GetAsync(Id); - Book = ObjectMapper.Map(bookDto); - } +### Install NPM packages - public async Task OnPostAsync() - { - await _bookAppService.UpdateAsync(Id, Book); - return NoContent(); - } - } -} -```` +Open a new command line interface (terminal window) and go to your `angular` folder and then run `yarn` command to install NPM packages: -* `[HiddenInput]` and `[BindProperty]` are standard ASP.NET Core MVC attributes. `SupportsGet` is used to be able to get `Id` value from query string parameter of the request. -* In the `OnGetAsync` method, we get `BookDto ` from the `BookAppService` and this is being mapped to the DTO object `CreateUpdateBookDto`. -* The `OnPostAsync` uses `BookAppService.UpdateAsync(...)` to update the entity. +```bash +yarn +``` -### Mapping from BookDto to CreateUpdateBookDto +### BookModule -To be able to map the `BookDto` to `CreateUpdateBookDto`, configure a new mapping. To do this, open the `BookStoreWebAutoMapperProfile.cs` in the `Acme.BookStore.Web` project and change it as shown below: +Run the following command line to create a new module, named `BookModule`: -````csharp -using AutoMapper; +```bash +yarn ng generate module book --routing true +``` -namespace Acme.BookStore.Web -{ - public class BookStoreWebAutoMapperProfile : Profile - { - public BookStoreWebAutoMapperProfile() - { - CreateMap(); - } - } -} -```` +![Generating books module](./images/bookstore-creating-book-module-terminal.png) + +### Routing -* We have just added `CreateMap();` to define this mapping. +Open the `app-routing.module.ts` file in `src\app` folder and add a route as shown below: -> Notice that we do the mapping definition in the web layer as a best practice since it is only needed in this layer. +```js +const routes: Routes = [ +// ... +// added a new route to the routes array + { + path: 'books', + loadChildren: () => import('./book/book.module').then(m => m.BookModule) + } +] +``` -### EditModal.cshtml +* We added a lazy-loaded route. See the [Lazy-Loading Feature Modules](https://angular.io/guide/lazy-loading-ngmodules#lazy-loading-feature-modules). -Replace `EditModal.cshtml` content with the following content: +Open the `route.provider.ts` file in `src\app` folder and replace the content as below: -````html -@page -@using Acme.BookStore.Localization -@using Acme.BookStore.Web.Pages.Books -@using Microsoft.Extensions.Localization -@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal -@model EditModalModel -@inject IStringLocalizer L -@{ - Layout = null; +```js +import { RoutesService, eLayoutType } from '@abp/ng.core'; +import { APP_INITIALIZER } from '@angular/core'; + +export const APP_ROUTE_PROVIDER = [ + { provide: APP_INITIALIZER, useFactory: configureRoutes, deps: [RoutesService], multi: true }, +]; + +function configureRoutes(routes: RoutesService) { + return () => { + routes.add([ + //... + // added below element + { + path: '/books', + name: '::Menu:Books', + iconClass: 'fas fa-book', + order: 101, + layout: eLayoutType.application, + }, + ]); + }; } - - - - - - - - - - -```` +``` -This page is very similar to the `CreateModal.cshtml`, except: +* We added a new route element to show a navigation element labeled "Books" on the menu. + * `path` is the URL of the route. + * `name` is the menu item name. A Localization key can be passed. + * `iconClass` is the icon of the menu item. + * `order` is the order of the menu item. We define 101 to show the route after the "Administration" item. + * `layout` is the layout of the BooksModule's routes. `eLayoutType.application`, `eLayoutType.account` or `eLayoutType.empty` can be defined. -* It includes an `abp-input` for the `Id` property to store `Id` of the editing book (which is a hidden input). -* It uses `Books/EditModal` as the post URL. +For more information, see the [RoutesService document](https://docs.abp.io/en/abp/latest/UI/Angular/Modifying-the-Menu.md#via-routesservice). -### Add "Actions" Dropdown to the Table +#### Book List Component -We will add a dropdown button to the table named *Actions*. +Run the command below on the terminal in the root folder to generate a new component, named book-list: -Open the `Pages/Books/Index.js` and replace the content as below: +```bash +yarn ng generate component book/book-list +``` -````js -$(function () { - var l = abp.localization.getResource('BookStore'); - var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); - var editModal = new abp.ModalManager(abp.appPath + 'Books/EditModal'); +![Creating books list](./images/bookstore-creating-book-list-terminal.png) - var dataTable = $('#BooksTable').DataTable( - abp.libs.datatables.normalizeConfiguration({ - serverSide: true, - paging: true, - order: [[1, "asc"]], - searching: false, - scrollX: true, - ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), - columnDefs: [ - { - title: l('Actions'), - rowAction: { - items: - [ - { - text: l('Edit'), - action: function (data) { - editModal.open({ id: data.record.id }); - } - } - ] - } - }, - { - title: l('Name'), - data: "name" - }, - { - title: l('Type'), - data: "type", - render: function (data) { - return l('Enum:BookType:' + data); - } - }, - { - title: l('PublishDate'), - data: "publishDate", - render: function (data) { - return luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }).toLocaleString(); - } - }, - { - title: l('Price'), - data: "price" - }, - { - title: l('CreationTime'), data: "creationTime", - render: function (data) { - return luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }).toLocaleString(luxon.DateTime.DATETIME_SHORT); - } - } - ] - }) - ); +Open `book.module.ts` file in the `app\book` folder and replace the content as below: - createModal.onResult(function () { - dataTable.ajax.reload(); - }); +```js +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { BookRoutingModule } from './book-routing.module'; +import { BookListComponent } from './book-list/book-list.component'; +import { SharedModule } from '../shared/shared.module'; //<== added this line ==> - editModal.onResult(function () { - dataTable.ajax.reload(); - }); +@NgModule({ + declarations: [BookListComponent], + imports: [ + CommonModule, + BookRoutingModule, + SharedModule, //<== added this line ==> + ], +}) +export class BookModule {} +``` - $('#NewBookButton').click(function (e) { - e.preventDefault(); - createModal.open(); - }); -}); -```` +* We imported `SharedModule` and added to `imports` array. -* Added a new `ModalManager` named `editModal` to open the edit modal dialog. -* Added a new column at the beginning of the `columnDefs` section. This column is used for the "*Actions*" dropdown button. -* "*Edit*" action simply calls `editModal.open()` to open the edit dialog. -* `editModal.onResult(...)` callback refreshes the data table when you close the edit modal. +Open `book-routing.module.ts` file in the `app\book` folder and replace the content as below: -You can run the application and edit any book by selecting the edit action on a book. +```js +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; +import { BookListComponent } from './book-list/book-list.component'; // <== added this line ==> -The final UI looks as below: +// <== replaced routes ==> +const routes: Routes = [ + { + path: '', + component: BookListComponent, + }, +]; -![bookstore-books-table-actions](./images/bookstore-edit-button-2.png) +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class BookRoutingModule { } +``` -## Deleting a Book +* We imported `BookListComponent` and replaced `routes` const. -Open the `Pages/Books/Index.js` and add a new item to the `rowAction` `items`: +Run `yarn start` and wait for Angular to serve the application: -````js -{ - text: l('Delete'), - confirmMessage: function (data) { - return l('BookDeletionConfirmationMessage', data.record.name); - }, - action: function (data) { - acme.bookStore.books.book - .delete(data.record.id) - .then(function() { - abp.notify.info(l('SuccessfullyDeleted')); - dataTable.ajax.reload(); - }); - } -} -```` +```bash +yarn start +``` -* `confirmMessage` option is used to ask a confirmation question before executing the `action`. -* `acme.bookStore.books.book.delete(...)` method makes an AJAX request to the server to delete a book. -* `abp.notify.info()` shows a notification after the delete operation. +Open the browser and navigate to http://localhost:4200/books. We'll see **book-list works!** text on the books page: -Since we've used two new localization texts (`BookDeletionConfirmationMessage` and `SuccessfullyDeleted`) you need to add these to the localization file (`en.json` under the `Localization/BookStore` folder of the `Acme.BookStore.Domain.Shared` project): +![Initial book list page](./images/bookstore-initial-book-list-page.png) -````json -"BookDeletionConfirmationMessage": "Are you sure to delete the book '{0}'?", -"SuccessfullyDeleted": "Successfully deleted!" -```` +### Generate Proxies -The final `Index.js` content is shown below: +ABP CLI provides `generate-proxy` command that generates client proxies for your HTTP APIs to make easy to consume your services from the client side. Before running generate-proxy command, your host must be up and running. See the [CLI documentation](../CLI.md) -````js -$(function () { - var l = abp.localization.getResource('BookStore'); - var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); - var editModal = new abp.ModalManager(abp.appPath + 'Books/EditModal'); +Run the following command in the `angular` folder: - var dataTable = $('#BooksTable').DataTable( - abp.libs.datatables.normalizeConfiguration({ - serverSide: true, - paging: true, - order: [[1, "asc"]], - searching: false, - scrollX: true, - ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), - columnDefs: [ - { - title: l('Actions'), - rowAction: { - items: - [ - { - text: l('Edit'), - action: function (data) { - editModal.open({ id: data.record.id }); - } - }, - { - text: l('Delete'), - confirmMessage: function (data) { - return l( - 'BookDeletionConfirmationMessage', - data.record.name - ); - }, - action: function (data) { - acme.bookStore.books.book - .delete(data.record.id) - .then(function() { - abp.notify.info( - l('SuccessfullyDeleted') - ); - dataTable.ajax.reload(); - }); - } - } - ] - } - }, - { - title: l('Name'), - data: "name" - }, - { - title: l('Type'), - data: "type", - render: function (data) { - return l('Enum:BookType:' + data); - } - }, - { - title: l('PublishDate'), - data: "publishDate", - render: function (data) { - return luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }).toLocaleString(); - } - }, - { - title: l('Price'), - data: "price" - }, - { - title: l('CreationTime'), data: "creationTime", - render: function (data) { - return luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }).toLocaleString(luxon.DateTime.DATETIME_SHORT); - } - } - ] - }) - ); +```bash +abp generate-proxy --module app +``` - createModal.onResult(function () { - dataTable.ajax.reload(); - }); - - editModal.onResult(function () { - dataTable.ajax.reload(); - }); - - $('#NewBookButton').click(function (e) { - e.preventDefault(); - createModal.open(); - }); -}); -```` - -You can run the application and try to delete a book. - -{{end}} - -{{if UI == "NG"}} +![Generate proxy command](./images/generate-proxy-command.png) -## Creating a new book +The generated files looks like below: -In this section, you will learn how to create a new modal dialog form to create a new book. +![Generated files](./images/generated-proxies.png) -### Add a modal to BookListComponent +### BookListComponent -Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: +Open the `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: ```js import { ListService, PagedResultDto } from '@abp/ng.core'; @@ -651,8 +505,6 @@ export class BookListComponent implements OnInit { booksType = BookType; - isModalOpen = false; // <== added this line ==> - constructor(public readonly list: ListService, private bookService: BookService) {} ngOnInit() { @@ -662,36 +514,24 @@ export class BookListComponent implements OnInit { this.book = response; }); } - - // added createBook method - createBook() { - this.isModalOpen = true; - } } ``` -* We defined a variable called `isModalOpen` and `createBook` method. -* We added the `createBook` method. - +* We imported and injected the generated `BookService`. +* We implemented the [ListService](https://docs.abp.io/en/abp/latest/UI/Angular/List-Service) that is a utility service to provide easy pagination, sorting, and search implementation. -Open `book-list.component.html` file in `books\book-list` folder and replace the content as below: +Open the `book-list.component.html` file in `app\book\book-list` folder and replace the content as below: ```html
-
{%{{{ '::Menu:Books' | abpLocalization }}}%}
-
- -
-
- -
+
+ {%{{{ '::Menu:Books' | abpLocalization }}}%} +
+
@@ -715,587 +555,22 @@ Open `book-list.component.html` file in `books\book-list` folder and replace the
- - - - -

{%{{{ '::NewBook' | abpLocalization }}}%}

-
- - - - - - -
-``` - -* We added the `abp-modal` which renders a modal to allow user to create a new book. -* `abp-modal` is a pre-built component to show modals. While you could use another approach to show a modal, `abp-modal` provides additional benefits. -* We added `New book` button to the `AbpContentToolbar`. - -You can open your browser and click **New book** button to see the new modal. - -![Empty modal for new book](./images/bookstore-empty-new-book-modal.png) - -### Create a reactive form - -[Reactive forms](https://angular.io/guide/reactive-forms) provide a model-driven approach to handling form inputs whose values change over time. - -Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: - -```js -import { ListService, PagedResultDto } from '@abp/ng.core'; -import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from '../models'; -import { BookService } from '../services'; -import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // <== added this line ==> - -@Component({ - selector: 'app-book-list', - templateUrl: './book-list.component.html', - styleUrls: ['./book-list.component.scss'], - providers: [ListService], -}) -export class BookListComponent implements OnInit { - book = { items: [], totalCount: 0 } as PagedResultDto; - - booksType = BookType; - - isModalOpen = false; - - form: FormGroup; // <== added this line ==> - - constructor( - public readonly list: ListService, - private bookService: BookService, - private fb: FormBuilder // <== injected FormBuilder ==> - ) {} - - ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); - - this.list.hookToQuery(bookStreamCreator).subscribe((response) => { - this.book = response; - }); - } - - createBook() { - this.buildForm(); // <== added this line ==> - this.isModalOpen = true; - } - - // added buildForm method - buildForm() { - this.form = this.fb.group({ - name: ['', Validators.required], - type: [null, Validators.required], - publishDate: [null, Validators.required], - price: [null, Validators.required], - }); - } -} -``` - -* We imported `FormGroup, FormBuilder and Validators`. -* We added `form: FormGroup` variable. -* We injected `fb: FormBuilder` service to the constructor. The [FormBuilder](https://angular.io/api/forms/FormBuilder) service provides convenient methods for generating controls. It reduces the amount of boilerplate needed to build complex forms. -* We added `buildForm` method to the end of the file and executed `buildForm()` in the `createBook` method. This method creates a reactive form to be able to create a new book. - * The `group` method of `FormBuilder`, `fb` creates a `FormGroup`. - * Added `Validators.required` static method which validates the relevant form element. - -### Create the DOM elements of the form - -Open `book-list.component.html` in `app\books\book-list` folder and replace ` ` with the following code part: - -```html - -
-
- * - -
- -
- * - -
- -
- * - -
- -
- * - -
-
-
-``` - -- This template creates a form with `Name`, `Price`, `Type` and `Publish` date fields. -- We've used [NgBootstrap datepicker](https://ng-bootstrap.github.io/#/components/datepicker/overview) in this component. - -### Datepicker requirements - -Open `book.module.ts` file in `app\book` folder and replace the content as below: - -```js -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { BookRoutingModule } from './book-routing.module'; -import { BookListComponent } from './book-list/book-list.component'; -import { SharedModule } from '../shared/shared.module'; -import { NgbDatepickerModule } from '@ng-bootstrap/ng-bootstrap'; //<== added this line ==> - -@NgModule({ - declarations: [BookListComponent], - imports: [ - CommonModule, - BookRoutingModule, - SharedModule, - NgbDatepickerModule, //<== added this line ==> - ], -}) -export class BookModule {} -``` - -* We imported `NgbDatepickerModule` to be able to use the date picker. - -Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: - -```js -import { ListService, PagedResultDto } from '@abp/ng.core'; -import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from '../models'; -import { BookService } from '../services'; -import { FormGroup, FormBuilder, Validators } from '@angular/forms'; -import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; // <== added this line ==> - -@Component({ - selector: 'app-book-list', - templateUrl: './book-list.component.html', - styleUrls: ['./book-list.component.scss'], - providers: [ListService, { provide: NgbDateAdapter, useClass: NgbDateNativeAdapter }], // <== added a provide ==> -}) -export class BookListComponent implements OnInit { - book = { items: [], totalCount: 0 } as PagedResultDto; - - booksType = BookType; - - // <== added bookTypeArr array ==> - bookTypeArr = Object.keys(BookType).filter( - (bookType) => typeof this.booksType[bookType] === 'number' - ); - - isModalOpen = false; - - form: FormGroup; - - constructor( - public readonly list: ListService, - private bookService: BookService, - private fb: FormBuilder - ) {} - - ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); - - this.list.hookToQuery(bookStreamCreator).subscribe((response) => { - this.book = response; - }); - } - - createBook() { - this.buildForm(); - this.isModalOpen = true; - } - - buildForm() { - this.form = this.fb.group({ - name: ['', Validators.required], - type: [null, Validators.required], - publishDate: [null, Validators.required], - price: [null, Validators.required], - }); - } -} ``` -* We imported ` NgbDateNativeAdapter, NgbDateAdapter` - -* We added a new provider `NgbDateAdapter` that converts Datepicker value to `Date` type. See the [datepicker adapters](https://ng-bootstrap.github.io/#/components/datepicker/overview) for more details. - -* We added `bookTypeArr` array to be able to use it in the combobox values. The `bookTypeArr` contains the fields of the `BookType` enum. Resulting array is shown below: +* We added HTML code of book list page. - ```js - ['Adventure', 'Biography', 'Dystopia', 'Fantastic' ...] - ``` +Now you can see the final result on your browser: - This array was used in the previous form template in the `ngFor` loop. +![Book list final result](./images/bookstore-book-list.png) -Now, you can open your browser to see the changes: - - -![New book modal](./images/bookstore-new-book-form.png) - -### Saving the book - -Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: - -```js -import { ListService, PagedResultDto } from '@abp/ng.core'; -import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from '../models'; -import { BookService } from '../services'; -import { FormGroup, FormBuilder, Validators } from '@angular/forms'; -import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; - -@Component({ - selector: 'app-book-list', - templateUrl: './book-list.component.html', - styleUrls: ['./book-list.component.scss'], - providers: [ListService, { provide: NgbDateAdapter, useClass: NgbDateNativeAdapter }], -}) -export class BookListComponent implements OnInit { - book = { items: [], totalCount: 0 } as PagedResultDto; - - booksType = BookType; - - bookTypeArr = Object.keys(BookType).filter( - (bookType) => typeof this.booksType[bookType] === 'number' - ); - - isModalOpen = false; - - form: FormGroup; - - constructor( - public readonly list: ListService, - private bookService: BookService, - private fb: FormBuilder - ) {} - - ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); - - this.list.hookToQuery(bookStreamCreator).subscribe((response) => { - this.book = response; - }); - } - - createBook() { - this.buildForm(); - this.isModalOpen = true; - } - - buildForm() { - this.form = this.fb.group({ - name: ['', Validators.required], - type: [null, Validators.required], - publishDate: [null, Validators.required], - price: [null, Validators.required], - }); - } - - // <== added save ==> - save() { - if (this.form.invalid) { - return; - } - - this.bookService.createByInput(this.form.value).subscribe(() => { - this.isModalOpen = false; - this.form.reset(); - this.list.get(); - }); - } -} -``` - -* We added `save` method - -Open `book-list.component.html` in `app\book\book-list` folder, find the `` element and replace this element with the following to create a new book. - -```html - - - - - - -``` - -Find the `
` tag and replace below content: - -```html - -``` - - -* We added the `(ngSubmit)="save()"` to `` element to save a new book by pressing the enter. -* We added `abp-button` to the bottom area of the modal to save a new book. - -The final modal UI looks like below: - -![Save button to the modal](./images/bookstore-new-book-form-v2.png) - -## Updating a book - -Open `book-list.component.ts` in `app\book\book-list` folder and add a variable named `selectedBook`. - -```js -import { ListService, PagedResultDto } from '@abp/ng.core'; -import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from '../models'; -import { BookService } from '../services'; -import { FormGroup, FormBuilder, Validators } from '@angular/forms'; -import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; - -@Component({ - selector: 'app-book-list', - templateUrl: './book-list.component.html', - styleUrls: ['./book-list.component.scss'], - providers: [ListService, { provide: NgbDateAdapter, useClass: NgbDateNativeAdapter }], -}) -export class BookListComponent implements OnInit { - book = { items: [], totalCount: 0 } as PagedResultDto; - - booksType = BookType; - - bookTypeArr = Object.keys(BookType).filter( - (bookType) => typeof this.booksType[bookType] === 'number' - ); - - isModalOpen = false; - - form: FormGroup; - - selectedBook = {} as BookDto; // <== declared selectedBook ==> - - constructor( - public readonly list: ListService, - private bookService: BookService, - private fb: FormBuilder - ) {} - - ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); - - this.list.hookToQuery(bookStreamCreator).subscribe((response) => { - this.book = response; - }); - } - - // <== this method is replaced ==> - createBook() { - this.selectedBook = {} as BookDto; // <== added ==> - this.buildForm(); - this.isModalOpen = true; - } - - // <== added editBook method ==> - editBook(id: string) { - this.bookService.getById(id).subscribe((book) => { - this.selectedBook = book; - this.buildForm(); - this.isModalOpen = true; - }); - } - - // <== this method is replaced ==> - buildForm() { - this.form = this.fb.group({ - name: [this.selectedBook.name || '', Validators.required], - type: [this.selectedBook.type || null, Validators.required], - publishDate: [ - this.selectedBook.publishDate ? new Date(this.selectedBook.publishDate) : null, - Validators.required, - ], - price: [this.selectedBook.price || null, Validators.required], - }); - } - - // <== this method is replaced ==> - save() { - if (this.form.invalid) { - return; - } - - // <== added request ==> - const request = this.selectedBook.id - ? this.bookService.updateByIdAndInput(this.form.value, this.selectedBook.id) - : this.bookService.createByInput(this.form.value); - - request.subscribe(() => { - this.isModalOpen = false; - this.form.reset(); - this.list.get(); - }); - } -} -``` - -* We declared a variable named `selectedBook` as `BookDto`. -* We added `editBook` method. This method fetches the book with the given `Id` and sets it to `selectedBook` object. -* We replaced the `buildForm` method so that it creates the form with the `selectedBook` data. -* We replaced the `createBook` method so it sets `selectedBook` to an empty object. -* We replaced the `save` method. - -### Add "Actions" dropdown to the table - -Open the `book-list.component.html` in `app\book\book-list` folder and replace the `
` tag as below: - -```html -
- - - - -
- -
- -
-
-
-
- - - - {%{{{ booksType[row.type] }}}%} - - - - - {%{{{ row.publishDate | date }}}%} - - - - - {%{{{ row.price | currency }}}%} - - -
-
-``` - -- We added a `ngx-datatable-column` for the "Actions" column. -- We added `button` with `ngbDropdownToggle` to open actions when clicked the button. -- We have used to [NgbDropdown](https://ng-bootstrap.github.io/#/components/dropdown/examples) for the dropdown menu of actions. - -The final UI looks like as below: - -![Action buttons](./images/bookstore-actions-buttons.png) - -Open `book-list.component.html` in `app\book\book-list` folder and find the `` tag and replace the content as below. - -```html - -

{%{{{ (selectedBook.id ? '::Edit' : '::NewBook' ) | abpLocalization }}}%}

-
-``` - -* This template will show **Edit** text for edit record operation, **New Book** for new record operation in the title. - -## Deleting a book - -### Delete confirmation popup - -Open `book-list.component.ts` in `app\book\book-list` folder and inject the `ConfirmationService`. - -Replace the constructor as below: - -```js -import { ConfirmationService } from '@abp/ng.theme.shared'; -//... - -constructor( - public readonly list: ListService, - private bookService: BookService, - private fb: FormBuilder, - private confirmation: ConfirmationService // <== added this line ==> -) {} -``` - -* We imported `ConfirmationService`. -* We injected `ConfirmationService` to the constructor. - -See the [Confirmation Popup documentation](https://docs.abp.io/en/abp/latest/UI/Angular/Confirmation-Service) - -In the `book-list.component.ts` add a delete method: - -```js -import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared'; //<== imported Confirmation namespace ==> - -//... - -delete(id: string) { - this.confirmation.warn('::AreYouSureToDelete', 'AbpAccount::AreYouSure').subscribe((status) => { - if (status === Confirmation.Status.confirm) { - this.bookService.deleteById(id).subscribe(() => this.list.get()); - } - }); -} -``` - - -The `delete` method shows a confirmation popup and subscribes for the user response. The `deleteById` method of `BookService` called only if user clicks to the `Yes` button. The confirmation popup looks like below: - -![bookstore-confirmation-popup](./images/bookstore-confirmation-popup.png) - - -### Add a delete button - - -Open `book-list.component.html` in `app\book\book-list` folder and modify the `ngbDropdownMenu` to add the delete button as shown below: - -```html -
- - -
-``` +The file system structure of the project: -The final actions dropdown UI looks like below: +![Book list final result](./images/bookstore-angular-file-tree.png) -![bookstore-final-actions-dropdown](./images/bookstore-final-actions-dropdown.png) +In this tutorial we have applied the rules of official [Angular Style Guide](https://angular.io/guide/styleguide#file-tree). {{end}} -## Next Part +## The Next Part -See the [next part](part-3.md) of this tutorial. +See the [next part](Part-3.md) of this tutorial. diff --git a/docs/en/Tutorials/Part-3.md b/docs/en/Tutorials/Part-3.md index 22e3cd4a5b..1a861f76bd 100644 --- a/docs/en/Tutorials/Part-3.md +++ b/docs/en/Tutorials/Part-3.md @@ -1,4 +1,4 @@ -# ASP.NET Core {{UI_Value}} Tutorial - Part 3 +# Web Application Development Tutorial - Part 3: Creating, Updating and Deleting Books ````json //[doc-params] { @@ -15,7 +15,7 @@ else if UI == "NG" DB="mongodb" DB_Text="MongoDB" UI_Text="angular" -else +else DB ="?" UI_Text="?" end @@ -30,213 +30,1273 @@ In this tutorial series, you will build an ABP based web application named `Acme This tutorial is organized as the following parts; -- [Part I: Creating the project and book list page](part-1.md) -- [Part-2: Creating, updating and deleting books](Part-2.md) -- **Part-3: Integration tests (this part)** -- [Part-4: Authorization](Part-4.md) +- [Part 1: Creating the project and book list page](Part-1.md) +- [Part 2: The book list page](Part-2.md) +- **Part 3: Creating, updating and deleting books (this part)** +- [Part 4: Integration tests](Part-4.md) +- [Part 5: Authorization](Part-5.md) ### Source Code You can find the completed solution on {{if UI == "MVC"}}[the GitHub repository](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore){{else}}[the GitHub repository](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb){{end}}. -## Test Projects in the Solution +{{if UI == "MVC"}} -This part covers the **server side** tests. There are several test projects in the solution: +## Creating a New Book -![bookstore-test-projects-v2](./images/bookstore-test-projects-{{UI_Text}}.png) +In this section, you will learn how to create a new modal dialog form to create a new book. The modal dialog will look like in the image below: -Each project is used to test the related project. Test projects use the following libraries for testing: +![bookstore-create-dialog](./images/bookstore-create-dialog-2.png) -* [Xunit](https://xunit.github.io/) as the main test framework. -* [Shoudly](http://shouldly.readthedocs.io/en/latest/) as the assertion library. -* [NSubstitute](http://nsubstitute.github.io/) as the mocking library. +### Create the Modal Form -{{if DB="ef"}} +Create a new razor page, named `CreateModal.cshtml` under the `Pages/Books` folder of the `Acme.BookStore.Web` project. -> The test projects are configured to use **SQLite in-memory** as the database. A separate database instance is created and seeded (with the data seed system) to prepare a fresh database for every test. +![bookstore-add-create-dialog](./images/bookstore-add-create-dialog-v2.png) -{{else if DB="mongodb"}} +#### CreateModal.cshtml.cs -> **[Mongo2Go](https://github.com/Mongo2Go/Mongo2Go)** library is used to mock the MongoDB database. A separate database instance is created and seeded (with the data seed system) to prepare a fresh database for every test. +Open the `CreateModal.cshtml.cs` file (`CreateModalModel` class) and replace with the following code: -{{end}} - -## Adding Test Data - -If you had created a data seed contributor as described in the [first part](Part-1.md), the same data will be available in your tests. So, you can skip this section. If you haven't created the seed contributor, you can use the `BookStoreTestDataSeedContributor` to seed the same data to be used in the tests below. - -## Testing The Application Service: BookAppService - -Create a test class named `BookAppService_Tests` in the `Acme.BookStore.Application.Tests` project: - -````csharp +````C# using System.Threading.Tasks; -using Shouldly; -using Volo.Abp.Application.Dtos; -using Xunit; +using Acme.BookStore.Books; +using Microsoft.AspNetCore.Mvc; -namespace Acme.BookStore.Books +namespace Acme.BookStore.Web.Pages.Books { - public class BookAppService_Tests : BookStoreApplicationTestBase + public class CreateModalModel : BookStorePageModel { + [BindProperty] + public CreateUpdateBookDto Book { get; set; } + private readonly IBookAppService _bookAppService; - public BookAppService_Tests() + public CreateModalModel(IBookAppService bookAppService) + { + _bookAppService = bookAppService; + } + + public void OnGet() { - _bookAppService = GetRequiredService(); + Book = new CreateUpdateBookDto(); } - [Fact] - public async Task Should_Get_List_Of_Books() + public async Task OnPostAsync() { - //Act - var result = await _bookAppService.GetListAsync( - new PagedAndSortedResultRequestDto() - ); - - //Assert - result.TotalCount.ShouldBeGreaterThan(0); - result.Items.ShouldContain(b => b.Name == "1984"); + await _bookAppService.CreateAsync(Book); + return NoContent(); } } } ```` -* `Should_Get_List_Of_Books` test simply uses `BookAppService.GetListAsync` method to get and check the list of books. -* We can safely check the book "1984" by its name, because we know that this books is available in the database since we've added it in the seed data. +* This class is derived from the `BookStorePageModel` instead of standard `PageModel`. `BookStorePageModel` indirectly inherits the `PageModel` and adds some common properties & methods that can be shared in your page model classes. +* `[BindProperty]` attribute on the `Book` property binds post request data to this property. +* This class simply injects the `IBookAppService` in the constructor and calls the `CreateAsync` method in the `OnPostAsync` handler. +* It creates a new `CreateUpdateBookDto` object in the `OnGet` method. ASP.NET Core can work without creating a new instance like that. However, it doesn't create an instance for you and if your class has some default value assignments or code execution in the class constructor, they won't work. For this case, we set default values for some of the `CreateUpdateBookDto` properties. -Add a new test method to the `BookAppService_Tests` class that creates a new **valid** book: +#### CreateModal.cshtml -````csharp -[Fact] -public async Task Should_Create_A_Valid_Book() -{ - //Act - var result = await _bookAppService.CreateAsync( - new CreateUpdateBookDto - { - Name = "New test book 42", - Price = 10, - PublishDate = System.DateTime.Now, - Type = BookType.ScienceFiction - } - ); +Open the `CreateModal.cshtml` file and paste the code below: - //Assert - result.Id.ShouldNotBe(Guid.Empty); - result.Name.ShouldBe("New test book 42"); +````html +@page +@using Acme.BookStore.Localization +@using Acme.BookStore.Web.Pages.Books +@using Microsoft.Extensions.Localization +@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal +@model CreateModalModel +@inject IStringLocalizer L +@{ + Layout = null; } + + + + + + + + + ```` -Add a new test that tries to create an invalid book and fails: +* This modal uses `abp-dynamic-form` [tag helper](../UI/AspNetCore/Tag-Helpers/Dynamic-Forms.md) to automatically create the form from the `CreateBookViewModel` model class. +* `abp-model` attribute indicates the model object where it's the `Book` property in this case. +* `abp-form-content` tag helper is a placeholder to render the form controls (it is optional and needed only if you have added some other content in the `abp-dynamic-form` tag, just like in this page). -````csharp -[Fact] -public async Task Should_Not_Create_A_Book_Without_Name() +> Tip: `Layout` should be `null` just as done in this example since we don't want to include all the layout for the modals when they are loaded via AJAX. + +### Add the "New book" Button + +Open the `Pages/Books/Index.cshtml` and set the content of `abp-card-header` tag as below: + +````html + + + + @L["Books"] + + + + + + +```` + +The final content of the `Index.cshtml` is shown below: + +````html +@page +@using Acme.BookStore.Localization +@using Acme.BookStore.Web.Pages.Books +@using Microsoft.Extensions.Localization +@model IndexModel +@inject IStringLocalizer L +@section scripts { - var exception = await Assert.ThrowsAsync(async () => - { - await _bookAppService.CreateAsync( - new CreateUpdateBookDto - { - Name = "", - Price = 10, - PublishDate = DateTime.Now, - Type = BookType.ScienceFiction - } - ); - }); - - exception.ValidationErrors - .ShouldContain(err => err.MemberNames.Any(mem => mem == "Name")); + } + + + + + + @L["Books"] + + + + + + + + + + +```` + +This adds a new button called **New book** to the **top-right** of the table: + +![bookstore-new-book-button](./images/bookstore-new-book-button-2.png) + +Open the `Pages/Books/Index.js` and add the following code just after the `Datatable` configuration: + +````js +var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); + +createModal.onResult(function () { + dataTable.ajax.reload(); +}); + +$('#NewBookButton').click(function (e) { + e.preventDefault(); + createModal.open(); +}); +```` + +* `abp.ModalManager` is a helper class to manage modals in the client side. It internally uses Twitter Bootstrap's standard modal, but abstracts many details by providing a simple API. +* `createModal.onResult(...)` used to refresh the data table after creating a new book. +* `createModal.open();` is used to open the model to create a new book. + +The final content of the `Index.js` should be like that: + +````js +$(function () { + var l = abp.localization.getResource('BookStore'); + + var dataTable = $('#BooksTable').DataTable( + abp.libs.datatables.normalizeConfiguration({ + serverSide: true, + paging: true, + order: [[1, "asc"]], + searching: false, + scrollX: true, + ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), + columnDefs: [ + { + title: l('Name'), + data: "name" + }, + { + title: l('Type'), + data: "type", + render: function (data) { + return l('Enum:BookType:' + data); + } + }, + { + title: l('PublishDate'), + data: "publishDate", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(); + } + }, + { + title: l('Price'), + data: "price" + }, + { + title: l('CreationTime'), data: "creationTime", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(luxon.DateTime.DATETIME_SHORT); + } + } + ] + }) + ); + + var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); + + createModal.onResult(function () { + dataTable.ajax.reload(); + }); + + $('#NewBookButton').click(function (e) { + e.preventDefault(); + createModal.open(); + }); +}); ```` -* Since the `Name` is empty, ABP will throw an `AbpValidationException`. +Now, you can **run the application** and add some new books using the new modal form. + +## Updating a Book + +Create a new razor page, named `EditModal.cshtml` under the `Pages/Books` folder of the `Acme.BookStore.Web` project: -The final test class should be as shown below: +![bookstore-add-edit-dialog](./images/bookstore-add-edit-dialog.png) + +### EditModal.cshtml.cs + +Open the `EditModal.cshtml.cs` file (`EditModalModel` class) and replace with the following code: ````csharp using System; -using System.Linq; using System.Threading.Tasks; -using Shouldly; -using Volo.Abp.Application.Dtos; -using Volo.Abp.Validation; -using Xunit; +using Acme.BookStore.Books; +using Microsoft.AspNetCore.Mvc; -namespace Acme.BookStore.Books +namespace Acme.BookStore.Web.Pages.Books { - public class BookAppService_Tests : BookStoreApplicationTestBase + public class EditModalModel : BookStorePageModel { + [HiddenInput] + [BindProperty(SupportsGet = true)] + public Guid Id { get; set; } + + [BindProperty] + public CreateUpdateBookDto Book { get; set; } + private readonly IBookAppService _bookAppService; - public BookAppService_Tests() + public EditModalModel(IBookAppService bookAppService) { - _bookAppService = GetRequiredService(); + _bookAppService = bookAppService; } - [Fact] - public async Task Should_Get_List_Of_Books() + public async Task OnGetAsync() { - //Act - var result = await _bookAppService.GetListAsync( - new PagedAndSortedResultRequestDto() - ); - - //Assert - result.TotalCount.ShouldBeGreaterThan(0); - result.Items.ShouldContain(b => b.Name == "1984"); + var bookDto = await _bookAppService.GetAsync(Id); + Book = ObjectMapper.Map(bookDto); } - - [Fact] - public async Task Should_Create_A_Valid_Book() - { - //Act - var result = await _bookAppService.CreateAsync( - new CreateUpdateBookDto - { - Name = "New test book 42", - Price = 10, - PublishDate = System.DateTime.Now, - Type = BookType.ScienceFiction - } - ); - //Assert - result.Id.ShouldNotBe(Guid.Empty); - result.Name.ShouldBe("New test book 42"); + public async Task OnPostAsync() + { + await _bookAppService.UpdateAsync(Id, Book); + return NoContent(); } - - [Fact] - public async Task Should_Not_Create_A_Book_Without_Name() + } +} +```` + +* `[HiddenInput]` and `[BindProperty]` are standard ASP.NET Core MVC attributes. `SupportsGet` is used to be able to get `Id` value from query string parameter of the request. +* In the `OnGetAsync` method, we get `BookDto ` from the `BookAppService` and this is being mapped to the DTO object `CreateUpdateBookDto`. +* The `OnPostAsync` uses `BookAppService.UpdateAsync(...)` to update the entity. + +### Mapping from BookDto to CreateUpdateBookDto + +To be able to map the `BookDto` to `CreateUpdateBookDto`, configure a new mapping. To do this, open the `BookStoreWebAutoMapperProfile.cs` in the `Acme.BookStore.Web` project and change it as shown below: + +````csharp +using AutoMapper; + +namespace Acme.BookStore.Web +{ + public class BookStoreWebAutoMapperProfile : Profile + { + public BookStoreWebAutoMapperProfile() { - var exception = await Assert.ThrowsAsync(async () => - { - await _bookAppService.CreateAsync( - new CreateUpdateBookDto - { - Name = "", - Price = 10, - PublishDate = DateTime.Now, - Type = BookType.ScienceFiction + CreateMap(); + } + } +} +```` + +* We have just added `CreateMap();` to define this mapping. + +> Notice that we do the mapping definition in the web layer as a best practice since it is only needed in this layer. + +### EditModal.cshtml + +Replace `EditModal.cshtml` content with the following content: + +````html +@page +@using Acme.BookStore.Localization +@using Acme.BookStore.Web.Pages.Books +@using Microsoft.Extensions.Localization +@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal +@model EditModalModel +@inject IStringLocalizer L +@{ + Layout = null; +} + + + + + + + + + + +```` + +This page is very similar to the `CreateModal.cshtml`, except: + +* It includes an `abp-input` for the `Id` property to store `Id` of the editing book (which is a hidden input). +* It uses `Books/EditModal` as the post URL. + +### Add "Actions" Dropdown to the Table + +We will add a dropdown button to the table named *Actions*. + +Open the `Pages/Books/Index.js` and replace the content as below: + +````js +$(function () { + var l = abp.localization.getResource('BookStore'); + var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); + var editModal = new abp.ModalManager(abp.appPath + 'Books/EditModal'); + + var dataTable = $('#BooksTable').DataTable( + abp.libs.datatables.normalizeConfiguration({ + serverSide: true, + paging: true, + order: [[1, "asc"]], + searching: false, + scrollX: true, + ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), + columnDefs: [ + { + title: l('Actions'), + rowAction: { + items: + [ + { + text: l('Edit'), + action: function (data) { + editModal.open({ id: data.record.id }); + } + } + ] } - ); - }); + }, + { + title: l('Name'), + data: "name" + }, + { + title: l('Type'), + data: "type", + render: function (data) { + return l('Enum:BookType:' + data); + } + }, + { + title: l('PublishDate'), + data: "publishDate", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(); + } + }, + { + title: l('Price'), + data: "price" + }, + { + title: l('CreationTime'), data: "creationTime", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(luxon.DateTime.DATETIME_SHORT); + } + } + ] + }) + ); - exception.ValidationErrors - .ShouldContain(err => err.MemberNames.Any(mem => mem == "Name")); - } + createModal.onResult(function () { + dataTable.ajax.reload(); + }); + + editModal.onResult(function () { + dataTable.ajax.reload(); + }); + + $('#NewBookButton').click(function (e) { + e.preventDefault(); + createModal.open(); + }); +}); +```` + +* Added a new `ModalManager` named `editModal` to open the edit modal dialog. +* Added a new column at the beginning of the `columnDefs` section. This column is used for the "*Actions*" dropdown button. +* "*Edit*" action simply calls `editModal.open()` to open the edit dialog. +* `editModal.onResult(...)` callback refreshes the data table when you close the edit modal. + +You can run the application and edit any book by selecting the edit action on a book. + +The final UI looks as below: + +![bookstore-books-table-actions](./images/bookstore-edit-button-2.png) + +## Deleting a Book + +Open the `Pages/Books/Index.js` and add a new item to the `rowAction` `items`: + +````js +{ + text: l('Delete'), + confirmMessage: function (data) { + return l('BookDeletionConfirmationMessage', data.record.name); + }, + action: function (data) { + acme.bookStore.books.book + .delete(data.record.id) + .then(function() { + abp.notify.info(l('SuccessfullyDeleted')); + dataTable.ajax.reload(); + }); } } ```` -Open the **Test Explorer Window** (use Test -> Windows -> Test Explorer menu if it is not visible) and **Run All** tests: +* `confirmMessage` option is used to ask a confirmation question before executing the `action`. +* `acme.bookStore.books.book.delete(...)` method makes an AJAX request to the server to delete a book. +* `abp.notify.info()` shows a notification after the delete operation. + +Since we've used two new localization texts (`BookDeletionConfirmationMessage` and `SuccessfullyDeleted`) you need to add these to the localization file (`en.json` under the `Localization/BookStore` folder of the `Acme.BookStore.Domain.Shared` project): + +````json +"BookDeletionConfirmationMessage": "Are you sure to delete the book '{0}'?", +"SuccessfullyDeleted": "Successfully deleted!" +```` + +The final `Index.js` content is shown below: + +````js +$(function () { + var l = abp.localization.getResource('BookStore'); + var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); + var editModal = new abp.ModalManager(abp.appPath + 'Books/EditModal'); + + var dataTable = $('#BooksTable').DataTable( + abp.libs.datatables.normalizeConfiguration({ + serverSide: true, + paging: true, + order: [[1, "asc"]], + searching: false, + scrollX: true, + ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), + columnDefs: [ + { + title: l('Actions'), + rowAction: { + items: + [ + { + text: l('Edit'), + action: function (data) { + editModal.open({ id: data.record.id }); + } + }, + { + text: l('Delete'), + confirmMessage: function (data) { + return l( + 'BookDeletionConfirmationMessage', + data.record.name + ); + }, + action: function (data) { + acme.bookStore.books.book + .delete(data.record.id) + .then(function() { + abp.notify.info( + l('SuccessfullyDeleted') + ); + dataTable.ajax.reload(); + }); + } + } + ] + } + }, + { + title: l('Name'), + data: "name" + }, + { + title: l('Type'), + data: "type", + render: function (data) { + return l('Enum:BookType:' + data); + } + }, + { + title: l('PublishDate'), + data: "publishDate", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(); + } + }, + { + title: l('Price'), + data: "price" + }, + { + title: l('CreationTime'), data: "creationTime", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(luxon.DateTime.DATETIME_SHORT); + } + } + ] + }) + ); + + createModal.onResult(function () { + dataTable.ajax.reload(); + }); + + editModal.onResult(function () { + dataTable.ajax.reload(); + }); + + $('#NewBookButton').click(function (e) { + e.preventDefault(); + createModal.open(); + }); +}); +```` + +You can run the application and try to delete a book. + +{{end}} + +{{if UI == "NG"}} + +## Creating a new book + +In this section, you will learn how to create a new modal dialog form to create a new book. + +### Add a modal to BookListComponent + +Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: + +```js +import { ListService, PagedResultDto } from '@abp/ng.core'; +import { Component, OnInit } from '@angular/core'; +import { BookDto, BookType } from '../models'; +import { BookService } from '../services'; + +@Component({ + selector: 'app-book-list', + templateUrl: './book-list.component.html', + styleUrls: ['./book-list.component.scss'], + providers: [ListService], +}) +export class BookListComponent implements OnInit { + book = { items: [], totalCount: 0 } as PagedResultDto; + + booksType = BookType; + + isModalOpen = false; // <== added this line ==> -![bookstore-appservice-tests](./images/bookstore-appservice-tests.png) + constructor(public readonly list: ListService, private bookService: BookService) {} -Congratulations, the **green icons** indicates that the tests have been successfully passed! + ngOnInit() { + const bookStreamCreator = (query) => this.bookService.getListByInput(query); + + this.list.hookToQuery(bookStreamCreator).subscribe((response) => { + this.book = response; + }); + } + + // added createBook method + createBook() { + this.isModalOpen = true; + } +} +``` + +* We defined a variable called `isModalOpen` and `createBook` method. +* We added the `createBook` method. + + +Open `book-list.component.html` file in `books\book-list` folder and replace the content as below: + +```html +
+
+
+
+
{%{{{ '::Menu:Books' | abpLocalization }}}%}
+
+ +
+
+ +
+
+
+
+
+ + + + + {%{{{ booksType[row.type] }}}%} + + + + + {%{{{ row.publishDate | date }}}%} + + + + + {%{{{ row.price | currency }}}%} + + + +
+
+ + + + +

{%{{{ '::NewBook' | abpLocalization }}}%}

+
+ + + + + + +
+``` + +* We added the `abp-modal` which renders a modal to allow user to create a new book. +* `abp-modal` is a pre-built component to show modals. While you could use another approach to show a modal, `abp-modal` provides additional benefits. +* We added `New book` button to the `AbpContentToolbar`. + +You can open your browser and click **New book** button to see the new modal. + +![Empty modal for new book](./images/bookstore-empty-new-book-modal.png) + +### Create a reactive form + +[Reactive forms](https://angular.io/guide/reactive-forms) provide a model-driven approach to handling form inputs whose values change over time. + +Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: + +```js +import { ListService, PagedResultDto } from '@abp/ng.core'; +import { Component, OnInit } from '@angular/core'; +import { BookDto, BookType } from '../models'; +import { BookService } from '../services'; +import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // <== added this line ==> + +@Component({ + selector: 'app-book-list', + templateUrl: './book-list.component.html', + styleUrls: ['./book-list.component.scss'], + providers: [ListService], +}) +export class BookListComponent implements OnInit { + book = { items: [], totalCount: 0 } as PagedResultDto; + + booksType = BookType; + + isModalOpen = false; + + form: FormGroup; // <== added this line ==> + + constructor( + public readonly list: ListService, + private bookService: BookService, + private fb: FormBuilder // <== injected FormBuilder ==> + ) {} + + ngOnInit() { + const bookStreamCreator = (query) => this.bookService.getListByInput(query); + + this.list.hookToQuery(bookStreamCreator).subscribe((response) => { + this.book = response; + }); + } + + createBook() { + this.buildForm(); // <== added this line ==> + this.isModalOpen = true; + } + + // added buildForm method + buildForm() { + this.form = this.fb.group({ + name: ['', Validators.required], + type: [null, Validators.required], + publishDate: [null, Validators.required], + price: [null, Validators.required], + }); + } +} +``` + +* We imported `FormGroup, FormBuilder and Validators`. +* We added `form: FormGroup` variable. +* We injected `fb: FormBuilder` service to the constructor. The [FormBuilder](https://angular.io/api/forms/FormBuilder) service provides convenient methods for generating controls. It reduces the amount of boilerplate needed to build complex forms. +* We added `buildForm` method to the end of the file and executed `buildForm()` in the `createBook` method. This method creates a reactive form to be able to create a new book. + * The `group` method of `FormBuilder`, `fb` creates a `FormGroup`. + * Added `Validators.required` static method which validates the relevant form element. + +### Create the DOM elements of the form + +Open `book-list.component.html` in `app\books\book-list` folder and replace ` ` with the following code part: + +```html + + +
+ * + +
+ +
+ * + +
+ +
+ * + +
+ +
+ * + +
+ +
+``` + +- This template creates a form with `Name`, `Price`, `Type` and `Publish` date fields. +- We've used [NgBootstrap datepicker](https://ng-bootstrap.github.io/#/components/datepicker/overview) in this component. + +### Datepicker requirements + +Open `book.module.ts` file in `app\book` folder and replace the content as below: + +```js +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { BookRoutingModule } from './book-routing.module'; +import { BookListComponent } from './book-list/book-list.component'; +import { SharedModule } from '../shared/shared.module'; +import { NgbDatepickerModule } from '@ng-bootstrap/ng-bootstrap'; //<== added this line ==> + +@NgModule({ + declarations: [BookListComponent], + imports: [ + CommonModule, + BookRoutingModule, + SharedModule, + NgbDatepickerModule, //<== added this line ==> + ], +}) +export class BookModule {} +``` + +* We imported `NgbDatepickerModule` to be able to use the date picker. + +Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: + +```js +import { ListService, PagedResultDto } from '@abp/ng.core'; +import { Component, OnInit } from '@angular/core'; +import { BookDto, BookType } from '../models'; +import { BookService } from '../services'; +import { FormGroup, FormBuilder, Validators } from '@angular/forms'; +import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; // <== added this line ==> + +@Component({ + selector: 'app-book-list', + templateUrl: './book-list.component.html', + styleUrls: ['./book-list.component.scss'], + providers: [ListService, { provide: NgbDateAdapter, useClass: NgbDateNativeAdapter }], // <== added a provide ==> +}) +export class BookListComponent implements OnInit { + book = { items: [], totalCount: 0 } as PagedResultDto; + + booksType = BookType; + + // <== added bookTypeArr array ==> + bookTypeArr = Object.keys(BookType).filter( + (bookType) => typeof this.booksType[bookType] === 'number' + ); + + isModalOpen = false; + + form: FormGroup; + + constructor( + public readonly list: ListService, + private bookService: BookService, + private fb: FormBuilder + ) {} + + ngOnInit() { + const bookStreamCreator = (query) => this.bookService.getListByInput(query); + + this.list.hookToQuery(bookStreamCreator).subscribe((response) => { + this.book = response; + }); + } + + createBook() { + this.buildForm(); + this.isModalOpen = true; + } + + buildForm() { + this.form = this.fb.group({ + name: ['', Validators.required], + type: [null, Validators.required], + publishDate: [null, Validators.required], + price: [null, Validators.required], + }); + } +} +``` + +* We imported ` NgbDateNativeAdapter, NgbDateAdapter` + +* We added a new provider `NgbDateAdapter` that converts Datepicker value to `Date` type. See the [datepicker adapters](https://ng-bootstrap.github.io/#/components/datepicker/overview) for more details. + +* We added `bookTypeArr` array to be able to use it in the combobox values. The `bookTypeArr` contains the fields of the `BookType` enum. Resulting array is shown below: + + ```js + ['Adventure', 'Biography', 'Dystopia', 'Fantastic' ...] + ``` + + This array was used in the previous form template in the `ngFor` loop. + +Now, you can open your browser to see the changes: + + +![New book modal](./images/bookstore-new-book-form.png) + +### Saving the book + +Open `book-list.component.ts` file in `app\book\book-list` folder and replace the content as below: + +```js +import { ListService, PagedResultDto } from '@abp/ng.core'; +import { Component, OnInit } from '@angular/core'; +import { BookDto, BookType } from '../models'; +import { BookService } from '../services'; +import { FormGroup, FormBuilder, Validators } from '@angular/forms'; +import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; + +@Component({ + selector: 'app-book-list', + templateUrl: './book-list.component.html', + styleUrls: ['./book-list.component.scss'], + providers: [ListService, { provide: NgbDateAdapter, useClass: NgbDateNativeAdapter }], +}) +export class BookListComponent implements OnInit { + book = { items: [], totalCount: 0 } as PagedResultDto; + + booksType = BookType; + + bookTypeArr = Object.keys(BookType).filter( + (bookType) => typeof this.booksType[bookType] === 'number' + ); + + isModalOpen = false; + + form: FormGroup; + + constructor( + public readonly list: ListService, + private bookService: BookService, + private fb: FormBuilder + ) {} + + ngOnInit() { + const bookStreamCreator = (query) => this.bookService.getListByInput(query); + + this.list.hookToQuery(bookStreamCreator).subscribe((response) => { + this.book = response; + }); + } + + createBook() { + this.buildForm(); + this.isModalOpen = true; + } + + buildForm() { + this.form = this.fb.group({ + name: ['', Validators.required], + type: [null, Validators.required], + publishDate: [null, Validators.required], + price: [null, Validators.required], + }); + } + + // <== added save ==> + save() { + if (this.form.invalid) { + return; + } + + this.bookService.createByInput(this.form.value).subscribe(() => { + this.isModalOpen = false; + this.form.reset(); + this.list.get(); + }); + } +} +``` + +* We added `save` method + +Open `book-list.component.html` in `app\book\book-list` folder, find the `` element and replace this element with the following to create a new book. + +```html + + + + + + +``` + +Find the `
` tag and replace below content: + +```html + +``` + + +* We added the `(ngSubmit)="save()"` to `` element to save a new book by pressing the enter. +* We added `abp-button` to the bottom area of the modal to save a new book. + +The final modal UI looks like below: + +![Save button to the modal](./images/bookstore-new-book-form-v2.png) + +## Updating a book + +Open `book-list.component.ts` in `app\book\book-list` folder and add a variable named `selectedBook`. + +```js +import { ListService, PagedResultDto } from '@abp/ng.core'; +import { Component, OnInit } from '@angular/core'; +import { BookDto, BookType } from '../models'; +import { BookService } from '../services'; +import { FormGroup, FormBuilder, Validators } from '@angular/forms'; +import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; + +@Component({ + selector: 'app-book-list', + templateUrl: './book-list.component.html', + styleUrls: ['./book-list.component.scss'], + providers: [ListService, { provide: NgbDateAdapter, useClass: NgbDateNativeAdapter }], +}) +export class BookListComponent implements OnInit { + book = { items: [], totalCount: 0 } as PagedResultDto; + + booksType = BookType; + + bookTypeArr = Object.keys(BookType).filter( + (bookType) => typeof this.booksType[bookType] === 'number' + ); + + isModalOpen = false; + + form: FormGroup; + + selectedBook = {} as BookDto; // <== declared selectedBook ==> + + constructor( + public readonly list: ListService, + private bookService: BookService, + private fb: FormBuilder + ) {} + + ngOnInit() { + const bookStreamCreator = (query) => this.bookService.getListByInput(query); + + this.list.hookToQuery(bookStreamCreator).subscribe((response) => { + this.book = response; + }); + } + + // <== this method is replaced ==> + createBook() { + this.selectedBook = {} as BookDto; // <== added ==> + this.buildForm(); + this.isModalOpen = true; + } + + // <== added editBook method ==> + editBook(id: string) { + this.bookService.getById(id).subscribe((book) => { + this.selectedBook = book; + this.buildForm(); + this.isModalOpen = true; + }); + } + + // <== this method is replaced ==> + buildForm() { + this.form = this.fb.group({ + name: [this.selectedBook.name || '', Validators.required], + type: [this.selectedBook.type || null, Validators.required], + publishDate: [ + this.selectedBook.publishDate ? new Date(this.selectedBook.publishDate) : null, + Validators.required, + ], + price: [this.selectedBook.price || null, Validators.required], + }); + } + + // <== this method is replaced ==> + save() { + if (this.form.invalid) { + return; + } + + // <== added request ==> + const request = this.selectedBook.id + ? this.bookService.updateByIdAndInput(this.form.value, this.selectedBook.id) + : this.bookService.createByInput(this.form.value); + + request.subscribe(() => { + this.isModalOpen = false; + this.form.reset(); + this.list.get(); + }); + } +} +``` + +* We declared a variable named `selectedBook` as `BookDto`. +* We added `editBook` method. This method fetches the book with the given `Id` and sets it to `selectedBook` object. +* We replaced the `buildForm` method so that it creates the form with the `selectedBook` data. +* We replaced the `createBook` method so it sets `selectedBook` to an empty object. +* We replaced the `save` method. + +### Add "Actions" dropdown to the table + +Open the `book-list.component.html` in `app\book\book-list` folder and replace the `
` tag as below: + +```html +
+ + + + +
+ +
+ +
+
+
+
+ + + + {%{{{ booksType[row.type] }}}%} + + + + + {%{{{ row.publishDate | date }}}%} + + + + + {%{{{ row.price | currency }}}%} + + +
+
+``` + +- We added a `ngx-datatable-column` for the "Actions" column. +- We added `button` with `ngbDropdownToggle` to open actions when clicked the button. +- We have used to [NgbDropdown](https://ng-bootstrap.github.io/#/components/dropdown/examples) for the dropdown menu of actions. + +The final UI looks like as below: + +![Action buttons](./images/bookstore-actions-buttons.png) + +Open `book-list.component.html` in `app\book\book-list` folder and find the `` tag and replace the content as below. + +```html + +

{%{{{ (selectedBook.id ? '::Edit' : '::NewBook' ) | abpLocalization }}}%}

+
+``` + +* This template will show **Edit** text for edit record operation, **New Book** for new record operation in the title. + +## Deleting a book + +### Delete confirmation popup + +Open `book-list.component.ts` in `app\book\book-list` folder and inject the `ConfirmationService`. + +Replace the constructor as below: + +```js +import { ConfirmationService } from '@abp/ng.theme.shared'; +//... + +constructor( + public readonly list: ListService, + private bookService: BookService, + private fb: FormBuilder, + private confirmation: ConfirmationService // <== added this line ==> +) {} +``` + +* We imported `ConfirmationService`. +* We injected `ConfirmationService` to the constructor. + +See the [Confirmation Popup documentation](https://docs.abp.io/en/abp/latest/UI/Angular/Confirmation-Service) + +In the `book-list.component.ts` add a delete method: + +```js +import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared'; //<== imported Confirmation namespace ==> + +//... + +delete(id: string) { + this.confirmation.warn('::AreYouSureToDelete', 'AbpAccount::AreYouSure').subscribe((status) => { + if (status === Confirmation.Status.confirm) { + this.bookService.deleteById(id).subscribe(() => this.list.get()); + } + }); +} +``` + + +The `delete` method shows a confirmation popup and subscribes for the user response. The `deleteById` method of `BookService` called only if user clicks to the `Yes` button. The confirmation popup looks like below: + +![bookstore-confirmation-popup](./images/bookstore-confirmation-popup.png) + + +### Add a delete button + + +Open `book-list.component.html` in `app\book\book-list` folder and modify the `ngbDropdownMenu` to add the delete button as shown below: + +```html +
+ + +
+``` + +The final actions dropdown UI looks like below: + +![bookstore-final-actions-dropdown](./images/bookstore-final-actions-dropdown.png) + +{{end}} -## Next Part +## The Next Part -See the [next part](part-4.md) of this tutorial. \ No newline at end of file +See the [next part](part-4.md) of this tutorial. diff --git a/docs/en/Tutorials/Part-4.md b/docs/en/Tutorials/Part-4.md index 43523440db..c2c0c2b530 100644 --- a/docs/en/Tutorials/Part-4.md +++ b/docs/en/Tutorials/Part-4.md @@ -1,4 +1,4 @@ -# ASP.NET Core {{UI_Value}} Tutorial - Part 4 +# Web Application Development Tutorial - Part 4: Integration Tests ````json //[doc-params] { @@ -30,286 +30,214 @@ In this tutorial series, you will build an ABP based web application named `Acme This tutorial is organized as the following parts; -- [Part I: Creating the project and book list page](part-1.md) -- [Part-2: Creating, updating and deleting books](Part-2.md) -- [Part-3: Integration tests](Part-3.md) -- **Part-4: Authorization (this part)** +- [Part 1: Creating the project and book list page](Part-1.md) +- [Part 2: The book list page](Part-2.md) +- [Part 3: Creating, updating and deleting books](Part-3.md) +- **Part 4: Integration tests (this part)** +- [Part 5: Authorization](Part-5.md) ### Source Code You can find the completed solution on {{if UI == "MVC"}}[the GitHub repository](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore){{else}}[the GitHub repository](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb){{end}}. -## Permissions +## Test Projects in the Solution -ABP Framework provides an [authorization system](../Authorization.md) based on the ASP.NET Core's [authorization infrastructure](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/introduction). One major feature added on top of the standard authorization infrastructure is the **permission system** which allows to define permissions and enable/disable per role, user or client. +This part covers the **server side** tests. There are several test projects in the solution: -### Permission Names +![bookstore-test-projects-v2](./images/bookstore-test-projects-{{UI_Text}}.png) -A permission must have a unique name (a `string`). The best way is to define it as a `const`, so we can reuse the permission name. +Each project is used to test the related project. Test projects use the following libraries for testing: -Open the `BookStorePermissions` class and change the content as shown below: +* [Xunit](https://xunit.github.io/) as the main test framework. +* [Shoudly](http://shouldly.readthedocs.io/en/latest/) as the assertion library. +* [NSubstitute](http://nsubstitute.github.io/) as the mocking library. -````csharp -namespace Acme.BookStore.Permissions -{ - public static class BookStorePermissions - { - public const string GroupName = "BookStore"; +{{if DB="ef"}} - public static class Books - { - public const string Default = GroupName + ".Books"; - public const string Create = Default + ".Create"; - public const string Edit = Default + ".Edit"; - public const string Delete = Default + ".Delete"; - } - } -} -```` +> The test projects are configured to use **SQLite in-memory** as the database. A separate database instance is created and seeded (with the data seed system) to prepare a fresh database for every test. + +{{else if DB="mongodb"}} + +> **[Mongo2Go](https://github.com/Mongo2Go/Mongo2Go)** library is used to mock the MongoDB database. A separate database instance is created and seeded (with the data seed system) to prepare a fresh database for every test. + +{{end}} -This is a hierarchical way of defining permission names. For example, "create book" permission name was defined as `BookStore.Books.Create`. +## Adding Test Data -### Permission Definitions +If you had created a data seed contributor as described in the [first part](Part-1.md), the same data will be available in your tests. So, you can skip this section. If you haven't created the seed contributor, you can use the `BookStoreTestDataSeedContributor` to seed the same data to be used in the tests below. -You should define permissions before using them. +## Testing The Application Service: BookAppService -Open the `BookStorePermissionDefinitionProvider` class inside the `Acme.BookStore.Application.Contracts` project and change the content as shown below: +Create a test class named `BookAppService_Tests` in the `Acme.BookStore.Application.Tests` project: ````csharp -using Acme.BookStore.Localization; -using Volo.Abp.Authorization.Permissions; -using Volo.Abp.Localization; +using System.Threading.Tasks; +using Shouldly; +using Volo.Abp.Application.Dtos; +using Xunit; -namespace Acme.BookStore.Permissions +namespace Acme.BookStore.Books { - public class BookStorePermissionDefinitionProvider : PermissionDefinitionProvider + public class BookAppService_Tests : BookStoreApplicationTestBase { - public override void Define(IPermissionDefinitionContext context) - { - var bookStoreGroup = context.AddGroup(BookStorePermissions.GroupName, L("Permission:BookStore")); + private readonly IBookAppService _bookAppService; - var booksPermission = bookStoreGroup.AddPermission(BookStorePermissions.Books.Default, L("Permission:Books")); - booksPermission.AddChild(BookStorePermissions.Books.Create, L("Permission:Books.Create")); - booksPermission.AddChild(BookStorePermissions.Books.Edit, L("Permission:Books.Edit")); - booksPermission.AddChild(BookStorePermissions.Books.Delete, L("Permission:Books.Delete")); + public BookAppService_Tests() + { + _bookAppService = GetRequiredService(); } - private static LocalizableString L(string name) + [Fact] + public async Task Should_Get_List_Of_Books() { - return LocalizableString.Create(name); + //Act + var result = await _bookAppService.GetListAsync( + new PagedAndSortedResultRequestDto() + ); + + //Assert + result.TotalCount.ShouldBeGreaterThan(0); + result.Items.ShouldContain(b => b.Name == "1984"); } } } ```` -This class defines a **permission group** (to group permissions on the UI, will be seen below) and **4 permissions** inside this group. Also, **Create**, **Edit** and **Delete** are children of the `BookStorePermissions.Books.Default` permission. A child permission can be selected **only if the parent was selected**. - -Finally, edit the localization file (`en.json` under the `Localization/BookStore` folder of the `Acme.BookStore.Domain.Shared` project) to define the localization keys used above: - -````json -"Permission:BookStore": "Book Store", -"Permission:Books": "Book Management", -"Permission:Books.Create": "Creating new books", -"Permission:Books.Edit": "Editing the books", -"Permission:Books.Delete": "Deleting the books" -```` - -> Localization key names are arbitrary and no forcing rule. But we prefer the convention used above. - -### Permission Management UI +* `Should_Get_List_Of_Books` test simply uses `BookAppService.GetListAsync` method to get and check the list of books. +* We can safely check the book "1984" by its name, because we know that this books is available in the database since we've added it in the seed data. -Once you define the permissions, you can see them on the **permission management modal**. - -Go to the *Administration -> Identity -> Roles* page, select *Permissions* action for the admin role to open the permission management modal: - -![bookstore-permissions-ui](images/bookstore-permissions-ui.png) - -Grant the permissions you want and save the modal. - -## Authorization - -Now, you can use the permissions to authorize the book management. - -### Application Layer & HTTP API - -Open the `BookAppService` class and add set the policy names as the permission names defined above: +Add a new test method to the `BookAppService_Tests` class that creates a new **valid** book: ````csharp -using System; -using Acme.BookStore.Permissions; -using Volo.Abp.Application.Dtos; -using Volo.Abp.Application.Services; -using Volo.Abp.Domain.Repositories; - -namespace Acme.BookStore.Books +[Fact] +public async Task Should_Create_A_Valid_Book() { - public class BookAppService : - CrudAppService< - Book, //The Book entity - BookDto, //Used to show books - Guid, //Primary key of the book entity - PagedAndSortedResultRequestDto, //Used for paging/sorting - CreateUpdateBookDto>, //Used to create/update a book - IBookAppService //implement the IBookAppService - { - public BookAppService(IRepository repository) - : base(repository) + //Act + var result = await _bookAppService.CreateAsync( + new CreateUpdateBookDto { - GetPolicyName = BookStorePermissions.Books.Default; - GetListPolicyName = BookStorePermissions.Books.Default; - CreatePolicyName = BookStorePermissions.Books.Create; - UpdatePolicyName = BookStorePermissions.Books.Edit; - DeletePolicyName = BookStorePermissions.Books.Create; + Name = "New test book 42", + Price = 10, + PublishDate = System.DateTime.Now, + Type = BookType.ScienceFiction } - } + ); + + //Assert + result.Id.ShouldNotBe(Guid.Empty); + result.Name.ShouldBe("New test book 42"); } ```` -Added code to the constructor. Base `CrudAppService` automatically uses these permissions on the CRUD operations. This makes the **application service** secure, but also makes the **HTTP API** secure since this service is automatically used as an HTTP API as explained before (see [auto API controllers](../API/Auto-API-Controllers.md)). - -{{if UI == "MVC"}} - -### Razor Page - -While securing the HTTP API & the application service prevents unauthorized users to use the services, they can still navigate to the book management page. While they will get authorization exception when the page makes the first AJAX call to the server, we should also authorize the page for a better user experience and security. - -Open the `BookStoreWebModule` and add the following code block inside the `ConfigureServices` method: +Add a new test that tries to create an invalid book and fails: ````csharp -Configure(options => +[Fact] +public async Task Should_Not_Create_A_Book_Without_Name() { - options.Conventions.AuthorizePage("/Books/Index", BookStorePermissions.Books.Default); - options.Conventions.AuthorizePage("/Books/CreateModal", BookStorePermissions.Books.Create); - options.Conventions.AuthorizePage("/Books/EditModal", BookStorePermissions.Books.Edit); -}); + var exception = await Assert.ThrowsAsync(async () => + { + await _bookAppService.CreateAsync( + new CreateUpdateBookDto + { + Name = "", + Price = 10, + PublishDate = DateTime.Now, + Type = BookType.ScienceFiction + } + ); + }); + + exception.ValidationErrors + .ShouldContain(err => err.MemberNames.Any(mem => mem == "Name")); +} ```` -Now, unauthorized users are redirected to the **login page**. +* Since the `Name` is empty, ABP will throw an `AbpValidationException`. -#### Hide the New Book Button +The final test class should be as shown below: -The book management page has a *New Book* button that should be invisible if the current user has no *Book Creation* permission. - -![bookstore-new-book-button-small](images/bookstore-new-book-button-small.png) - -Open the `Pages/Books/Index.cshtml` file and change the content as shown below: +````csharp +using System; +using System.Linq; +using System.Threading.Tasks; +using Shouldly; +using Volo.Abp.Application.Dtos; +using Volo.Abp.Validation; +using Xunit; -````html -@page -@using Acme.BookStore.Localization -@using Acme.BookStore.Permissions -@using Acme.BookStore.Web.Pages.Books -@using Microsoft.AspNetCore.Authorization -@using Microsoft.Extensions.Localization -@model IndexModel -@inject IStringLocalizer L -@inject IAuthorizationService AuthorizationService -@section scripts +namespace Acme.BookStore.Books { - -} + public class BookAppService_Tests : BookStoreApplicationTestBase + { + private readonly IBookAppService _bookAppService; + + public BookAppService_Tests() + { + _bookAppService = GetRequiredService(); + } - - - - - @L["Books"] - - - @if (await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Create)) + [Fact] + public async Task Should_Get_List_Of_Books() + { + //Act + var result = await _bookAppService.GetListAsync( + new PagedAndSortedResultRequestDto() + ); + + //Assert + result.TotalCount.ShouldBeGreaterThan(0); + result.Items.ShouldContain(b => b.Name == "1984"); + } + + [Fact] + public async Task Should_Create_A_Valid_Book() + { + //Act + var result = await _bookAppService.CreateAsync( + new CreateUpdateBookDto { - + Name = "New test book 42", + Price = 10, + PublishDate = System.DateTime.Now, + Type = BookType.ScienceFiction } - - - - - - - -```` - -* Added `@inject IAuthorizationService AuthorizationService` to access to the authorization service. -* Used `@if (await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Create))` to check the book creation permission to conditionally render the *New Book* button. - -### JavaScript Side - -Books table in the book management page has an actions button for each row. The actions button includes *Edit* and *Delete* action: - -![bookstore-edit-delete-actions](images/bookstore-edit-delete-actions.png) - -We should hide an action if the current user has not granted for the related permission. Datatables row actions has a `visible` option that can be set to `false` to hide the action item. - -Open the `Pages/Books/Index.js` inside the `Acme.BookStore.Web` project and add a `visible` option to the `Edit` action as shown below: + ); -````js -{ - text: l('Edit'), - visible: abp.auth.isGranted('BookStore.Books.Edit'), //CHECK for the PERMISSION - action: function (data) { - editModal.open({ id: data.record.id }); + //Assert + result.Id.ShouldNotBe(Guid.Empty); + result.Name.ShouldBe("New test book 42"); + } + + [Fact] + public async Task Should_Not_Create_A_Book_Without_Name() + { + var exception = await Assert.ThrowsAsync(async () => + { + await _bookAppService.CreateAsync( + new CreateUpdateBookDto + { + Name = "", + Price = 10, + PublishDate = DateTime.Now, + Type = BookType.ScienceFiction + } + ); + }); + + exception.ValidationErrors + .ShouldContain(err => err.MemberNames.Any(mem => mem == "Name")); + } } } ```` -Do same for the `Delete` action: - -````js -visible: abp.auth.isGranted('BookStore.Books.Delete') -```` - -* `abp.auth.isGranted(...)` is used to check a permission that is defined before. -* `visible` could also be get a function that returns a `bool` if the value will be calculated later, based on some conditions. - -### Menu Item - -Even we have secured all the layers of the book management page, it is still visible on the main menu of the application. We should hide the menu item if the current user has no permission. - -Open the `BookStoreMenuContributor` class, find the code block below: - -````csharp -context.Menu.AddItem( - new ApplicationMenuItem( - "BooksStore", - l["Menu:BookStore"], - icon: "fa fa-book" - ).AddItem( - new ApplicationMenuItem( - "BooksStore.Books", - l["Menu:Books"], - url: "/Books" - ) - ) -); -```` - -And replace this code block with the following: - -````csharp -var bookStoreMenu = new ApplicationMenuItem( - "BooksStore", - l["Menu:BookStore"], - icon: "fa fa-book" -); - -context.Menu.AddItem(bookStoreMenu); +Open the **Test Explorer Window** (use Test -> Windows -> Test Explorer menu if it is not visible) and **Run All** tests: -//CHECK the PERMISSION -if (await context.IsGrantedAsync(BookStorePermissions.Books.Default)) -{ - bookStoreMenu.AddItem(new ApplicationMenuItem( - "BooksStore.Books", - l["Menu:Books"], - url: "/Books" - )); -} -```` +![bookstore-appservice-tests](./images/bookstore-appservice-tests.png) -{{else if UI == "NG"}} +Congratulations, the **green icons** indicates that the tests have been successfully passed! -***Angular UI authorization document is being prepared...*** +## The Next Part -{{end}} \ No newline at end of file +See the [next part](part-5.md) of this tutorial. \ No newline at end of file diff --git a/docs/en/Tutorials/Part-5.md b/docs/en/Tutorials/Part-5.md new file mode 100644 index 0000000000..17dacbd4f7 --- /dev/null +++ b/docs/en/Tutorials/Part-5.md @@ -0,0 +1,316 @@ +# Web Application Development Tutorial - Part 5: Authorization +````json +//[doc-params] +{ + "UI": ["MVC","NG"] +} +```` + +{{ +if UI == "MVC" + DB="ef" + DB_Text="Entity Framework Core" + UI_Text="mvc" +else if UI == "NG" + DB="mongodb" + DB_Text="MongoDB" + UI_Text="angular" +else + DB ="?" + UI_Text="?" +end +}} + +## 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: + +* **{{DB_Text}}** as the ORM provider. +* **{{UI_Value}}** as the UI Framework. + +This tutorial is organized as the following parts; + +- [Part 1: Creating the project and book list page](Part-1.md) +- [Part 2: The book list page](Part-2.md) +- [Part 3: Creating, updating and deleting books](Part-3.md) +- [Part 4: Integration tests](Part-4.md) +- **Part 5: Authorization (this part)** + +### Source Code + +You can find the completed solution on {{if UI == "MVC"}}[the GitHub repository](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore){{else}}[the GitHub repository](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb){{end}}. + +## Permissions + +ABP Framework provides an [authorization system](../Authorization.md) based on the ASP.NET Core's [authorization infrastructure](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/introduction). One major feature added on top of the standard authorization infrastructure is the **permission system** which allows to define permissions and enable/disable per role, user or client. + +### Permission Names + +A permission must have a unique name (a `string`). The best way is to define it as a `const`, so we can reuse the permission name. + +Open the `BookStorePermissions` class and change the content as shown below: + +````csharp +namespace Acme.BookStore.Permissions +{ + public static class BookStorePermissions + { + public const string GroupName = "BookStore"; + + public static class Books + { + public const string Default = GroupName + ".Books"; + public const string Create = Default + ".Create"; + public const string Edit = Default + ".Edit"; + public const string Delete = Default + ".Delete"; + } + } +} +```` + +This is a hierarchical way of defining permission names. For example, "create book" permission name was defined as `BookStore.Books.Create`. + +### Permission Definitions + +You should define permissions before using them. + +Open the `BookStorePermissionDefinitionProvider` class inside the `Acme.BookStore.Application.Contracts` project and change the content as shown below: + +````csharp +using Acme.BookStore.Localization; +using Volo.Abp.Authorization.Permissions; +using Volo.Abp.Localization; + +namespace Acme.BookStore.Permissions +{ + public class BookStorePermissionDefinitionProvider : PermissionDefinitionProvider + { + public override void Define(IPermissionDefinitionContext context) + { + var bookStoreGroup = context.AddGroup(BookStorePermissions.GroupName, L("Permission:BookStore")); + + var booksPermission = bookStoreGroup.AddPermission(BookStorePermissions.Books.Default, L("Permission:Books")); + booksPermission.AddChild(BookStorePermissions.Books.Create, L("Permission:Books.Create")); + booksPermission.AddChild(BookStorePermissions.Books.Edit, L("Permission:Books.Edit")); + booksPermission.AddChild(BookStorePermissions.Books.Delete, L("Permission:Books.Delete")); + } + + private static LocalizableString L(string name) + { + return LocalizableString.Create(name); + } + } +} +```` + +This class defines a **permission group** (to group permissions on the UI, will be seen below) and **4 permissions** inside this group. Also, **Create**, **Edit** and **Delete** are children of the `BookStorePermissions.Books.Default` permission. A child permission can be selected **only if the parent was selected**. + +Finally, edit the localization file (`en.json` under the `Localization/BookStore` folder of the `Acme.BookStore.Domain.Shared` project) to define the localization keys used above: + +````json +"Permission:BookStore": "Book Store", +"Permission:Books": "Book Management", +"Permission:Books.Create": "Creating new books", +"Permission:Books.Edit": "Editing the books", +"Permission:Books.Delete": "Deleting the books" +```` + +> Localization key names are arbitrary and no forcing rule. But we prefer the convention used above. + +### Permission Management UI + +Once you define the permissions, you can see them on the **permission management modal**. + +Go to the *Administration -> Identity -> Roles* page, select *Permissions* action for the admin role to open the permission management modal: + +![bookstore-permissions-ui](images/bookstore-permissions-ui.png) + +Grant the permissions you want and save the modal. + +## Authorization + +Now, you can use the permissions to authorize the book management. + +### Application Layer & HTTP API + +Open the `BookAppService` class and add set the policy names as the permission names defined above: + +````csharp +using System; +using Acme.BookStore.Permissions; +using Volo.Abp.Application.Dtos; +using Volo.Abp.Application.Services; +using Volo.Abp.Domain.Repositories; + +namespace Acme.BookStore.Books +{ + public class BookAppService : + CrudAppService< + Book, //The Book entity + BookDto, //Used to show books + Guid, //Primary key of the book entity + PagedAndSortedResultRequestDto, //Used for paging/sorting + CreateUpdateBookDto>, //Used to create/update a book + IBookAppService //implement the IBookAppService + { + public BookAppService(IRepository repository) + : base(repository) + { + GetPolicyName = BookStorePermissions.Books.Default; + GetListPolicyName = BookStorePermissions.Books.Default; + CreatePolicyName = BookStorePermissions.Books.Create; + UpdatePolicyName = BookStorePermissions.Books.Edit; + DeletePolicyName = BookStorePermissions.Books.Create; + } + } +} +```` + +Added code to the constructor. Base `CrudAppService` automatically uses these permissions on the CRUD operations. This makes the **application service** secure, but also makes the **HTTP API** secure since this service is automatically used as an HTTP API as explained before (see [auto API controllers](../API/Auto-API-Controllers.md)). + +{{if UI == "MVC"}} + +### Razor Page + +While securing the HTTP API & the application service prevents unauthorized users to use the services, they can still navigate to the book management page. While they will get authorization exception when the page makes the first AJAX call to the server, we should also authorize the page for a better user experience and security. + +Open the `BookStoreWebModule` and add the following code block inside the `ConfigureServices` method: + +````csharp +Configure(options => +{ + options.Conventions.AuthorizePage("/Books/Index", BookStorePermissions.Books.Default); + options.Conventions.AuthorizePage("/Books/CreateModal", BookStorePermissions.Books.Create); + options.Conventions.AuthorizePage("/Books/EditModal", BookStorePermissions.Books.Edit); +}); +```` + +Now, unauthorized users are redirected to the **login page**. + +#### Hide the New Book Button + +The book management page has a *New Book* button that should be invisible if the current user has no *Book Creation* permission. + +![bookstore-new-book-button-small](images/bookstore-new-book-button-small.png) + +Open the `Pages/Books/Index.cshtml` file and change the content as shown below: + +````html +@page +@using Acme.BookStore.Localization +@using Acme.BookStore.Permissions +@using Acme.BookStore.Web.Pages.Books +@using Microsoft.AspNetCore.Authorization +@using Microsoft.Extensions.Localization +@model IndexModel +@inject IStringLocalizer L +@inject IAuthorizationService AuthorizationService +@section scripts +{ + +} + + + + + + @L["Books"] + + + @if (await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Create)) + { + + } + + + + + + + +```` + +* Added `@inject IAuthorizationService AuthorizationService` to access to the authorization service. +* Used `@if (await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Create))` to check the book creation permission to conditionally render the *New Book* button. + +### JavaScript Side + +Books table in the book management page has an actions button for each row. The actions button includes *Edit* and *Delete* action: + +![bookstore-edit-delete-actions](images/bookstore-edit-delete-actions.png) + +We should hide an action if the current user has not granted for the related permission. Datatables row actions has a `visible` option that can be set to `false` to hide the action item. + +Open the `Pages/Books/Index.js` inside the `Acme.BookStore.Web` project and add a `visible` option to the `Edit` action as shown below: + +````js +{ + text: l('Edit'), + visible: abp.auth.isGranted('BookStore.Books.Edit'), //CHECK for the PERMISSION + action: function (data) { + editModal.open({ id: data.record.id }); + } +} +```` + +Do same for the `Delete` action: + +````js +visible: abp.auth.isGranted('BookStore.Books.Delete') +```` + +* `abp.auth.isGranted(...)` is used to check a permission that is defined before. +* `visible` could also be get a function that returns a `bool` if the value will be calculated later, based on some conditions. + +### Menu Item + +Even we have secured all the layers of the book management page, it is still visible on the main menu of the application. We should hide the menu item if the current user has no permission. + +Open the `BookStoreMenuContributor` class, find the code block below: + +````csharp +context.Menu.AddItem( + new ApplicationMenuItem( + "BooksStore", + l["Menu:BookStore"], + icon: "fa fa-book" + ).AddItem( + new ApplicationMenuItem( + "BooksStore.Books", + l["Menu:Books"], + url: "/Books" + ) + ) +); +```` + +And replace this code block with the following: + +````csharp +var bookStoreMenu = new ApplicationMenuItem( + "BooksStore", + l["Menu:BookStore"], + icon: "fa fa-book" +); + +context.Menu.AddItem(bookStoreMenu); + +//CHECK the PERMISSION +if (await context.IsGrantedAsync(BookStorePermissions.Books.Default)) +{ + bookStoreMenu.AddItem(new ApplicationMenuItem( + "BooksStore.Books", + l["Menu:Books"], + url: "/Books" + )); +} +```` + +{{else if UI == "NG"}} + +***Angular UI authorization document is being prepared...*** + +{{end}} \ No newline at end of file diff --git a/docs/en/docs-nav.json b/docs/en/docs-nav.json index b691ea9b07..239f071619 100644 --- a/docs/en/docs-nav.json +++ b/docs/en/docs-nav.json @@ -26,19 +26,27 @@ "text": "Tutorials", "items": [ { - "text": "Application Development", + "text": "Web Application Development", "items": [ { - "text": "Part-1: Creating a new solution and listing items", + "text": "1: Creating the Server Side", "path": "Tutorials/Part-1.md" }, { - "text": "Part-2: CRUD operations", + "text": "2: The Book List Page", "path": "Tutorials/Part-2.md" }, { - "text": "Part-3: Integration tests", + "text": "3: Creating, Updating and Deleting Books", "path": "Tutorials/Part-3.md" + }, + { + "text": "4: Integration Tests", + "path": "Tutorials/Part-4.md" + }, + { + "text": "5: Authorization", + "path": "Tutorials/Part-5.md" } ] }