diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 366972c165..6ba3ad7a6d 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -17,7 +17,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-dotnet@master with: - dotnet-version: 3.1.102 + dotnet-version: 5.0.100 - name: Build All run: .\build-all.ps1 diff --git a/.gitignore b/.gitignore index 5b47e32794..b9576fda4c 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ *.user *.userosscache *.sln.docstates +*.editorconfig # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs @@ -304,3 +305,7 @@ modules/virtual-file-explorer/app/Volo.Abp.VirtualFileExplorer.DemoApp/Logs/ /templates/app/angular/package-lock.json /modules/client-simulation/demo/Volo.ClientSimulation.Demo/package-lock.json abp-build-config.json +/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Pages/Test/ + +# Identity Server temp signature file +tempkey.jwk \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000000..dea0a6c6f7 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,29 @@ + + + + + 5.0.0 + + + 16.6.1 + + + 4.2.2 + + + 3.0.2 + + + 2.4.1 + + + 2.4.1 + + + 2.4.2 + + + 2.2.14 + + + \ No newline at end of file diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 0000000000..a0572030a2 --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 9dffe69012..cd27da8fe0 100644 --- a/README.md +++ b/README.md @@ -5,19 +5,102 @@ [![MyGet (with prereleases)](https://img.shields.io/myget/abp-nightly/vpre/Volo.Abp.svg?style=flat-square)](https://docs.abp.io/en/abp/latest/Nightly-Builds) [![NuGet Download](https://img.shields.io/nuget/dt/Volo.Abp.Core.svg?style=flat-square)](https://www.nuget.org/packages/Volo.Abp.Core) -ABP is an **open source application framework** focused on ASP.NET Core based web application development, but also supports developing other type of applications. +ABP Framework is a complete **infrastructure** based on the **ASP.NET Core** to create **modern web applications** and **APIs** by following the software development **best practices** and the **latest technologies**. -## Links +## Getting Started -* Official Web Site +- [Getting Started Guide](https://docs.abp.io/en/abp/latest/Getting-Started) is the easiest way to start a new web application with the ABP Framework. +- [Web Application Development Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1) is a complete tutorial to develop a full stack web application. + +### Quick Start + +Install the ABP CLI: + +````bash +> dotnet tool install -g Volo.Abp.Cli +```` + +Create a new solution: + +````bash +> abp new BookStore -u mvc -d ef +```` + +> See the [CLI documentation](https://docs.abp.io/en/abp/latest/CLI) for all available options. + +### UI Framework Options + + + +### Database Provider Options + + + +## What ABP Provides? + +ABP provides a **full stack developer experience**. + +### Architecture + + + +ABP offers a complete, **modular** and **layered** software architecture based on **[Domain Driven Design](https://docs.abp.io/en/abp/latest/Domain-Driven-Design)** principles and patterns. It also provides the necessary infrastructure and guiding to [implement this architecture](https://docs.abp.io/en/abp/latest/Domain-Driven-Design-Implementation-Guide). + +ABP Framework is suitable for **[microservice solutions](https://docs.abp.io/en/abp/latest/Microservice-Architecture)** as well as monolithic applications. + +### Infrastructure + +There are a lot of features provided by the ABP Framework to achieve real world scenarios easier, like [Event Bus](https://docs.abp.io/en/abp/latest/Event-Bus), [Background Job System](https://docs.abp.io/en/abp/latest/Background-Jobs), [Audit Logging](https://docs.abp.io/en/abp/latest/Audit-Logging), [BLOB Storing](https://docs.abp.io/en/abp/latest/Blob-Storing), [Data Seeding](https://docs.abp.io/en/abp/latest/Data-Seeding), [Data Filtering](https://docs.abp.io/en/abp/latest/Data-Filtering), etc. + +### Cross Cutting Concerns + +ABP also simplifies (and even automates wherever possible) cross cutting concerns and common non-functional requirements like [Exception Handling](https://docs.abp.io/en/abp/latest/Exception-Handling), [Validation](https://docs.abp.io/en/abp/latest/Validation), [Authorization](https://docs.abp.io/en/abp/latest/Authorization), [Localization](https://docs.abp.io/en/abp/latest/Localization), [Caching](https://docs.abp.io/en/abp/latest/Caching), [Dependency Injection](https://docs.abp.io/en/abp/latest/Dependency-Injection), [Setting Management](https://docs.abp.io/en/abp/latest/Settings), etc. + +### Application Modules + +ABP is a modular framework and the Application Modules provide **pre-built application functionalities**; + +- [**Account**](https://docs.abp.io/en/abp/latest/Modules/Account): Provides UI for the account management and allows user to login/register to the application. +- **[Identity](https://docs.abp.io/en/abp/latest/Modules/Identity)**: Manages organization units, roles, users and their permissions, based on the Microsoft Identity library. +- [**IdentityServer**](https://docs.abp.io/en/abp/latest/Modules/IdentityServer): Integrates to IdentityServer4. +- [**Tenant Management**](https://docs.abp.io/en/abp/latest/Modules/Tenant-Management): Manages tenants for a [multi-tenant](https://docs.abp.io/en/abp/latest/Multi-Tenancy) (SaaS) application. + +See the [Application Modules](https://docs.abp.io/en/abp/latest/Modules/Index) document for all pre-built modules. + +### Startup Templates + +The [Startup templates](https://docs.abp.io/en/abp/latest/Startup-Templates/Index) are pre-built Visual Studio solution templates. You can create your own solution based on these templates to **immediately start your development**. + +## ABP Community + +### ABP Community Web Site + +The [ABP Community](https://community.abp.io/) is a website to publish **articles** and share **knowledge** about the ABP Framework. You can also create content for the community! + +### Blog + +Follow the [ABP Blog](https://blog.abp.io/) to learn the latest happenings in the ABP Framework. + +### Samples + +See the [sample projects](https://docs.abp.io/en/abp/latest/Samples/Index) built with the ABP Framework. + +### Want to Contribute? + +ABP is a community-driven open source project. See [the contribution guide](https://docs.abp.io/en/abp/latest/Contribution/Index) if you want to be a part of this project. + +## Official Links + +* Main Web Site * Get Started * Features - * Documentation - * Samples - * Blog +* Documentation +* Samples +* Blog +* Community * Stack overflow * Twitter -## Contribution +## Support the ABP Framework -ABP is an open source platform. Check [the contribution guide](docs/en/Contribution/Index.md) if you want to contribute to the project. +Love ABP Framework? **Please give a star** to this repository :star: \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/de-DE.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/de-DE.json new file mode 100644 index 0000000000..b0418f082f --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/de-DE.json @@ -0,0 +1,14 @@ +{ + "culture": "de-DE", + "texts": { + "Account": "ABP Benutzerkonto - Anmeldung & Registrierung | ABP.IO", + "Welcome": "Willkommen", + "UseOneOfTheFollowingLinksToContinue": "Nutzen Sie einen der nachfolgenden Links um fortzusetzen", + "FrameworkHomePage": "Framework Website", + "FrameworkDocumentation": "Framework Dokumentation", + "OfficialBlog": "Offizieller Blog", + "CommercialHomePage": "Commercial Website", + "CommercialSupportWebSite": "Commercial Support-Website", + "CommunityWebSite": "ABP Community-Website" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/es.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/es.json new file mode 100644 index 0000000000..44ec873da0 --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/es.json @@ -0,0 +1,14 @@ +{ + "culture": "es", + "texts": { + "Account": "Cuenta de ABP - Iniciar sesión y registrarse | ABP.IO", + "Welcome": "Bienvenido", + "UseOneOfTheFollowingLinksToContinue": "Usa uno de los siguientes links para continuar", + "FrameworkHomePage": "Página de inicio del framework", + "FrameworkDocumentation": "Documentación del framework", + "OfficialBlog": "Blog Oficial", + "CommercialHomePage": "Página de inicio comercial", + "CommercialSupportWebSite": "Sitio web de soporte comercial", + "CommunityWebSite": "Sitio web comunidad ABP" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/zh-Hans.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/zh-Hans.json index adc808ed7e..0d66f1288d 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/zh-Hans.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Account/Localization/Resources/zh-Hans.json @@ -8,6 +8,7 @@ "FrameworkDocumentation": "框架文档", "OfficialBlog": "官方博客", "CommercialHomePage": "商业版首页", - "CommercialSupportWebSite": "商业版支持网站" + "CommercialSupportWebSite": "商业版支持网站", + "CommunityWebSite": "ABP社区网站" } } \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/de-DE.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/de-DE.json new file mode 100644 index 0000000000..60725c437b --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/de-DE.json @@ -0,0 +1,199 @@ +{ + "culture": "de-DE", + "texts": { + "Permission:Organizations": "Organisationen", + "Permission:Manage": "Organisationen verwalten", + "Permission:DiscountRequests": "Rabattanfragen", + "Permission:DiscountManage": "Rabattanfragen verwalten", + "Permission:Disable": "Deaktivieren", + "Permission:Enable": "Aktivieren", + "Permission:EnableSendEmail": "E-Mail-Senden aktivieren", + "Permission:SendEmail": "E-Mail senden", + "Permission:NpmPackages": "NPM-Pakete", + "Permission:NugetPackages": "Nuget-Pakete", + "Permission:Maintenance": "Wartung", + "Permission:Maintain": "Warten", + "Permission:ClearCaches": "Caches leeren", + "Permission:Modules": "Module", + "Permission:Packages": "Pakete", + "Permission:Edit": "Bearbeiten", + "Permission:Delete": "Löschen", + "Permission:Create": "Erstellen", + "Permission:Accounting": "Abrechnung", + "Permission:Accounting:Quotation": "Angebot", + "Permission:Accounting:Invoice": "Rechnung", + "Menu:Organizations": "Organisationen", + "Menu:Accounting": "Abrechnung", + "Menu:Packages": "Pakete", + "Menu:DiscountRequests": "Rabattanfragen", + "NpmPackageDeletionWarningMessage": "Dieses NPM-Paket wird entfernt. Bestätigen Sie das?", + "NugetPackageDeletionWarningMessage": "Dieses Nuget-Paket wird entfernt. Bestägiten Sie das?", + "ModuleDeletionWarningMessage": "Dieses Modul wird entfernt. Bestätigen Sie das?", + "Name": "Name", + "DisplayName": "Anzeigename", + "ShortDescription": "Kurzbeschreibung", + "NameFilter": "Name", + "CreationTime": "Erstellungszeitpunkt", + "IsPro": "Ist pro", + "ShowOnModuleList": "In Modulliste anzeigen", + "EfCoreConfigureMethodName": "Methodenname konfigurieren", + "IsProFilter": "Ist pro", + "ApplicationType": "Anwendungstyp", + "Target": "Ziel", + "TargetFilter": "Ziel", + "ModuleClass": "Modulklasse", + "NugetPackageTarget.DomainShared": "Gemeinsame Domain", + "NugetPackageTarget.Domain": "Domain", + "NugetPackageTarget.Application": "Anwendung", + "NugetPackageTarget.ApplicationContracts": "Anwedungsverträge", + "NugetPackageTarget.HttpApi": "HTTP-API", + "NugetPackageTarget.HttpApiClient": "HTTP-API-Client", + "NugetPackageTarget.Web": "Web", + "NugetPackageTarget.EntityFrameworkCore": "DeleteAllEntityFramework Core", + "NugetPackageTarget.MongoDB": "MongoDB", + "Edit": "Bearbeiten", + "Delete": "Löschen", + "Refresh": "Aktualisieren", + "NpmPackages": "NPM-Pakete", + "NugetPackages": "Nuget-Pakete", + "NpmPackageCount": "NPM-Paketanzahl", + "NugetPackageCount": "Nuget-Paketanzahl", + "Module": "Module", + "ModuleInfo": "Modulinfo", + "CreateANpmPackage": "Erstellen Sie ein NPM Paket", + "CreateAModule": "Erstellen Sie in Modul", + "CreateANugetPackage": "Erstellen Sei ein Nuget-Paket", + "AddNew": "Neu hinzufügen", + "PackageAlreadyExist{0}": "\"{0}\" Paket ist bereits hinzugefügt.", + "ModuleAlreadyExist{0}": "\"{0}\" Modul ist bereits hinzugefügt.", + "ClearCache": "Cache leeren", + "SuccessfullyCleared": "Erfolgreich geleert", + "Menu:NpmPackages": "NPM-Pakete", + "Menu:Modules": "Module", + "Menu:Maintenance": "Wartung", + "Menu:NugetPackages": "Nuget-Pakete", + "CreateAnOrganization": "Erstellen Sie eine Organisation", + "Organizations": "Organisationen", + "LongName": "Lange Name", + "LicenseType": "Lizenztyp", + "MissingLicenseTypeField": "Das Feld Lizenztyp ist erforderlich!", + "LicenseStartTime": "Startzeit der Lizenz", + "LicenseEndTime": "Endzeit der Lizenz", + "AllowedDeveloperCount": "Zulässige Entwickleranzahl", + "UserNameOrEmailAddress": "Benutzername oder E-Mail-Adresse", + "AddOwner": "Besitzer hinzufügen", + "UserName": "Benutzername", + "Email": "E-Mail", + "Developers": "Entwickler", + "AddDeveloper": "Entwickler hinzufügen", + "Create": "Erstellen", + "UserNotFound": "Benutzer nicht gefunden", + "{0}WillBeRemovedFromDevelopers": "{0} wird von den Entwicklern entfernt. Bestätigen Sie das?", + "{0}WillBeRemovedFromOwners": "{0} wird von den Besitzern entfernt. Bestätigen Sie das?", + "Computers": "Computer", + "UniqueComputerId": "Eindeutig Computer-ID", + "LastSeenDate": "Zuletzt gesehenes Datum", + "{0}Computer{1}WillBeRemovedFromRecords": "Computer von {0} ({1}) wird aus den Datensätzen entfernt", + "OrganizationDeletionWarningMessage": "Organisation wird gelöscht", + "DeletingLastOwnerWarningMessage": "Eine Organisation muss zumindest einen Besitzer aufweisen! Daher können Sie diesen Besitzer nicht entfernen", + "This{0}AlreadyExistInThisOrganization": "Dies {0} existiert bereits in dieser Organisation", + "AreYouSureYouWantToDeleteAllComputers": "Sind Sie sicher, dass Sie alle Computer löschen möchten?", + "DeleteAll": "Alles Löschen", + "DoYouWantToCreateNewUser": "Möchten Sie einen neuen Benutzer erstellen?", + "MasterModules": "Master-Module", + "OrganizationName": "Organisationsname", + "CreationDate": "Erstellungsdatum", + "LicenseStartDate": "Startdatum der Lizenz", + "LicenseEndDate": "Enddatum der Lizenz", + "OrganizationNamePlaceholder": "Organisationsname...", + "TotalQuestionCountPlaceholder": "Gesamtzahl der Fragen...", + "RemainingQuestionCountPlaceholder": "Anzahl verbleibender Fragen...", + "LicenseTypePlaceholder": "Lizenztyp...", + "CreationDatePlaceholder": "Erstellungsdatum...", + "LicenseStartDatePlaceholder": "Startdatum der Lizenz...", + "LicenseEndDatePlaceholder": "Enddatum der Lizenz...", + "UsernameOrEmail": "Benutzername oder E-Mail-Adresse", + "UsernameOrEmailPlaceholder": "Benutzername oder E-Mail-Adresse...", + "Member": "Mitglied", + "PurchaseOrderNo": "Bestellnummer", + "QuotationDate": "Angebotsdatum", + "CompanyName": "Firmenname", + "CompanyAddress": "Firmenanschrift", + "Price": "Preis", + "DiscountText": "Rabatttext", + "DiscountQuantity": "Rabattmenge", + "DiscountPrice": "Rabattpreis", + "Quotation": "Angebot", + "ExtraText": "Zusätzlicher Text", + "ExtraAmount": "Zusätzliche Menge", + "DownloadQuotation": "Angebot herunterladen", + "Invoice": "Rechnung", + "TaxNumber": "Steuernummer", + "InvoiceNumber": "Rechnungsnummer", + "InvoiceDate": "Rechnungsdatum", + "InvoiceNote": "Rechnungsnotiz", + "Quantity": "Menge", + "AddProduct": "Produkt hinzufügen", + "AddProductWarning": "Sie müssen ein Produkt hinzufügen!", + "TotalPrice": "Gesamtpreis", + "Generate": "Generieren", + "MissingQuantityField": "Das Feld Menge ist erforderlich!", + "MissingPriceField": "Das Feld Preis ist erforderlich!", + "CodeUsageStatus": "Status", + "Country": "Land", + "DeveloperCount": "Entwickleranzahl", + "RequestCode": "Anfrage-Code", + "WebSite": "Webseite", + "GithubUsername": "Github Benutzername", + "PhoneNumber": "Telefonnummer", + "ProjectDescription": "Projektbeschreibung", + "Referrer": "Referrer", + "DiscountRequests": "Rabattanfrage", + "Copylink": "Link kopieren", + "Disable": "Deaktivieren", + "Enable": "Aktivieren", + "EnableSendEmail": "E-Mail-Senden aktivieren", + "SendEmail": "E-Mail senden", + "SuccessfullyDisabled": "Erfolgreich deaktiviert", + "SuccessfullyEnabled": "Erfolgreich aktiviert", + "EmailSent": "E-Mail gesendet", + "SuccessfullySent": "Erfolgreich gesendet", + "SuccessfullyDeleted": "Erfolgreich gelöscht", + "DiscountRequestDeletionWarningMessage": "Rabattanfrage wird gelöscht", + "BusinessType": "Unternehmensart", + "TotalQuestionCount": "Gesamtzahl der Fragen", + "RemainingQuestionCount": "Anzahl verbleibender Fragen", + "TotalQuestionMustBeGreaterWarningMessage": "TotalQuestionCount muss größer sein als RemainingQuestionCount !", + "QuestionCountsMustBeGreaterThanZero": "TotalQuestionCount und RemainingQuestionCount müssen Null oder größer als Null sein !", + "UnlimitedQuestionCount": "Unbegrenzte Anzahl von Fragen", + "Notes": "Anmerkungen", + "Menu:Community": "Community", + "Menu:Articles": "Beiträge", + "Wait": "Warten", + "Approve": "Genehmigen", + "Reject": "Ablehnen", + "Details": "Details", + "Url": "URL", + "Title": "Titel", + "ContentSource": "Inhaltsquelle", + "Status": "Status", + "ReadArticle": "Beitrag lesen", + "ArticleHasBeenWaiting": "Beitrag hat gewartet", + "ArticleHasBeenApproved": "Beitrag wurde genehmigt", + "ArticleHasBeenRejected": "Beitrag wurde abgelehnt", + "Permission:Community": "Community", + "Permission:CommunityArticle": "Beitrag", + "Link": "Link", + "Enum:ContentSource:0": "Github", + "Enum:ContentSource:1": "Extern", + "Enum:Status:0": "Wartend", + "Enum:Status:1": "Abgelehnt", + "Enum:Status:2": "Genehmigt", + "Summary": "Zusammenfassung", + "AuthorName": "Autorenname", + "CoverImage": "Titelbild", + "RemoveCacheConfirmationMessage": "Sind Sie sicher, dass Sie den Cache für den Artikel \"{0}\" entfernen wollen?", + "SuccessfullyRemoved": "Erfolgreich geleert", + "RemoveCache": "Cache entfernen" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/es.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/es.json new file mode 100644 index 0000000000..89ef8706e0 --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/es.json @@ -0,0 +1,199 @@ +{ + "culture": "es", + "texts": { + "Permission:Organizations": "Organizaciones", + "Permission:Manage": "Gestionar organizaciones", + "Permission:DiscountRequests": "Solicitudes de descuento", + "Permission:DiscountManage": "Gestionar solicitudes de descuento", + "Permission:Disable": "Desactivar", + "Permission:Enable": "Activar", + "Permission:EnableSendEmail": "Activar enviar email", + "Permission:SendEmail": "Enviar email", + "Permission:NpmPackages": "Paquetes NPM", + "Permission:NugetPackages": "Paquetes Nuget", + "Permission:Maintenance": "Mantenimiento", + "Permission:Maintain": "Mantener", + "Permission:ClearCaches": "Borrar cachés", + "Permission:Modules": "Módulos", + "Permission:Packages": "Paquetes", + "Permission:Edit": "Editar", + "Permission:Delete": "Borrar", + "Permission:Create": "Crear", + "Permission:Accounting": "Contabilidad", + "Permission:Accounting:Quotation": "Cotización", + "Permission:Accounting:Invoice": "Factura", + "Menu:Organizations": "Organizaciones", + "Menu:Accounting": "Contabilidad", + "Menu:Packages": "Paquetes", + "Menu:DiscountRequests": "Solicitudes de descuento", + "NpmPackageDeletionWarningMessage": "Este NPM paquete será borrado. ¿Quieres confirmar?", + "NugetPackageDeletionWarningMessage": "Este NPM paquete será borrado. ¿Quieres confirmar?", + "ModuleDeletionWarningMessage": "Este NPM paquete será borrado. ¿Quieres confirmar?", + "Name": "Nombre", + "DisplayName": "Nombre para mostrar", + "ShortDescription": "Descripción corta", + "NameFilter": "Nombre", + "CreationTime": "Fecha de creación", + "IsPro": "Es pro", + "ShowOnModuleList": "Mostrar en la lista de módulos", + "EfCoreConfigureMethodName": "configurar nombre de método", + "IsProFilter": "Es pro", + "ApplicationType": "tipo de aplicación", + "Target": "Destino", + "TargetFilter": "Destino", + "ModuleClass": "Módulo de clase", + "NugetPackageTarget.DomainShared": "Dominio compartido", + "NugetPackageTarget.Domain": "Dominio", + "NugetPackageTarget.Application": "Aplicación", + "NugetPackageTarget.ApplicationContracts": "Contratos de aplicación", + "NugetPackageTarget.HttpApi": "Http Api", + "NugetPackageTarget.HttpApiClient": "Cliente Http Api", + "NugetPackageTarget.Web": "Web", + "NugetPackageTarget.EntityFrameworkCore": "Delete todo EntityFramework Core", + "NugetPackageTarget.MongoDB": "MongoDB", + "Edit": "Editar", + "Delete": "Borrar", + "Refresh": "Refrescar", + "NpmPackages": "Paquetes NPM", + "NugetPackages": "Paquetes Nuget", + "NpmPackageCount": "Número de paquetes NPM", + "NugetPackageCount": "Número de paquetes Nuget", + "Module": "Módulos", + "ModuleInfo": "Info de módulo", + "CreateANpmPackage": "Crear un paquete NPM", + "CreateAModule": "Crear un módulo", + "CreateANugetPackage": "Crear un paquete de Nuget", + "AddNew": "Añadir nuevo", + "PackageAlreadyExist{0}": "\"{0}\" paquete ya se encuentra añadido", + "ModuleAlreadyExist{0}": "\"{0}\" módulo ya se encuentra añadido.", + "ClearCache": "Borrar caché", + "SuccessfullyCleared": "Borrado satisfactoriamente", + "Menu:NpmPackages": "Paquetes de NPM", + "Menu:Modules": "Módulos", + "Menu:Maintenance": "Mantenimiento", + "Menu:NugetPackages": "Paquetes Nuget", + "CreateAnOrganization": "Crear una organización", + "Organizations": "Organizaciones", + "LongName": "Nombre largo", + "LicenseType": "Tipo de licencia", + "MissingLicenseTypeField": "El campo tipo de licencia es requerido!", + "LicenseStartTime": "Fecha de inicio de licencia", + "LicenseEndTime": "Fecha de caducidad de licencia", + "AllowedDeveloperCount": "Número de desarrolladores permitidos", + "UserNameOrEmailAddress": "Nombre de usuario o", + "AddOwner": "Añadir propietario", + "UserName": "Nombre de usuario", + "Email": "Email", + "Developers": "Desarrolladores", + "AddDeveloper": "Añadir desarrollador", + "Create": "Crear", + "UserNotFound": "Usuario no encontrado", + "{0}WillBeRemovedFromDevelopers": "{0} será eliminado de desarrolladores, ¿deseas continuar?", + "{0}WillBeRemovedFromOwners": "{0} será eliminado de propietarios, ¿deseas continuar?", + "Computers": "Ordenadores", + "UniqueComputerId": "Id única de ordenador", + "LastSeenDate": "Fecha de visto por última vez", + "{0}Computer{1}WillBeRemovedFromRecords": "El ordenador {0} ({1}) será eliminado de los registros", + "OrganizationDeletionWarningMessage": "La organización será eliminada", + "DeletingLastOwnerWarningMessage": "Una organización debe tener al menos un propietario!. Por lo tanto, tu no puedes eliminar este propietario", + "This{0}AlreadyExistInThisOrganization": "Este/a {0} ya existe en esta organización", + "AreYouSureYouWantToDeleteAllComputers": "Estás seguro tu quieres eliminar todos los ordenadores", + "DeleteAll": "Eliminar todo", + "DoYouWantToCreateNewUser": "¿Quieres crear un nuevo usuario?", + "MasterModules": "Módulos maestros", + "OrganizationName": "Nombre de organización", + "CreationDate": "Fecha de creación", + "LicenseStartDate": "Fecha de inicio de licencia", + "LicenseEndDate": "Fecha de caducidad de licencia", + "OrganizationNamePlaceholder": "Nombre de organización...", + "TotalQuestionCountPlaceholder": "Número total de preguntas...", + "RemainingQuestionCountPlaceholder": "Número de preguntas pendientes", + "LicenseTypePlaceholder": "Tipo de licencia...", + "CreationDatePlaceholder": "Fecha de creación...", + "LicenseStartDatePlaceholder": "Fecha de inicio de licencia...", + "LicenseEndDatePlaceholder": "Fecha de caducidad de licencia...", + "UsernameOrEmail": "Usuario o email", + "UsernameOrEmailPlaceholder": "Usuario o email...", + "Member": "Miembro", + "PurchaseOrderNo": "Número de orden de compra", + "QuotationDate": "Fecha de presupuesto", + "CompanyName": "Nombre de empresa", + "CompanyAddress": "Dirección de empresa", + "Price": "Precio", + "DiscountText": "Texto de descuento", + "DiscountQuantity": "Cantidad de descuento", + "DiscountPrice": "Precio de descuento", + "Quotation": "Presupuesto", + "ExtraText": "Texto extra", + "ExtraAmount": "Cantidad extra", + "DownloadQuotation": "Descarga el presupuesto", + "Invoice": "Factura", + "TaxNumber": "Identificación fiscal", + "InvoiceNumber": "Número de factura", + "InvoiceDate": "Fecha de factura", + "InvoiceNote": "Nota de factura", + "Quantity": "Cantidad", + "AddProduct": "Añadir producto", + "AddProductWarning": "Tu necesitas añadir un producto!", + "TotalPrice": "Precio total", + "Generate": "Generar", + "MissingQuantityField": "El campo cantidad es requerido!", + "MissingPriceField": "El campo precio es requerido!", + "CodeUsageStatus": "Estado", + "Country": "País", + "DeveloperCount": "Cuentas de desarrollo", + "RequestCode": "Solicitud de código", + "WebSite": "Sitio web", + "GithubUsername": "Nombre de usuario Github", + "PhoneNumber": "Número de teléfono", + "ProjectDescription": "Descripción del proyecto", + "Referrer": "Referente", + "DiscountRequests": "Solicitud de descuento", + "Copylink": "Copiar Link", + "Disable": "Deshabilitar", + "Enable": "Habilitar", + "EnableSendEmail": "Habilitar el envío de Email", + "SendEmail": "Enviar Email", + "SuccessfullyDisabled": "Deshabilitado correctamente", + "SuccessfullyEnabled": "Habilitado correctamente", + "EmailSent": "Email enviado", + "SuccessfullySent": "Enviado correctamente", + "SuccessfullyDeleted": "Borrado correctamente", + "DiscountRequestDeletionWarningMessage": "La solicitud de descuento será borrada", + "BusinessType": "Tipo de negocio", + "TotalQuestionCount": "Número total de preguntas", + "RemainingQuestionCount": "Número de preguntas restantes", + "TotalQuestionMustBeGreaterWarningMessage": "TotalQuestionCount debe ser mayor que RemainingQuestionCount !", + "QuestionCountsMustBeGreaterThanZero": "TotalQuestionCount y RemainingQuestionCount debe ser cero o más grande que cero !", + "UnlimitedQuestionCount": "Número de preguntas ilimitadas", + "Notes": "Notas", + "Menu:Community": "Comunidad", + "Menu:Articles": "Artículos", + "Wait": "Esperar", + "Approve": "Aprobar", + "Reject": "Rechazar", + "Details": "Detalles", + "Url": "Url", + "Title": "Título", + "ContentSource": "Fuente de contenido", + "Status": "Estado", + "ReadArticle": "Leer artículo", + "ArticleHasBeenWaiting": "El artículo ha sido puesto en espera", + "ArticleHasBeenApproved": "El artículo ha sido aprobado", + "ArticleHasBeenRejected": "El artículo ha sido rechazado", + "Permission:Community": "Comunidad", + "Permission:CommunityArticle": "Artículo", + "Link": "Link", + "Enum:ContentSource:0": "Github", + "Enum:ContentSource:1": "Externo", + "Enum:Status:0": "En espera", + "Enum:Status:1": "Rechazado", + "Enum:Status:2": "Aprobado", + "Summary": "Resumen", + "AuthorName": "Nombre del autor", + "CoverImage": "Imagen de portada", + "RemoveCacheConfirmationMessage": "¿Estás seguro que quieres borrar la caché para \"{0}\" artículo?", + "SuccessfullyRemoved": "Borrada correctamente", + "RemoveCache": "" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/zh-Hans.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/zh-Hans.json index bc78a54119..f5cbeb0213 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/zh-Hans.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/zh-Hans.json @@ -3,6 +3,12 @@ "texts": { "Permission:Organizations": "组织", "Permission:Manage": "管理组织", + "Permission:DiscountRequests": "折扣请求", + "Permission:DiscountManage": "管理折扣请求", + "Permission:Disable": "禁用", + "Permission:Enable": "启动", + "Permission:EnableSendEmail": "启用发送邮件", + "Permission:SendEmail": "发送邮件", "Permission:NpmPackages": "NPM包", "Permission:NugetPackages": "Nuget包", "Permission:Maintenance": "维护", @@ -13,8 +19,13 @@ "Permission:Edit": "编辑", "Permission:Delete": "删除", "Permission:Create": "创建", + "Permission:Accounting": "账单", + "Permission:Accounting:Quotation": "报价", + "Permission:Accounting:Invoice": "发票", "Menu:Organizations": "组织", + "Menu:Accounting": "账单", "Menu:Packages": "包", + "Menu:DiscountRequests": "折扣请求", "NpmPackageDeletionWarningMessage": "该NPM包将会被删除. 你确定吗?", "NugetPackageDeletionWarningMessage": "该Nuget包将会被删除. 你确定吗?", "ModuleDeletionWarningMessage": "该模块将会被删除. 你确定吗?", @@ -24,6 +35,7 @@ "NameFilter": "名称", "CreationTime": "创建时间", "IsPro": "是否为专业版", + "ShowOnModuleList": "展示模块列表", "EfCoreConfigureMethodName": "配置方法法", "IsProFilter": "是否为专业版", "ApplicationType": "应用程序类型", @@ -53,6 +65,7 @@ "CreateANugetPackage": "创建Nuget包", "AddNew": "新建", "PackageAlreadyExist{0}": "\"{0}\"已经被添加.", + "ModuleAlreadyExist{0}": "\"{0}\" 模块已经添加.", "ClearCache": "清除缓存", "SuccessfullyCleared": "清除成功", "Menu:NpmPackages": "NPM包", @@ -63,6 +76,7 @@ "Organizations": "组织", "LongName": "完整名称", "LicenseType": "授权类型", + "MissingLicenseTypeField": "许可证类型字段是必需的!", "LicenseStartTime": "授权开始时间", "LicenseEndTime": "授权结束时间", "AllowedDeveloperCount": "允许的开发人员数量", @@ -74,14 +88,112 @@ "AddDeveloper": "添加开发者", "Create": "创建", "UserNotFound": "用户不存在", - "{0}WillBeRemovedFromMembers": "{0} 将从成员中删除", + "{0}WillBeRemovedFromDevelopers": "{0} 将从开发者中移除, 你确定吗?", + "{0}WillBeRemovedFromOwners": "{0} 将从所有者中移除, 你确定吗?", "Computers": "计算机", "UniqueComputerId": "计算机唯一ID", "LastSeenDate": "上次查看日期", "{0}Computer{1}WillBeRemovedFromRecords": "计算机 {0} ({1}) 将从记录中删除", "OrganizationDeletionWarningMessage": "组织将被删除", + "DeletingLastOwnerWarningMessage": "一个组织必须至少有一个所有者!因此你不能删除此所有者", "This{0}AlreadyExistInThisOrganization": "该组织中已经存在此 {0}", "AreYouSureYouWantToDeleteAllComputers": "您确定要删除所有计算机吗?", - "DeleteAll": "删除所有" + "DeleteAll": "删除所有", + "DoYouWantToCreateNewUser": "你想要创建一个新用户吗", + "MasterModules": "主模块", + "OrganizationName": "组织名称", + "CreationDate": "创建时间", + "LicenseStartDate": "许可开始时间", + "LicenseEndDate": "许可结束时间", + "OrganizationNamePlaceholder": "组织名称...", + "TotalQuestionCountPlaceholder": "问题总数...", + "RemainingQuestionCountPlaceholder": "剩下的问题数...", + "LicenseTypePlaceholder": "许可类型...", + "CreationDatePlaceholder": "创建时间...", + "LicenseStartDatePlaceholder": "许可开始时间...", + "LicenseEndDatePlaceholder": "许可结束时间...", + "UsernameOrEmail": "用户名或邮箱", + "UsernameOrEmailPlaceholder": "用户名或邮箱...", + "Member": "成员", + "PurchaseOrderNo": "订单编号", + "QuotationDate": "报价日期", + "CompanyName": "公司名称", + "CompanyAddress": "公司地址", + "Price": "价格", + "DiscountText": "折扣文字", + "DiscountQuantity": "折扣数量", + "DiscountPrice": "折扣价格", + "Quotation": "报价单", + "ExtraText": "额外文字", + "ExtraAmount": "额外金额", + "DownloadQuotation": "下载报价单", + "Invoice": "发票", + "TaxNumber": "税号", + "InvoiceNumber": "发票数字", + "InvoiceDate": "发票日期", + "InvoiceNote": "发票说明", + "Quantity": "数量", + "AddProduct": "添加产品", + "AddProductWarning": "你需要添加产品", + "TotalPrice": "总价", + "Generate": "生成", + "MissingQuantityField": "数量字段为必填项!", + "MissingPriceField": "价格字段为必填项!", + "CodeUsageStatus": "状态", + "Country": "国家", + "DeveloperCount": "开发者数量", + "RequestCode": "请求码", + "WebSite": "网站", + "GithubUsername": "Github用户名", + "PhoneNumber": "手机号", + "ProjectDescription": "产品描述", + "Referrer": "推荐人", + "DiscountRequests": "折扣请求", + "Copylink": "拷贝链接", + "Disable": "禁用", + "Enable": "启用", + "EnableSendEmail": "启用发送邮件", + "SendEmail": "发送邮件", + "SuccessfullyDisabled": "禁用成功", + "SuccessfullyEnabled": "启用成功", + "EmailSent": "邮件发送", + "SuccessfullySent": "发送成功", + "SuccessfullyDeleted": "删除成功", + "DiscountRequestDeletionWarningMessage": "折扣成功将被删除", + "BusinessType": "商业类型", + "TotalQuestionCount": "问题总数", + "RemainingQuestionCount": "剩余问题数", + "TotalQuestionMustBeGreaterWarningMessage": "TotalQuestionCount必须大于RemainingQuestionCount!", + "QuestionCountsMustBeGreaterThanZero": "TotalQuestionCount和RemainingQuestionCount必须为0或大于0", + "UnlimitedQuestionCount": "无限的问题计数", + "Notes": "笔记", + "Menu:Community": "社区", + "Menu:Articles": "文章", + "Wait": "等待", + "Approve": "批准", + "Reject": "拒绝", + "Details": "详情", + "Url": "Url", + "Title": "标题", + "ContentSource": "内容源", + "Status": "状态", + "ReadArticle": "阅读文章", + "ArticleHasBeenWaiting": "文章还在等待", + "ArticleHasBeenApproved": "文章已被批准", + "ArticleHasBeenRejected": "文章已被拒绝", + "Permission:Community": "社区", + "Permission:CommunityArticle": "文字", + "Link": "链接", + "Enum:ContentSource:0": "Github", + "Enum:ContentSource:1": "外部", + "Enum:Status:0": "等待中", + "Enum:Status:1": "已拒绝", + "Enum:Status:2": "已批准", + "Summary": "概要", + "AuthorName": "作者名称", + "CoverImage": "封面图片", + "RemoveCacheConfirmationMessage": "你确定要删除\"{0}\" 文章缓存?", + "SuccessfullyRemoved": "清除成功", + "RemoveCache": "删除缓存" } } \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/de-DE.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/de-DE.json new file mode 100644 index 0000000000..77e1b2090a --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/de-DE.json @@ -0,0 +1,33 @@ +{ + "culture": "de-DE", + "texts": { + "Volo.AbpIo.Domain:010004": "Maximale Mitgliederanzahl erreicht!", + "Volo.AbpIo.Domain:010005": "Miximale Besizeranzahl erreicht!", + "Volo.AbpIo.Domain:010006": "Dieser Benutzer ist bereits ein Besitzer in dieser Organisation!", + "Volo.AbpIo.Domain:010007": "Dieser Benutzer ist bereits ein Entwickler in dieser Organisation!", + "Volo.AbpIo.Domain:010008": "Die zulässige Entwickleranzahl darf nicht geringer sein als die aktuelle Entwickleranzahl!", + "Volo.AbpIo.Domain:010009": "Die zulässige Entwickleranzahl darf nicht kleiner als 0 sein!", + "Volo.AbpIo.Domain:010010": "Die maximale Anzahl der Mac-Adressen ist überschritten!", + "Volo.AbpIo.Domain:010011": "Die persönliche Lizenz kann nicht mehr als 1 Entwickler haben!", + "Volo.AbpIo.Domain:010012": "Die Lizenz kann nicht einen Monat nach Ablauf der Lizenz verlängert werden!", + "Volo.AbpIo.Domain:020001": "Dieses NPM-Paket konnte nicht gelöscht werden, da \"{NugetPackages}\" Nuget-Pakete von diesem Paket abhängig sind.", + "Volo.AbpIo.Domain:020002": "Dieses NPM-Paket konnte nicht gelöscht werden, da \"{Module}\" Module dieses Paket verwenden.", + "Volo.AbpIo.Domain:020003": "Dieses NPM-Paket konnte nicht gelöscht werden, da \"{Module}\" Module dieses Paket verwenden und \"{NugetPackages}\" Nuget-Pakete von diesem Paket abhängig sind.", + "Volo.AbpIo.Domain:020004": "Dieses Nuget-Paket konnte nicht gelöscht werden, da \"{Module}\" Module dieses Paket verwenden.", + "WantToLearn?": "Wollen Sie sich einlernen?", + "ReadyToGetStarted?": "Bereit anzufangen?", + "JoinOurCommunity": "Tritt unserer Community bei", + "GetStartedUpper": "LOSLEGEN", + "ForkMeOnGitHub": "Fork me on GitHub", + "Features": "Features", + "GetStarted": "Loslegen", + "Documents": "Unterlagen", + "Community": "Community", + "ContributionGuide": "Leitfaden für Mitwirkende", + "Blog": "Blog", + "Commercial": "Commercial", + "MyAccount": "Mein Benutzerkonto", + "SeeDocuments": "Siehe Unterlagen", + "Samples": "Beispiele" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/en.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/en.json index d6f334f7cd..71dc425dc6 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/en.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/en.json @@ -27,6 +27,9 @@ "Blog": "Blog", "Commercial": "Commercial", "MyAccount": "My account", - "SeeDocuments": "See Documents" + "Permission:License": "License", + "Permission:UserInfo": "Usere info", + "SeeDocuments": "See Documents", + "Samples": "Samples" } } \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/es.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/es.json new file mode 100644 index 0000000000..9974232511 --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/es.json @@ -0,0 +1,33 @@ +{ + "culture": "es", + "texts": { + "Volo.AbpIo.Domain:010004": "Número máximo de miembros alcanzado!", + "Volo.AbpIo.Domain:010005": "Número máximo de propietarios alcanzado!", + "Volo.AbpIo.Domain:010006": "Este usuario ya es un propietario de esta organización!", + "Volo.AbpIo.Domain:010007": "Este usuario ya es un desarrollador en este organización!", + "Volo.AbpIo.Domain:010008": "Número de desarrolladores permitido no puede ser menor que el número actual de desarrolladores!", + "Volo.AbpIo.Domain:010009": "El número de desarrolladores no puede ser menor que cero!", + "Volo.AbpIo.Domain:010010": "Número máximo de dirección mac excedido!", + "Volo.AbpIo.Domain:010011": "Una licencia personal no puede tener más de un desarrollador!", + "Volo.AbpIo.Domain:010012": "La licencia no puede ser extendida un mes despues de que expire!", + "Volo.AbpIo.Domain:020001": "Este paquete NPM no pudo ser borrado porque \"{NugetPackages}\" paquetes Nuget son dependientes de este paquete.", + "Volo.AbpIo.Domain:020002": "Este paquete NPM no pudo ser borrado porque \"{Modules}\" modulos están usando este paquete.", + "Volo.AbpIo.Domain:020003": "Este paquete NPM no pudo ser borrado porque \"{Modules}\" modulos están usando este paquete.y \"{NugetPackages}\" paquetes Nuget son dependientes de este paquete.", + "Volo.AbpIo.Domain:020004": "Este paquete Nuget no pudo ser borrado porque \"{Modules}\" modulos están usando este paquete.", + "WantToLearn?": "¿Quieres aprender?", + "ReadyToGetStarted?": "¿Preparado para comenzar?", + "JoinOurCommunity": "Unete a nuestra comunidad", + "GetStartedUpper": "COMENZAR", + "ForkMeOnGitHub": "Fork en GitHub", + "Features": "Características", + "GetStarted": "Comenzar", + "Documents": "Documentos", + "Community": "Comunidad", + "ContributionGuide": "Guia de contribución", + "Blog": "Blog", + "Commercial": "Comercial", + "MyAccount": "Mi cuenta", + "SeeDocuments": "Ver documentos", + "Samples": "Ejemplos" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/zh-Hans.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/zh-Hans.json index 986d1fdc2c..79493b537e 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/zh-Hans.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Base/Localization/Resources/zh-Hans.json @@ -26,6 +26,8 @@ "ContributionGuide": "贡献指南", "Blog": "博客", "Commercial": "商业版", - "SeeDocuments": "查看文档" + "MyAccount": "我的账户", + "SeeDocuments": "查看文档", + "Samples": "示例" } } \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/de-DE.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/de-DE.json new file mode 100644 index 0000000000..ddc493e63b --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/de-DE.json @@ -0,0 +1,35 @@ +{ + "culture": "de-DE", + "texts": { + "OrganizationManagement": "Organisationsverwaltung", + "OrganizationList": "Organisationsauflistung", + "Volo.AbpIo.Commercial:010003": "Sie sind der Besitzer dieser Organisation!", + "OrganizationNotFoundMessage": "Keine Organisation gefunden!", + "DeveloperCount": "Zugeordnete / Gesamte Entwickler", + "QuestionCount": "Verbleibende / Gesamte Fragen", + "Unlimited": "Unbegrenzt", + "Owners": "Besitzer", + "AddMember": "Mitglied hinzufügen", + "AddOwner": "Besizer hinzufügen", + "AddDeveloper": "Entwickler hinzufügen", + "UserName": "Benutzername", + "Name": "Name", + "EmailAddress": "E-Mail-Adress", + "Developers": "Entwickler", + "LicenseType": "Lizenztyp", + "Manage": "Verwalten", + "StartDate": "Startdatum", + "EndDate": "Enddatum", + "Modules": "Module", + "LicenseExtendMessage": "Ihr Lizenzenddatum wird auf {0} verlängert", + "LicenseUpgradeMessage": "Ihre Lizenz wird auf {0} aktualisiert", + "LicenseAddDeveloperMessage": "{0} Entwickler zu Ihrer Lizenz hinzugefügt", + "Volo.AbpIo.Commercial:010004": "Kann den angegebenen Benutzer nicht finden! Der Benutzer muss sich bereits registriert haben.", + "MyOrganizations": "Meine Organisationen", + "ApiKey": "API-Schlüssel", + "UserNameNotFound": "Es gibt keinen Benutzer mit dem Benutzernamen {0}", + "SuccessfullyAddedToNewsletter": "Vielen Dank, dass Sie unseren Newsletter abonniert haben!", + "MyProfile": "Mein Profil", + "EmailNotValid": "Bitte geben Sie eine gültige E-Mail-Adresse ein." + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json index 2a57c6b25d..e029499b06 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json @@ -30,6 +30,8 @@ "UserNameNotFound": "There is no user with username {0}", "SuccessfullyAddedToNewsletter": "Thanks you for subscribing to our newsletter!", "MyProfile": "My profile", - "EmailNotValid": "Please enter a valid email address." + "EmailNotValid": "Please enter a valid email address.", + "JoinOurMarketingNewsletter": "Join our marketing newsletter", + "WouldLikeToReceiveMarketingMaterials": "I would like to receive marketing materials like product deals & special offers." } } \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/es.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/es.json new file mode 100644 index 0000000000..80647e85e9 --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/es.json @@ -0,0 +1,35 @@ +{ + "culture": "es", + "texts": { + "OrganizationManagement": "Gestión de la organización", + "OrganizationList": "Lista organización", + "Volo.AbpIo.Commercial:010003": "Tu no eres el propietario de esta organización!", + "OrganizationNotFoundMessage": "Organización no encontrada!", + "DeveloperCount": "Total desarrolladores asignados", + "QuestionCount": "Total de preguntas restantes", + "Unlimited": "Ilimitado", + "Owners": "Propietarios", + "AddMember": "Añadir miembro", + "AddOwner": "Añadir propietario", + "AddDeveloper": "Añadir desarrollador", + "UserName": "Nombre de usuario", + "Name": "Nombre", + "EmailAddress": "Dirección de Email", + "Developers": "Desarrolladores", + "LicenseType": "Tipo de licencia", + "Manage": "Gestionar", + "StartDate": "Fecha de inicio", + "EndDate": "Fecha de fin", + "Modules": "Módulos", + "LicenseExtendMessage": "Tu fecha de finalización de tu licencia ha sido extendido a {0}", + "LicenseUpgradeMessage": "Tu licencia esta actualizada a {0}", + "LicenseAddDeveloperMessage": "{0} desarrolladores añadidos a tu licencia", + "Volo.AbpIo.Commercial:010004": "No se pudo encontrar el usuario especificado. El usuario debe estar ya registrado.", + "MyOrganizations": "Mis organizaciones", + "ApiKey": "API Key", + "UserNameNotFound": "No hay un usuario con el nombre de usuario {0}", + "SuccessfullyAddedToNewsletter": "Gracias por suscribirte a nuestro boletín de noticias!", + "MyProfile": "Mi perfil", + "EmailNotValid": "Por favor, introduce una dirección de email válida." + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/zh-Hans.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/zh-Hans.json index e80457377f..0147e71a05 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/zh-Hans.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/zh-Hans.json @@ -6,6 +6,8 @@ "Volo.AbpIo.Commercial:010003": "你不是该组织的所有者!", "OrganizationNotFoundMessage": "找不到任何组织!", "DeveloperCount": "开发者数量", + "QuestionCount": "剩余 / 问题总数", + "Unlimited": "无限制", "Owners": "所有者", "AddMember": "添加成员", "AddOwner": "添加所有者", @@ -25,6 +27,9 @@ "Volo.AbpIo.Commercial:010004": "不能找到指定的用户! 用户必须已经注册.", "MyOrganizations": "我的组织", "ApiKey": "API key", - "UserNameNotFound": "没有用户名为{0}的用户" + "UserNameNotFound": "没有用户名为{0}的用户", + "SuccessfullyAddedToNewsletter": "感谢你订阅我们的新闻通讯!", + "MyProfile": "我的资料", + "EmailNotValid": "请输入有效的电子邮件地址" } } \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/de-DE.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/de-DE.json new file mode 100644 index 0000000000..0db3c9b29b --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/de-DE.json @@ -0,0 +1,90 @@ +{ + "culture": "de-DE", + "texts": { + "Permission:CommunityArticle": "Community-Beitrag", + "Permission:Edit": "Bearbeiten", + "Waiting": "Wartend", + "Approved": "Genehmigt", + "Rejected": "Abgelehnt", + "Wait": "Warten", + "Approve": "Genehmigen", + "Reject": "Ablehnen", + "ReadArticle": "Beitrag lesen", + "Status": "Status", + "ContentSource": "Inhaltsquelle", + "Details": "Details", + "Url": "URL", + "Title": "Titel", + "CreationTime": "Erstellungszeitpunkt", + "Save": "Speichern", + "SameUrlAlreadyExist": "Dieselbe URL existiert bereits, wenn Sie diesen Beitrag hinzufügen möchten, sollten Sie die URL ändern!", + "UrlIsNotValid": "Der URL ist nicht korrekt.", + "UrlNotFound": "URL nicht gefunden.", + "UrlContentNotFound": "URL-Inhalt nicht gefunden", + "Summary": "Zusammenfassung", + "MostRead": "Meist gelesen", + "Latest": "Neueste", + "ContributeAbpCommunity": "Tragen Sie zur ABP Community bei", + "SubmitYourArticle": "Reichen Sie Ihren Beitrag ein", + "ContributionGuide": "Leitfaden für Mitwirkende", + "BugReport": "Fehler melden", + "SeeAllArticles": "Alle Beiträge anzeigen", + "WelcomeToABPCommunity!": "Willkommen in der ABP Community!", + "MyProfile": "Mein Profil", + "MyOrganizations": "Meine Organisationen", + "EmailNotValid": "Bitte geben Sie eine gültige E-Mail-Adresse ein.", + "FeatureRequest": "Featureanfrage", + "CreateArticleTitleInfo": "Titel des Beitrags, der in der Beitragsliste angezeigt werden soll.", + "CreateArticleUrlInfo": "Original GitHub-/externe URL des Beitrags.", + "CreateArticleSummaryInfo": "Eine kurze Zusammenfassung des Beitrags, der in der Beitragsliste angezeigt werden soll.", + "CreateArticleCoverInfo": "Fügen Sie zum Erstellen eines effektiven Beitrags ein Titelbild hinzu. Laden Sie Bilder mit einem Seitenverhältnis von 16: 9 hoch, um die beste Ansicht zu erhalten.", + "ThisExtensionIsNotAllowed": "Diese Erweiterung ist nicht zulässig.", + "TheFileIsTooLarge": "Die Datei ist zu groß.", + "GoToTheArticle": "Gehe zum Beitrag", + "Contribute": "Beitragen", + "OverallProgress": "Gesamtfortschritt", + "Done": "Fertig", + "Open": "Offen", + "Closed": "Geschlossen", + "LatestQuestionOnThe": "Letzte Frage zum", + "Stackoverflow": "Stackoverflow", + "Votes": "Stimmen", + "Answer": "Antwort", + "Views": "Ansichten", + "Answered": "Beantwortet", + "WaitingForYourAnswer": "Warten auf Ihre Antwort", + "Asked": "gefragt", + "AllQuestions": "Alle Fragen", + "NextVersion": "Nächste Version", + "MilestoneErrorMessage": "Die aktuellen Meilensteindetails konnten von Github nicht abgerufen werden.", + "QuestionItemErrorMessage": "Die neuesten Fragendetails konnten von Stackoverflow nicht abgerufen werden.", + "Oops": "Hoppla!", + "CreateArticleSuccessMessage": "Der Beitrag wurde erfolgreich eingereicht. Er wird nach einer Überprüfung durch den Site-Administrator veröffentlicht.", + "ChooseCoverImage": "Ein Titelbild auswählen...", + "CoverImage": "Titelbild", + "ShareYourExperiencesWithTheABPFramework": "Ihre Erfahrungen mit dem ABP Framework teilen!", + "Optional": "Optional", + "UpdateUserWebSiteInfo": "Beispiel: https://johndoe.com", + "UpdateUserTwitterInfo": "Beispiel: johndoe", + "UpdateUserGithubInfo": "Beispiel: johndoe", + "UpdateUserLinkedinInfo": "Beispiel: https://www.linkedin.com/...", + "UpdateUserCompanyInfo": "Beispiel: Volosoft", + "UpdateUserJobTitleInfo": "Beispiel: Software Developer", + "UserName": "Benutzername", + "Company": "Firma", + "PersonalWebsite": "Persönliche Website", + "RegistrationDate": "Registrierungsdatum", + "Social": "Social", + "Biography": "Biographie", + "HasNoPublishedArticlesYet": "hat noch keine Beiträge veröffentlicht", + "Author": "Autor", + "LatestGithubAnnouncements": "Neueste Github-Ankündigungen", + "SeeAllAnnouncements": "Alle Ankündigungen anzeigen", + "LatestBlogPost": "Letzter Blog-Beitrag", + "Edit": "Bearbeiten", + "ProfileImageChange": "Ändern Sie das Profilbild", + "BlogItemErrorMessage": "Die neuesten Blogpost-Details konnten nicht abgerufen werden.", + "PlannedReleaseDate": "Geplantes Erscheinungsdatum", + "CommunityArticleRequestErrorMessage": "Die Anfrage nach den neuesten Beiträgen von Github konnte nicht abgerufen werden." + } +} diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/en.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/en.json index ea5237bc29..c570e6fb1e 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/en.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/en.json @@ -83,6 +83,22 @@ "LatestBlogPost": "Latest Blog Post", "Edit": "Edit", "ProfileImageChange": "Change the profile image", - "BlogItemErrorMessage": "Could not get the latest blog post details from ABP." + "BlogItemErrorMessage": "Could not get the latest blog post details from ABP.", + "PlannedReleaseDate": "Planned release date", + "CommunityArticleRequestErrorMessage": "Could not get the latest article request from Github.", + "ArticleRequestFromGithubIssue": "There are not any article requests now.", + "LatestArticles": "Latest Articles", + "ArticleRequests": "Article Requests", + "AllArticleRequests": "See All Article Requests", + "SubscribeToTheNewsletter": "Subscribe to the Newsletter", + "NewsletterEmailDefinition": "Get information about happenings in ABP like new releases, free sources, articles, and more.", + "NoThanks": "No, thanks", + "MaybeLater": "Maybe later", + "JoinOurArticleNewsletter": "Join our article newsletter", + "Community": "Community", + "Marketing": "Marketing", + "CommunityPrivacyPolicyConfirmation": "I agree to the Terms & Conditions and Privacy Policy.", + "ArticleRequestMessageTitle": "Open an issue on the GitHub to request an article/tutorial you want to see on this web site.", + "ArticleRequestMessageBody": "Here, the list of the requested articles by the community. Do you want to write a requested article? Please click to the request and join to the discussion." } } diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/es.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/es.json new file mode 100644 index 0000000000..433de31852 --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/es.json @@ -0,0 +1,90 @@ +{ + "culture": "es", + "texts": { + "Permission:CommunityArticle": "Artículo de comunidad", + "Permission:Edit": "Editar", + "Waiting": "Esperando", + "Approved": "Aprobado", + "Rejected": "Rechazado", + "Wait": "Esperar", + "Approve": "Aprobar", + "Reject": "Rechazar", + "ReadArticle": "Leer artículo", + "Status": "Estado", + "ContentSource": "Fuente de contenido", + "Details": "Detalles", + "Url": "Url", + "Title": "Título", + "CreationTime": "Fecha de creación", + "Save": "Guardar", + "SameUrlAlreadyExist": "La url ya existe si tu quieres añadir este artículo, tu debes cambiar la url!", + "UrlIsNotValid": "Url no es valida", + "UrlNotFound": "Url no encontrada", + "UrlContentNotFound": "Contenido de la Url no encontrado", + "Summary": "Resumen", + "MostRead": "Más leído", + "Latest": "Últimos", + "ContributeAbpCommunity": "Contribuye a la comunidad ABP", + "SubmitYourArticle": "Envía tu artículo", + "ContributionGuide": "Guía de contribución", + "BugReport": "Informe de errores", + "SeeAllArticles": "Ver todos los artículos", + "WelcomeToABPCommunity!": "Bienvenido a la comunidad ABP", + "MyProfile": "Mi perfil", + "MyOrganizations": "Mis organizaciones", + "EmailNotValid": "Por favor entra una dirección de email válida.", + "FeatureRequest": "Solucitud de característica", + "CreateArticleTitleInfo": "Título del artículo para ser mostrado en la lista de artículos.", + "CreateArticleUrlInfo": "Url original del artículo GitHub/ Externo", + "CreateArticleSummaryInfo": "Un pequeño resumen del artículo para ser mostrado en la lista de artículos.", + "CreateArticleCoverInfo": "Para crear un artículo eficaz, agregue una foto de portada. Cargue imágenes con una relación de aspecto de 16: 9 para obtener la mejor vista.", + "ThisExtensionIsNotAllowed": "Esta extensión no está permitida.", + "TheFileIsTooLarge": "El fichero es demasiado grande.", + "GoToTheArticle": "Ir a el artículo", + "Contribute": "Contribuir", + "OverallProgress": "Progreso general", + "Done": "Hecho", + "Open": "Abrir", + "Closed": "Cerrado", + "LatestQuestionOnThe": "Última pregunta en la", + "Stackoverflow": "Stackoverflow", + "Votes": "Votos", + "Answer": "Respuesta", + "Views": "Vistas", + "Answered": "Respondido", + "WaitingForYourAnswer": "Esperando tu respuesta", + "Asked": "Preguntado", + "AllQuestions": "Todas las preguntas", + "NextVersion": "Siguiente versión", + "MilestoneErrorMessage": "No se pudieron obtener los detalles del hito actual en Github.", + "QuestionItemErrorMessage": "no se pudieron obtener los detalles de pregunta actual en Stackoverflow.", + "Oops": "Oops!", + "CreateArticleSuccessMessage": "El artículo se ha enviado correctamente. Se publicará después de una revisión del administrador del sitio.", + "ChooseCoverImage": "Elige una imagen de portada...", + "CoverImage": "Imagen de portada", + "ShareYourExperiencesWithTheABPFramework": "Comparte tus experiencias con el ABP Framework!", + "Optional": "Opcional", + "UpdateUserWebSiteInfo": "Ejemplo: https://johndoe.com", + "UpdateUserTwitterInfo": "Ejemplo: johndoe", + "UpdateUserGithubInfo": "Ejemplo: johndoe", + "UpdateUserLinkedinInfo": "Ejemplo: https://www.linkedin.com/...", + "UpdateUserCompanyInfo": "Ejemplo: Volosoft", + "UpdateUserJobTitleInfo": "Ejemplo: desarrollador de software", + "UserName": "Nombre de usuario", + "Company": "Empresa", + "PersonalWebsite": "Sitio web personal", + "RegistrationDate": "Fecha de registro", + "Social": "Social", + "Biography": "Biografía", + "HasNoPublishedArticlesYet": "No has publicado articules todavía", + "Author": "Autor", + "LatestGithubAnnouncements": "Últimas notificaciones de Github", + "SeeAllAnnouncements": "Ver todos las notificaciones", + "LatestBlogPost": "", + "Edit": "Editar", + "ProfileImageChange": "Cambiar la imagen de perfil", + "BlogItemErrorMessage": "No se pudo obtener los detalles del último blog desde ABP.", + "PlannedReleaseDate": "Fecha de entrega planificada", + "CommunityArticleRequestErrorMessage": "No se pudo obtener la última petición de artículo desde Github" + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/zh-Hans.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/zh-Hans.json index 307ff066a7..fa793c91a0 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/zh-Hans.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/zh-Hans.json @@ -1,64 +1,89 @@ { - "culture": "zh-Hans", - "texts": { - "Permission:CommunityArticle": "社区文章", - "Permission:Edit": "修改", - "Waiting": "等待中", - "Approved": "已批准", - "Rejected": "已拒绝", - "Wait": "等待", - "Approve": "批准", - "Reject": "拒绝", - "ReadArticle": "阅读文章", - "Status": "状态", - "ContentSource": "内容来源", - "Details": "详情", - "Url": "url", - "Title": "标题", - "CreationTime": "创建时间", - "Save": "保存", - "SameUrlAlreadyExist": "url已存在,如果你想要添加这篇文章,你需要更改url!", - "UrlIsNotValid": "Url无效.", - "UrlNotFound" : "Url未找到.", - "UrlContentNotFound": "Url内容未找到.", - "Summary": "摘要", - "MostRead": "阅读最多", - "Latest": "最新", - "ContributeAbpCommunity": "为ABP社区做贡献", - "SubmitYourArticle": "提交你的文章", - "ContributionGuide": "贡献指南", - "BugReport": "Bug报告", - "SeeAllArticles": "查看所有的文章", - "WelcomeToABPCommunity!": "欢迎来到ABP社区!", - "MyProfile": "我的资料", - "MyOrganizations": "我的组织", - "EmailNotValid": "请输入有效的电子邮箱地址.", - "FeatureRequest": "功能请求", - "CreateArticleTitleInfo": "文章标题显示在文章列表中.", - "CreateArticleUrlInfo": "文章的原始GitHub/外部URL.", - "CreateArticleSummaryInfo": "文章的简短摘要将显示在文章列表中.", - "CreateArticleCoverInfo": "为了创建有效的文章,请添加封面图. 仅支持16:9的图片!", - "ThisExtensionIsNotAllowed": "不允许此扩展名.", - "TheFileIsTooLarge": "文件过大.", - "GoToTheArticle": "转到文章", - "Contribute": "贡献", - "OverallProgress": "总体流程", - "Done": "完成", - "Open": "打开", - "Closed": "关闭", - "LatestQuestionOnThe": "有关的最新问题", - "Stackoverflow": "Stackoverflow", - "Votes": "票数", - "Answer": "回答", - "Views": "观看次数", - "Answered": "已回答", - "WaitingForYourAnswer": "等待你的回答", - "Asked": "提问", - "AllQuestions": "所有的问题", - "NextVersion": "下一个版本", - "MilestoneErrorMessage": "无法从Github获取当前的里程碑详细信息.", - "QuestionItemErrorMessage": "无法从Stackoverflow获取最新的问题详细信息.", - "Oops": "哎呀!" - } + "culture": "zh-Hans", + "texts": { + "Permission:CommunityArticle": "社区文章", + "Permission:Edit": "修改", + "Waiting": "等待中", + "Approved": "已批准", + "Rejected": "已拒绝", + "Wait": "等待", + "Approve": "批准", + "Reject": "拒绝", + "ReadArticle": "阅读文章", + "Status": "状态", + "ContentSource": "内容来源", + "Details": "详情", + "Url": "url", + "Title": "标题", + "CreationTime": "创建时间", + "Save": "保存", + "SameUrlAlreadyExist": "url已存在,如果你想要添加这篇文章,你需要更改url!", + "UrlIsNotValid": "Url无效.", + "UrlNotFound": "Url未找到.", + "UrlContentNotFound": "Url内容未找到.", + "Summary": "摘要", + "MostRead": "阅读最多", + "Latest": "最新", + "ContributeAbpCommunity": "为ABP社区做贡献", + "SubmitYourArticle": "提交你的文章", + "ContributionGuide": "贡献指南", + "BugReport": "Bug报告", + "SeeAllArticles": "查看所有的文章", + "WelcomeToABPCommunity!": "欢迎来到ABP社区!", + "MyProfile": "我的资料", + "MyOrganizations": "我的组织", + "EmailNotValid": "请输入有效的电子邮箱地址.", + "FeatureRequest": "功能请求", + "CreateArticleTitleInfo": "文章标题显示在文章列表中.", + "CreateArticleUrlInfo": "文章的原始GitHub/外部URL.", + "CreateArticleSummaryInfo": "文章的简短摘要将显示在文章列表中.", + "CreateArticleCoverInfo": "为了创建有效的文章,请添加封面图. 仅支持16:9的图片!", + "ThisExtensionIsNotAllowed": "不允许此扩展名.", + "TheFileIsTooLarge": "文件过大.", + "GoToTheArticle": "转到文章", + "Contribute": "贡献", + "OverallProgress": "总体流程", + "Done": "完成", + "Open": "打开", + "Closed": "关闭", + "LatestQuestionOnThe": "有关的最新问题", + "Stackoverflow": "Stackoverflow", + "Votes": "票数", + "Answer": "回答", + "Views": "观看次数", + "Answered": "已回答", + "WaitingForYourAnswer": "等待你的回答", + "Asked": "提问", + "AllQuestions": "所有的问题", + "NextVersion": "下一个版本", + "MilestoneErrorMessage": "无法从Github获取当前的里程碑详细信息.", + "QuestionItemErrorMessage": "无法从Stackoverflow获取最新的问题详细信息.", + "Oops": "哎呀!", + "CreateArticleSuccessMessage": "文章提交成功. 网站管理员审核通过后将被发布.", + "ChooseCoverImage": "选项一张封面图片", + "CoverImage": "封面图片", + "ShareYourExperiencesWithTheABPFramework": "分享你的ABP Framework经验!", + "Optional": "可选的", + "UpdateUserWebSiteInfo": "示例: https://johndoe.com", + "UpdateUserTwitterInfo": "示例: johndoe", + "UpdateUserGithubInfo": "示例: johndoe", + "UpdateUserLinkedinInfo": "示例: https://www.linkedin.com/...", + "UpdateUserCompanyInfo": "示例v: Volosoft", + "UpdateUserJobTitleInfo": "示例: Software Developer", + "UserName": "用户名", + "Company": "公司", + "PersonalWebsite": "个人网站", + "RegistrationDate": "注册时间", + "Social": "社交", + "Biography": "传记", + "HasNoPublishedArticlesYet": "尚未发表文章", + "Author": "作者", + "LatestGithubAnnouncements": "最新的Github公告", + "SeeAllAnnouncements": "查看所有公告", + "LatestBlogPost": "最新博客文章", + "Edit": "修改", + "ProfileImageChange": "更改资料图片", + "BlogItemErrorMessage": "无法从ABP获取最新的博客文章详细信息.", + "PlannedReleaseDate": "计划发布日期" } - \ No newline at end of file +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/de-DE.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/de-DE.json new file mode 100644 index 0000000000..6f9f0726cf --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/de-DE.json @@ -0,0 +1,189 @@ +{ + "culture": "de-DE", + "texts": { + "GetStarted": "Erste Schritte - Startvorlagen", + "Create": "Erstellen", + "NewProject": "Neues Projekt", + "DirectDownload": "Direkter Download", + "ProjectName": "Proejktname", + "ProjectType": "Projekttyp", + "DatabaseProvider": "Datenbankanbieter", + "NTier": "N-Tier", + "IncludeUserInterface": "Benutzeroberfläche einschließen", + "CreateNow": "Jetzt erstellen", + "TheStartupProject": "Das Startprojekt", + "Tutorial": "Lernprogramm", + "UsingCLI": "mit CLI", + "SeeDetails": "Details ansehen", + "AbpShortDescription": "ABP Framework ist eine vollständige Infrastruktur zum Erstellen moderner Webanwendungen unter Befolgung von Best Practices und Konventionen für Softwareentwicklung.", + "SourceCodeUpper": "QUELLCODE", + "LatestReleaseLogs": "Akteulle Release", + "Infrastructure": "Infrastrutkur", + "Architecture": "Architektur", + "Modular": "Modular", + "DontRepeatYourself": "Don't Repeat Yourself", + "DeveloperFocused": "Entwickler-Zentriert", + "FullStackApplicationInfrastructure": "Full-Stack-Anwendungsinfrastruktur.", + "DomainDrivenDesign": "Domain Driven Design", + "DomainDrivenDesignExplanation": "Entworfen und entwickelt basierend auf DDD-Mustern und -Prinzipien. Bietet ein Schichtenmodell für Ihre Anwendung.", + "Authorization": "Authorization", + "AuthorizationExplanation": "Erweiterte Autorisierung mit Benutzer-, Rollen- und fein abgestimmtem Berechtigungssystem. Aufbauend auf der Microsoft Identity-Bibliothek.", + "MultiTenancy": "Multi-Tenancy", + "MultiTenancyExplanationShort": "SaaS-Anwendungen leicht gemacht! Integrierte Mandantenfähigkeit von der Datenbank bis zur Benutzeroberfläche.", + "CrossCuttingConcerns": "Cross Cutting Concerns", + "CrossCuttingConcernsExplanationShort": "Komplette Infrastruktur für Autorisierung, Validierung, Ausnahmebehandlung, Caching, Überwachungsprotokollierung, Transaktionsverwaltung und mehr.", + "BuiltInBundlingMinification": "Built-In Bundling & Minification", + "BuiltInBundlingMinificationExplanation": "Für die Bundling und Minification müssen keine externen Tools verwendet werden. ABP bietet eine einfachere, dynamische, leistungsstarke, modulare und integrierte Methode!", + "VirtualFileSystem": "Virtual File System", + "VirtualFileSystemExplanation": "Betten Sie Ansichten, Skripte, Stile, Bilder ... in Pakete/Bibliotheken ein und verwenden Sie sie in verschiedenen Anwendungen wieder.", + "Theming": "Theming", + "ThemingExplanationShort": "Verwenden und passen Sie das Bootstrap-basierte Standard-UI-Design an oder erstellen Sie Ihr eigenes.", + "BootstrapTagHelpersDynamicForms": "Bootstrap Tag Helpers & Dynamic Forms", + "BootstrapTagHelpersDynamicFormsExplanation": "Anstatt die sich wiederholenden Details von Bootstrap-Komponenten manuell zu schreiben, verwenden Sie die Tag-Helper von ABP, um diese zu vereinfachen und dabei die Vorteile von Intellisense zu nutzen. Erstellen Sie mit dem dynamischen Formular-Tag-Helfer schnell UI-Formulare basierend auf einem C#-Modell.", + "HTTPAPIsDynamicProxies": "HTTP APIs & Dynamic Proxies", + "HTTPAPIsDynamicProxiesExplanation": "Stellen Sie Anwendungsdienste automatisch als HTTP-APIs im REST-Stil bereit und verwenden Sie diese mit dynamischen JavaScript- und C#-Proxys.", + "CompleteArchitectureInfo": "Moderne Architektur zur Erstellung wartbarer Softwarelösungen.", + "DomainDrivenDesignBasedLayeringModelExplanation": "Hilft Ihnen bei der Implementierung einer DDD-basierten Schichtarchitektur und beim Aufbau einer wartbaren Codebasis.", + "DomainDrivenDesignBasedLayeringModelExplanationCont": "Bietet Startvorlagen, Abstraktionen, Basisklassen, Dienste, Dokumentation und Anleitungen, mit denen Sie Ihre Anwendung basierend auf DDD-Mustern und -Prinzipien entwickeln können.", + "MicroserviceCompatibleModelExplanation": "Das Kernframework und die vorgefertigten Module sind unter Berücksichtigung der Microservice-Architektur konzipiert.", + "MicroserviceCompatibleModelExplanationCont": "Bietet Infrastruktur, Integrationen, Beispiele und Dokumentation zur einfacheren Implementierung von Microservice-Lösungen, ohne zusätzliche Komplexität zu verursachen, wenn Sie eine monolithische Anwendung wünschen.", + "ModularInfo": "ABP bietet ein Modulsystem, mit dem Sie wiederverwendbare Anwendungsmodule entwickeln, Ereignisse im Anwendungslebenszyklus verknüpfen und Abhängigkeiten zwischen Kernteilen Ihres Systems ausdrücken können.", + "PreBuiltModulesThemes": "Vorgefertigte Module & Themes", + "PreBuiltModulesThemesExplanation": "Open Source- und kommerzielle Module und Themes stehen bereit, um in Ihrer Geschäftsanwendung verwendet zu werden.", + "NuGetNPMPackages": "NuGet- & NPM-Pakete", + "NuGetNPMPackagesExplanation": "Bereitgestellt als NuGet- & NPM-Pakete. Einfach zu installieren und zu aktualisieren.", + "ExtensibleReplaceable": "Erweiterbar/Austauschbar", + "ExtensibleReplaceableExplanation": "Alle Dienste und Module sind auf Erweiterbarkeit ausgelegt. Sie können Dienste, Seiten, Stile und Komponenten ersetzen.", + "CrossCuttingConcernsExplanation2": "Halten Sie Ihre Codebasis kleiner, damit Sie sich auf ihre geschäftsspezifischen Code konzentrieren können.", + "CrossCuttingConcernsExplanation3": "Verbringen Sie keine Zeit damit, grundlegende Anwendungsanforderungen für jedes neue Projekte zu implementieren.", + "AuthenticationAuthorization": "Authentifizierung & Autorisierung", + "ExceptionHandling": "Fehlerbehandlung", + "Validation": "Validierung", + "DatabaseConnection": "Datenbankverbindung", + "TransactionManagement": "Transaktionsmanagement", + "AuditLogging": "Audit Logging", + "Caching": "Caching", + "Multitenancy": "Multimandantenfähigkeit", + "DataFiltering": "Datenfilterung", + "ConventionOverConfiguration": "Convention Over Configuration", + "ConventionOverConfigurationExplanation": "ABP implementiert standardmäßig allgemeine Anwendungskonventionen mit einer minimalen oder Null-Konfiguration.", + "ConventionOverConfigurationExplanationList1": "Automatische Registrierung bekannter Services für Dependency Injection.", + "ConventionOverConfigurationExplanationList2": "Stellt Anwendungsdienste mittels Namenskonventionen als HTTP-APIs bereit.", + "ConventionOverConfigurationExplanationList3": "Erstellt dynamische HTTP-Client-Proxys für C# und JavaScript.", + "ConventionOverConfigurationExplanationList4": "Bietet Standard-Repositorys für Ihre Entities.", + "ConventionOverConfigurationExplanationList5": "Verwaltet die Unit-of-Work gemäß Webanforderung oder Anwendungsdienstmethode.", + "ConventionOverConfigurationExplanationList6": "Triggert Erstellungs-, Aktualisierungs- und Lösch-Events für Ihre Entities.", + "BaseClasses": "Basisklassen", + "BaseClassesExplanation": "Vorgefertigte Basisklassen für gängige Anwendungsmuster.", + "DeveloperFocusedExplanation": "ABP ist für Entwickler", + "DeveloperFocusedExplanationCont": "Es zielt darauf ab, Ihre tägliche Softwareentwicklung zu vereinfachen, ohne Sie daran zu hindern, Low-Level-Code zu schreiben.", + "SeeAllFeatures": "Alle Features anzeigen", + "CLI_CommandLineInterface": "CLI (Command Line Interface)", + "CLI_CommandLineInterfaceExplanation": "Enthält eine CLI, mit der Sie die Erstellung neuer Projekte und das Hinzufügen neuer Module automatisieren können.", + "StartupTemplates": "Startvorlagen", + "StartupTemplatesExplanation": "Verschiedene Startvorlagen bieten eine vollständig konfigurierte Lösung, um Ihre Entwicklung zu beschleunigen.", + "BasedOnFamiliarTools": "Basierend auf vertrauten Tools", + "BasedOnFamiliarToolsExplanation": "Aufbauend auf und integriert mit beliebten Tools, die Sie bereits kennen. Geringe Lernkurve, einfache Anpassung, komfortable Entwicklung.", + "ORMIndependent": "ORM-unabhängig", + "ORMIndependentExplanation": "Das Kernframework ist ORM-/datenbankunabhängig und kann mit jeder Datenquelle arbeiten. Entity Framework Core- und MongoDB-Anbieter sind bereits verfügbar.", + "Features": "Entdecken Sie die ABP Framework-Features", + "ABPCLI": "ABP CLI", + "Modularity": "Modularität", + "BootstrapTagHelpers": "Bootstrap Tag Helpers", + "DynamicForms": "Dynamische Formulare", + "BundlingMinification": "Bundling & Minification", + "BackgroundJobs": "Background Jobs", + "BackgroundJobsExplanation": "Definieren Sie einfache Klassen, um Jobs im Hintergrund in der Warteschlange auszuführen. Verwenden Sie den integrierten Jobmanager oder integrieren Sie Ihren eigenen. Hangfire & RabbitMQ -Integrationen sind bereits verfügbar.", + "DDDInfrastructure": "DDD-Infrastruktur", + "DomainDrivenDesignInfrastructure": "Domain Driven Design-Infrastruktur", + "AutoRESTAPIs": "Auto REST APIs", + "DynamicClientProxies": "Dynamische Client-Proxies", + "DistributedEventBus": "Distributed Event Bus", + "DistributedEventBusWithRabbitMQIntegration": "Distributed Event Bus mit RabbitMQ-Integration", + "TestInfrastructure": "Test-Infrastruktur", + "AuditLoggingEntityHistories": "Audit Logging & Entity Histories", + "ObjectToObjectMapping": "Object to Object Mapping", + "ObjectToObjectMappingExplanation": " Object to Object Mapping Abstraktion mit AutoMapper-Integration.", + "EmailSMSAbstractions": "E-Mail & SMS Abstraktionen", + "EmailSMSAbstractionsWithTemplatingSupport": "E-Mail- und SMS-Abstraktionen mit Vorlagenunterstützung", + "Localization": "Lokalisierung", + "SettingManagement": "Einstellungsverwaltung", + "ExtensionMethods": "Erweiterungsmethoden", + "ExtensionMethodsHelpers": "Erweiterungsmethoden & Helfer", + "AspectOrientedProgramming": "Aspektorientierte Programmierung", + "DependencyInjection": "Dependency Injection", + "DependencyInjectionByConventions": "Dependency Injection durch Konventionen", + "ABPCLIExplanation": "ABP CLI (Command Line Interface) ist ein Befehlszeilenprogramm zum Ausführen einiger gängiger Vorgänge für ABP-basierte Lösungen.", + "ModularityExplanation": "ABP bietet eine vollständige Infrastruktur zum Erstellen eigener Anwendungsmodule, die Entities, Services, Datenbankintegration, APIs, UI-Komponenten usw. enthalten können.", + "MultiTenancyExplanation": "Das ABP-Framework unterstützt nicht nur die Entwicklung von Multi-Mandantenanwendungen, sondern macht Ihren Code von der Mandantenfähigkeit auch weitgehend unabhängig.", + "MultiTenancyExplanation2": "Kann den aktuellen Mandanten automatisch ermitteln und Daten verschiedener Mandanten voneinander isolieren.", + "MultiTenancyExplanation3": "Unterstützt einzelne Datenbank-, Datenbank-pro-Mandanten- und Hybrid-Ansätze.", + "MultiTenancyExplanation4": "Sie konzentrieren sich auf Ihren geschäftsspezifischen Code und lassen das Framework die Mandantenfähigkeit für Sie übernehmen.", + "BootstrapTagHelpersExplanation": "Anstatt die sich wiederholenden Details von Bootstrap-Komponenten manuell zu schreiben, verwenden Sie die Tag-Helper von ABP, um diese zu vereinfachen und dabei die Vorteile von Intellisense zu nutzen. Sie können Bootstrap weitherhin verwenden, wann immer Sie es benötigen.", + "DynamicFormsExplanation": "Helfer für dynamische Formular- und Input-Tags können das vollständige Formular anhand einer C#-Klasse als Model erstellen.", + "AuthenticationAuthorizationExplanation": "Umfangreiche Authentifizierungs- und Autorisierungsoptionen, die in ASP.NET Core Identity & IdentityServer4 integriert sind. Bietet ein erweiterbares und detailliertes Berechtigungssystem.", + "CrossCuttingConcernsExplanation": "Wiederholen Sie sich nicht, um all diese allgemeinen Dinge immer wieder zu implementieren. Konzentrieren Sie sich auf Ihren geschäftsspezifischen Code und lassen Sie ihn von ABP durch Konventionen automatisieren.", + "DatabaseConnectionTransactionManagement": "Datenbankverbindungs- und Transaktionsmanagement", + "CorrelationIdTracking": "Correlation-ID-Verfolgung", + "BundlingMinificationExplanation": "ABP bietet ein einfaches, dynamisches, leistungsstarkes, modulares und integriertes Bundling- und Minification-System.", + "VirtualFileSystemnExplanation": "Das virtuelle Dateisystem ermöglicht die Verwaltung von Dateien, die physisch nicht auf dem Dateisystem (Datenträger) vorhanden sind. Es wird hauptsächlich verwendet, um Dateien (js, css, image, cshtml ...) in Assemblys einzubetten und sie zur Laufzeit wie physische Dateien zu verwenden.", + "ThemingExplanation": "Mit dem Theming-System können Sie Ihre Anwendung & Module Theme-unabhängig entwickeln, indem Sie eine Reihe gemeinsamer Basisbibliotheken und Layouts definieren, die auf dem neuesten Bootstrap-Framework basieren.", + "DomainDrivenDesignInfrastructureExplanation": "Eine vollständige Infrastruktur zum Erstellen von mehrschichtigen Anwendungen basierend auf den Domain Driven Design Entwurfsmustern und -prinzipien;", + "Specification": "Specification", + "Repository": "Repository", + "DomainService": "Domain Service", + "ValueObject": "Value Object", + "ApplicationService": "Application Service", + "DataTransferObject": "Data Transfer Object", + "AggregateRootEntity": "Aggregate Root, Entity", + "AutoRESTAPIsExplanation": "ABP kann Ihre Anwendungsservices gemäß Konvention automatisch als API-Controller konfigurieren.", + "DynamicClientProxiesExplanation": "Verwenden Sie Ihre APIs ganz einfach in JavaScript- und C#-Clients.", + "DistributedEventBusWithRabbitMQIntegrationExplanation": "Veröffentlichen und konsumieren Sie Distributed Events einfach mithilfe des integrierten Distributed Event Bus mit verfügbarer RabbitMQ-Integration.", + "TestInfrastructureExplanation": "Das Framework wurde unter Berücksichtigung von Unit- und Integrationstests entwickelt. Bietet Ihnen Basisklassen, um es einfacher zu machen. Startvorlagen werden mit vorkonfiguriert Tests geliefert.", + "AuditLoggingEntityHistoriesExplanation": "Integriertes Audit Logging für geschäftskritische Anwendungen. Audit Logging auf Request-, Service-, und Methodenebene sowie Entity-Historien mit Details auf Property-Ebene.", + "EmailSMSAbstractionsWithTemplatingSupportExplanation": "IEmailSender- und ISmsSender-Abstraktionen entkoppeln Ihre Anwendungslogik von der Infrastruktur. Das erweiterte E-Mail-Vorlagensystem ermöglicht das Erstellen und Lokalisieren von E-Mail-Vorlagen und deren einfache Verwendung bei Bedarf.", + "LocalizationExplanation": "Das Lokalisierungssystem ermöglicht das Erstellen von Ressourcen in einfachen JSON-Dateien und die Lokalisierung Ihrer Benutzeroberfläche. Es unterstützt erweiterte Szenarien wie Vererbung, Erweiterungen und JavaScript-Integration und ist vollständig mit dem Lokalisierungssystem von AspNet Core kompatibel.", + "SettingManagementExplanation": "Definieren Sie Einstellungen für Ihre Anwendung und erhalten Sie zur Laufzeit Werte basierend auf der aktuellen Konfiguration, dem Mandanten und dem Benutzer.", + "ExtensionMethodsHelpersExplanation": "Wiederholen Sie sich nicht einmal für triviale Codeteile. Erweiterungen und Helfer für Standardtypen machen Ihren Code viel sauberer und einfacher zu schreiben.", + "AspectOrientedProgrammingExplanation": "Bietet eine komfortable Infrastruktur zum Erstellen dynamischer Proxys und zum Implementieren der aspektorientierten Programmierung. Fangen Sie eine Klasse ab und führen Sie Ihren Code vor und nach jeder Methodenausführung aus.", + "DependencyInjectionByConventionsExplanation": "Sie müssen Ihre Klassen nicht manuell für die Dependency Injection registrieren. Registriert gängige Servicetypen automatisch gemäß Konvention. Für andere Arten von Services können Sie Schnittstellen und Attribute verwenden, um dies einfacher gestalten und an Ort und Stelle zu ermöglichen.", + "DataFilteringExplanation": "Definieren und verwenden Sie Datenfilter, die automatisch angewendet werden, wenn Sie Entities aus der Datenbank abfragen. Soft Delete- und Multimandanten-Filter sind sofort verfügbar, wenn Sie einfache Schnittstellen implementieren.", + "PublishEvents": "Events veröffentlichen", + "HandleEvents": "Auf Events reagieren", + "AndMore": "und mehr...", + "Code": "Code", + "Result": "Resultat", + "SeeTheDocumentForMoreInformation": "Weitere Informationen finden Sie in der {0} -Dokumentation ", + "IndexPageHeroSection": "Open SourceWebanwendung
Framework
für ASP.Net Core", + "UiFramework": "UI-Framework", + "EmailAddress": "E-Mail-Adresse", + "Mobile": "Mobile", + "ReactNative": "React Native", + "Strong": "Stark", + "Complete": "Vollständig", + "BasedLayeringModel": "Based Layering Model", + "Microservice": "Microservice", + "Compatible": "Kompatibel", + "MeeTTheABPCommunityInfo": "Unsere Mission ist es, eine Umgebung zu schaffen, in der Entwickler sich gegenseitig mit Beiträgen, Tutorials, Fallstudien usw. helfen und Gleichgesinnte treffen können.", + "JoinTheABPCommunityInfo": "Beteiligen Sie sich an einer lebendigen Community und tragen Sie zum ABP Framework bei!", + "AllArticles": "Alle Beiträge", + "SubmitYourArticle": "Reichen Sie Ihren Beitrag ein", + "DynamicClientProxyDocument": "In der Dokumentation zu den Dynamischen Client-Proxies finden Sie Informationen zu JavaScript & C#.", + "EmailSMSAbstractionsDocument": "Weitere Informationen finden Sie in den Unterlagen E-Mail-Senden and SMS-Senden.", + "CreateProjectWizard": "Dieser Assistent erstellt ein neues Projekt aus der Startvorlage, die ordnungsgemäß konfiguriert ist, um Ihr Projekt zu starten.", + "TieredOption": "Erstellt eine Tiered Lösung, bei der Web- und HTTP-API-Ebenen physisch getrennt sind. Wenn diese Option nicht aktiviert ist, wird eine mehrschichtige Lösung erstellt, die weniger komplex und für die meisten Szenarien geeignet ist.", + "SeparateIdentityServerOption": "Trennt die Serverseite in zwei Anwendungen: Die erste ist für den Identitätsserver und die zweite für die serverseitige HTTP-API.", + "UseslatestPreVersion": "Verwendet die neueste Vorabversion", + "ReadTheDocumentation": "Lesen SieDie Dokumentation", + "Documentation": "Dokumentation", + "GettingStartedTutorial": "Erste Schritte Tutorial", + "ApplicationDevelopmentTutorial": "Tutorial zur Anwendungsentwicklung", + "TheStartupTemplate": "Die Startvorlage", + "InstallABPCLIInfo": "ABP CLI ist der schnellste Weg, um eine neue Lösung mit dem ABP-Framework zu starten. Installieren Sie die ABP-CLI über die Eingabeaufforderung:", + "DifferentLevelOfNamespaces": "Sie können verschiedene Ebenen von Namespaces verwenden; z.B. BookStore, Acme.BookStore or Acme.Retail.BookStore.", + "ABPCLIExamplesInfo": "Der Befehl new erstellt eine mehrschichtige MVC-Anwendung mit Entity Framework Core als Datenbankanbieter. Es gibt jedoch zusätzliche Optionen. Beispiele:", + "SeeCliDocumentForMoreInformation": "Weitere Optionen finden Sie im ABP CLI-Dokument oder wählen Sie oben die Registerkarte \"Direkter Download\".", + "Optional": "Optional", + "LocalFrameworkRef": "Behalten Sie die lokale Projektreferenz für die Framework-Pakete bei." + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en.json index fa7b216bd0..e1dd405851 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en.json @@ -45,7 +45,7 @@ "CompleteArchitectureInfo": "Modern architecture to create maintainable software solutions.", "DomainDrivenDesignBasedLayeringModelExplanation": "Helps you to implement a DDD based layered architecture and build a maintainable code base.", "DomainDrivenDesignBasedLayeringModelExplanationCont": "Provides startup templates, abstractions, base classes, services, documentation and guides to help you to develop your application based on DDD patterns & principles.", - "MicroserviceCompatibleModelExplanation": "The core framework & pre-build modules are designed the microservice architecture in mind.", + "MicroserviceCompatibleModelExplanation": "The core framework & pre-build modules are designed with microservice architecture in mind.", "MicroserviceCompatibleModelExplanationCont": "Provides infrastructure, integrations, samples and documentation to implement microservice solutions easier, while it doesn\u2019t bring additional complexity if you want a monolithic application.", "ModularInfo": "ABP provides a module system that allows you to develop reusable application modules, tie into application lifecycle events, and express dependencies between core parts of your system.", "PreBuiltModulesThemes": "Pre-Built Modules & Themes", @@ -93,6 +93,7 @@ "DynamicForms": "Dynamic Forms", "BundlingMinification": "Bundling & Minification", "BackgroundJobs": "Background Jobs", + "BackgroundJobsExplanation": "Define simple classes to execute jobs in background as queued. Use built-in job manager or integrate your own. Hangfire & RabbitMQ integrations are already available.", "DDDInfrastructure": "DDD Infrastructure", "DomainDrivenDesignInfrastructure": "Domain Driven Design Infrastructure", "AutoRESTAPIs": "Auto REST APIs", @@ -102,6 +103,7 @@ "TestInfrastructure": "Test Infrastructure", "AuditLoggingEntityHistories": "Audit Logging & Entity Histories", "ObjectToObjectMapping": "Object to Object Mapping", + "ObjectToObjectMappingExplanation": "Object to object mapping abstraction with AutoMapper integration.", "EmailSMSAbstractions": "Email & SMS Abstractions", "EmailSMSAbstractionsWithTemplatingSupport": "Email & SMS Abstractions with Templating Support", "Localization": "Localization", @@ -156,6 +158,40 @@ "UiFramework": "UI Framework", "EmailAddress": "Email address", "Mobile": "Mobile", - "ReactNative": "React Native" + "ReactNative": "React Native", + "Strong": "Strong", + "Complete": "Complete", + "BasedLayeringModel": "Based Layering Model", + "Microservice": "Microservice", + "Compatible": "Compatible", + "MeeTTheABPCommunityInfo": "Our mission is to create an environment where developers can help each other with articles, tutorials, case studies, etc. and meet like-minded people.", + "JoinTheABPCommunityInfo": "Get involved with a vibrant community and become a contributor to the ABP Framework!", + "AllArticles": "All Articles", + "SubmitYourArticle": "Submit Your Article", + "DynamicClientProxyDocument": "See the dynamic client proxy documentations for JavaScript & C#.", + "EmailSMSAbstractionsDocument": "See the emailing and SMS sending documents for more information.", + "CreateProjectWizard": "This wizard creates a new project from the startup template which is properly configured to jump start to your project.", + "TieredOption": "Creates a tiered solution where Web and Http API layers are physically separated. If not checked, creates a layered solution which is less complex and suitable for most scenarios.", + "SeparateIdentityServerOption": "Separates server side into two applications: First one is for the identity server and the second one is for your server side HTTP API.", + "UseslatestPreVersion": "Uses latest pre-release version", + "ReadTheDocumentation": "ReadThe Documentation", + "Documentation": "Documentation", + "GettingStartedTutorial": "Getting Started Tutorial", + "ApplicationDevelopmentTutorial": "Application Development Tutorial", + "TheStartupTemplate": "The Startup Template", + "InstallABPCLIInfo": "ABP CLI is the fastest way to start a new solution with the ABP framework. Install the ABP CLI using a command line window:", + "DifferentLevelOfNamespaces": "You can use different level of namespaces; e.g. BookStore, Acme.BookStore or Acme.Retail.BookStore.", + "ABPCLIExamplesInfo": "new command creates a layered MVC application with Entity Framework Core as the database provider. However, it has additional options. Examples:", + "SeeCliDocumentForMoreInformation": "See the ABP CLI document for more options or select the \"Direct Download\" tab above.", + "Optional": "Optional", + "LocalFrameworkRef": "Keep local project reference for the framework packages.", + "BlobStoring": "BLOB Storing", + "BlobStoringExplanation": "BLOB Storing system provides an abstraction to work with BLOBs. ABP provides some pre-built storage provider integrations (Azure, AWS, File System, Database, etc.) that you can easily use in your applications.", + "TextTemplating": "Text Templating", + "TextTemplatingExplanation": "Text templating is used to dynamically render contents based on a template and a model (a data object). For example, you can use it to create dynamic email contents with a pre-built template.", + "MultipleUIOptions": "Multiple UI Options", + "MultipleDBOptions": "Multiple Database Providers", + "MultipleUIOptionsExplanation": "The core framework is designed as UI independent and can work with any type of UI system, while there are multiple pre-built and integrated options are provided out of the box.", + "MultipleDBOptionsExplanation": "The framework can work with any data source, while the following providers are officially developed and supported;" } } diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/es.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/es.json new file mode 100644 index 0000000000..3c36634f56 --- /dev/null +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/es.json @@ -0,0 +1,189 @@ +{ + "culture": "es", + "texts": { + "GetStarted": "Comencemos - Plantillas de inicio", + "Create": "Crear", + "NewProject": "Nuevo proyecto", + "DirectDownload": "Descarga directa", + "ProjectName": "Nombre de proyecto", + "ProjectType": "Tipo de proyecto", + "DatabaseProvider": "Proveedor de base de datos", + "NTier": "N-Capas", + "IncludeUserInterface": "Incluir interface de usuario", + "CreateNow": "Crear ahora", + "TheStartupProject": "El proyecto de inicio", + "Tutorial": "Tutorial", + "UsingCLI": "Usando CLI", + "SeeDetails": "Ver detalles", + "AbpShortDescription": "ABP Framework es una completa infraestructure para crear modernas aplicaciones web que sigue las mejores prácticas y convenciones de desarrollo de software.", + "SourceCodeUpper": "CÓDIGO FUENTE", + "LatestReleaseLogs": "Últimos registros de lanzamiento", + "Infrastructure": "infraestructura", + "Architecture": "Arquitectura", + "Modular": "Modular", + "DontRepeatYourself": "No te repitas tu mismo", + "DeveloperFocused": "Pensado para el desarrollador", + "FullStackApplicationInfrastructure": "infraestructura de aplicación Full stack", + "DomainDrivenDesign": "", + "DomainDrivenDesignExplanation": "Diseñado y desarrollado basandose en los patrones y principios de DDD. Promorciona una capa de modelo para tus aplicaciones.", + "Authorization": "Autorización", + "AuthorizationExplanation": "Sistema de autorización avanzado con usuarios, roles y permisos de granularidad-fina. Construido sobre la librería Microsoft Identity.", + "MultiTenancy": "Multi-inquilino", + "MultiTenancyExplanationShort": "Aplicaciones SaaS sencillas!, integradas con multi-inquilino desde la base de datos hasta la UI.", + "CrossCuttingConcerns": "Requerimientos comunes", + "CrossCuttingConcernsExplanationShort": "Completa infraestructura de autorización, validación, manejo de excepciones, caching, auditoría, gestión de transacciones y más.", + "BuiltInBundlingMinification": "Empaquetado y minificado integrado", + "BuiltInBundlingMinificationExplanation": "No se necesitan usar herramientas externas para el empaquetado y minificado. ABP ofrece un camino simple, dinámico, potente, modular e integrado.", + "VirtualFileSystem": "Sistema de ficheros virtual", + "VirtualFileSystemExplanation": "Incrusta vistas, scripts, estilos, imágenes en paquetes/ librerias y reusalos en diferentes aplicaciones.", + "Theming": "Temas", + "ThemingExplanationShort": "Usa y personaliza la UI estandar basada en bootstrap o crea tu propio tema.", + "BootstrapTagHelpersDynamicForms": "Boostrap Tag Helpers y formularios dinámicos", + "BootstrapTagHelpersDynamicFormsExplanation": "", + "HTTPAPIsDynamicProxies": "HTTP APIs y proxies dinámicos", + "HTTPAPIsDynamicProxiesExplanation": "Expon servicios de aplicación como REST HTPP APIs y consumelos dinámicamente desde proxies JavaScript y C#.", + "CompleteArchitectureInfo": "Arquitectura moderna para crear soluciones software sostenibles.", + "DomainDrivenDesignBasedLayeringModelExplanation": "Ayuda a implementar ", + "DomainDrivenDesignBasedLayeringModelExplanationCont": "Promorciona plantillas de inicio, clases base, servicios, documentación y guías de ayuda para desarrollar tu aplicación basada en patrones y principios DDD.", + "MicroserviceCompatibleModelExplanation": "El núcleo del framework y los modules pre-construidos están diseñados con una arquitectura microservicios en mente.", + "MicroserviceCompatibleModelExplanationCont": "Proporciona la infraestructura, integraciones, ejemplos y documentación para implementar soluciones microservicios más facilmente, mientras no trae complejidad adicional si quieres una aplicación monolítica.", + "ModularInfo": "ABP proporciona un sistema de modulos que te permite desarrollar modulos de aplicacion resusables. Conectado en el ciclo de eventos de aplicación y mínimas dependencias entre las partes principales de tu sistema.", + "PreBuiltModulesThemes": "Modulos y temas integrados", + "PreBuiltModulesThemesExplanation": "Módulos y temas de código abierto y comerciales preparados para usar en tu aplicación de negocio.", + "NuGetNPMPackages": "Paquetes Nuget y NPM", + "NuGetNPMPackagesExplanation": "Paquetes distribuidos a través de Nuget y NPM para instalar y actualizar.", + "ExtensibleReplaceable": "Extensible/ Reemplazable", + "ExtensibleReplaceableExplanation": "Todos los serivios y módulos están diseñados para ser extensibles. Tu puedes reemplazar servicios, páginas, estilos y componentes.", + "CrossCuttingConcernsExplanation2": "Mantiene tu código base más pequeño y te permite enforcate en el código que es especifico en tu negocio.", + "CrossCuttingConcernsExplanation3": "No pierdas tiempo implementando requerimientos comunes de aplicación en múltiples proyectos.", + "AuthenticationAuthorization": "Autenticación y autorización", + "ExceptionHandling": "Manejo de excepciones.", + "Validation": "Validación", + "DatabaseConnection": "Conexión a la base de datos", + "TransactionManagement": "Gestión de transacciones", + "AuditLogging": "Registro de auditoría", + "Caching": "Caché", + "Multitenancy": "Multi-inquilino", + "DataFiltering": "Filtrado de datos", + "ConventionOverConfiguration": "Convención sobre la configuración", + "ConventionOverConfigurationExplanation": "ABP implementa comunes convenciones de aplicación por defecto con una mínima o nula configuración.", + "ConventionOverConfigurationExplanationList1": "Los registradores conocen los servicios para la inyección de dependencias.", + "ConventionOverConfigurationExplanationList2": "Expone servicios de aplicación como APIs HTTP mediante convenciones de nomenclatura.", + "ConventionOverConfigurationExplanationList3": "Crea clientes proxies HTTP dinámicos para C# y JavaScript.", + "ConventionOverConfigurationExplanationList4": "Proporciona repositorios por defecto para tus entidades.", + "ConventionOverConfigurationExplanationList5": "Maneja Unit of Work por cada petición web o metodo de servicio de aplicación.", + "ConventionOverConfigurationExplanationList6": "Publica, crea, actualiza y borra eventos para tus entidades.", + "BaseClasses": "Clase base", + "BaseClassesExplanation": "Clases base integradas para patrones comunes de aplicación.", + "DeveloperFocusedExplanation": "ABP es para desarrolladores.", + "DeveloperFocusedExplanationCont": "Su objetivo es simplificar su desarrollo diario de software sin restringirle la escritura de código de bajo nivel.", + "SeeAllFeatures": "Ver todas las características", + "CLI_CommandLineInterface": "CLI (Command Line Interface)", + "CLI_CommandLineInterfaceExplanation": "Incluye un CLI que te ayuda a automatizar la creación de nuevos proyectos y añadir nuevos módulos.", + "StartupTemplates": "Plantillas de inicio", + "StartupTemplatesExplanation": "Varias plantillas de inicio proporcionan una solución completamente configurada lista para comenzar el desarrollo.", + "BasedOnFamiliarTools": "Basado en herramientas familiares", + "BasedOnFamiliarToolsExplanation": "Construido y diseñado con herramientas populares que tu ya conoces. Baja curva de aprendizaje, facil adaptación y desarrollo confortable.", + "ORMIndependent": "Independiente del ORM", + "ORMIndependentExplanation": "El núcleo del core es independiente del ORM/ base de datos y puedes trabajar con cualquier fuente de datos. Entity Framework Core y MongoDB están actualmente disponibles.", + "Features": "Explora las características de ABP Framework", + "ABPCLI": "ABP CLI", + "Modularity": "Modularidad", + "BootstrapTagHelpers": "Bootstrap Tag Helpers", + "DynamicForms": "Formularios dinámicos", + "BundlingMinification": "Empaquetado y Minimificación", + "BackgroundJobs": "", + "BackgroundJobsExplanation": "Defina clases simples para ejecutar trabajos en segundo plano como en cola. Utilice el administrador de trabajos integrado o integre el suyo propio. Hangfire & RabbitMQ integraciones están actualmente disponibles.", + "DDDInfrastructure": "infraestructura DSS", + "DomainDrivenDesignInfrastructure": "infraestructura Domain Driven Design", + "AutoRESTAPIs": "Auto REST APIs", + "DynamicClientProxies": "Clientes proxies dinámicos", + "DistributedEventBus": "Bus de eventos distribuido", + "DistributedEventBusWithRabbitMQIntegration": "Bus de eventos distribuido con la integración RabbitMQ ", + "TestInfrastructure": "infraestructura de Test", + "AuditLoggingEntityHistories": "Registro de auditoría y historial de entidades", + "ObjectToObjectMapping": "Mapeado objeto a objeto", + "ObjectToObjectMappingExplanation": "Mapeado objeto a objeto abstracción integrada con AutoMapper.", + "EmailSMSAbstractions": "Abstracciones para Email y SMS", + "EmailSMSAbstractionsWithTemplatingSupport": "Abstracciones para Email y SMS con soporte para plantillas", + "Localization": "Localización", + "SettingManagement": "Gestión de la configuración", + "ExtensionMethods": "Extension Methods", + "ExtensionMethodsHelpers": "Extension Methods & Helpers", + "AspectOrientedProgramming": "Programación orientada a aspectos", + "DependencyInjection": "Inyección de dependencias", + "DependencyInjectionByConventions": "Inyección de dependencias por convenciones", + "ABPCLIExplanation": "ABP CLI (Command Line Interface) es una herramienta en línea de comandos que proporciona ciertas tareas comunes para soluciones basadas en ABP.", + "ModularityExplanation": "ABP proporciona una infraestructura completa para construir tu propios módulos de aplicación que pueden contener entidades, servicios, base de datos integradas, APIs, componentes de UI y otros...", + "MultiTenancyExplanation": "ABP framework no sólo soporta el desarrollo de aplicaciones multi-inquilino, si no también hace que tu código no tenga que preocuparse de multi-inquilino.", + "MultiTenancyExplanation2": "Puedes determinar automaticamente el inquilino actual, y aislar los datos de diferentes inquilinos entre sí. ", + "MultiTenancyExplanation3": "Soporta base de datos única, base de datos por inquilino y enfoques híbridos.", + "MultiTenancyExplanation4": "Enfocate en tu código y deja al framework que maneje multi-inquilino en tu nombre.", + "BootstrapTagHelpersExplanation": "En vez de escribir repetidamente los detalle de componentes bootstrap, usa ABP's tag helpers para simplificarlo y obtener ventaja de intellisence. Tu puedes definitivamente usar Bootstrp cuando tu lo necesites.", + "DynamicFormsExplanation": "Los formularios dinámicos y tag helpers de entrada pueden crear el formulario completo a partir de una clase de C# como modelo. ", + "AuthenticationAuthorizationExplanation": "Autenticación enriquecidad y opciones de autorización integradas con ASP.NET Core Identity & IdentityServer4. Proporciona un extensible y detallado sistema de permisos.", + "CrossCuttingConcernsExplanation": "No te repitas tu mismo al implementar todas esas cosas comunes una y otra vez. Enfocate en tu negocio y permite a ABP automatizarlos por convención.", + "DatabaseConnectionTransactionManagement": "Conexión de base de datos y gestión de transacciones", + "CorrelationIdTracking": "Correlation-Id de seguimiento", + "BundlingMinificationExplanation": "ABP ofrece un sistema simple, dinámico, potente, modular y empaquetado & minificación ", + "VirtualFileSystemnExplanation": "El sistema de archivos virtuales permite administrar archivos que no existen físicamente en el sistema de archivos (disco). Se utiliza principalmente para incrustar (js, css, image, cshtml...) en ensamblados y utilizarlos como archivos físicos en tiempo de ejecución.", + "ThemingExplanation": "El sistema de temas permite desarrollar el tema de su aplicación y módulos independiente mediante la definición de un conjunto de bibliotecas y diseños base comunes, basado en el último marco de Trabajo bootstrap.", + "DomainDrivenDesignInfrastructureExplanation": "Una infraestructura completa para crear aplicaciones en capas basadas en los patrones y principios DDD", + "Specification": "Especificación", + "Repository": "Repositorios", + "DomainService": "Servicio de dominio", + "ValueObject": "Objetos de valor", + "ApplicationService": "Servicio de aplicación", + "DataTransferObject": "Objetos de transferencia de datos", + "AggregateRootEntity": "Agregado ráiz, Entidad", + "AutoRESTAPIsExplanation": "ABP puede configurar automáticamente los servicios de aplicación como controladores de API por convención.", + "DynamicClientProxiesExplanation": "Consuma fácilmente sus API de clientes de JavaScript y C#", + "DistributedEventBusWithRabbitMQIntegrationExplanation": "Publique y consuma eventos distribuidos fácilmente mediante el bus de eventos distribuido integrado con la integración RabbitMQ disponible.", + "TestInfrastructureExplanation": "El framework se ha desarrollado unitariamente y pruebas de integración. Proporciona clases base para que sea más fácil. Las plantillas de inicio vienen preconfiguradas para las pruebas.", + "AuditLoggingEntityHistoriesExplanation": "Registro de auditoría integrado para aplicaciones críticas para el negocio. Registro de auditorías de solicitud, servicio, nivel de método e historiales de entidades con detalles de nivel de propiedad.", + "EmailSMSAbstractionsWithTemplatingSupportExplanation": "Las abstracciones IEmailSender e ISmsSender desacoplan la lógica de la aplicación de la infraestructura. El sistema avanzado de plantillas de correo electrónico permite crear y localizar plantillas de correo electrónico y utilizarlas fácilmente cuando sea necesario.", + "LocalizationExplanation": "El sistema de localización permite crear recursos en archivos JSON sin formato y utilizarlos para localizar la interfaz de usuario. Admite escenarios avanzados como herencia, extensiones e integración de JavaScript, mientras que es totalmente compatible con el sistema de localización de AspNet Core.", + "SettingManagementExplanation": "Defina la configuración de la aplicación y obtenga valores en tiempo de ejecución en función de la configuración actual, el inquilino y el usuario.", + "ExtensionMethodsHelpersExplanation": "No te repitas ni siquiera para partes de código triviales. Extensiones y ayudantes para tipos estándar hace que su código sea mucho más limpio y fácil de escribir.", + "AspectOrientedProgrammingExplanation": "Proporciona una infraestructura cómoda para crear servidores proxy dinámicos e implementar la programación orientada a aspectos. Interceptar cualquier clase y ejecutar el código antes y después de cada ejecución del método.", + "DependencyInjectionByConventionsExplanation": "No es necesario registrar las clases en la inserción de dependencias manualmente. Registra automáticamente los tipos de servicio comunes por convención. Para otro tipo de servicios, puede utilizar interfaces y atributos para que sea más fácil y in situ.", + "DataFilteringExplanation": "Definir y usar filtros de datos que se aplican automáticamente al consultar entidades desde la base de datos. Los filtros Soft Delete & MultiTenant se proporcionan de fábrica cuando se implementan interfaces sencillas.", + "PublishEvents": "Publicar eventos", + "HandleEvents": "Manejar eventos", + "AndMore": "y más...", + "Code": "Código", + "Result": "Resultado", + "SeeTheDocumentForMoreInformation": "Ver el {0} documento para más información.", + "IndexPageHeroSection": "Código fuente abiertoWeb Application
Framework
para asp.net core", + "UiFramework": "UI Framework", + "EmailAddress": "Dirección de correo", + "Mobile": "Móvil", + "ReactNative": "React Nativo", + "Strong": "Fuerte", + "Complete": "Completar", + "BasedLayeringModel": "Módelo basado en capas", + "Microservice": "Microservicio", + "Compatible": "Compatible", + "MeeTTheABPCommunityInfo": "Nuestra misión es crear un entorno en el que los desarrolladores puedan ayudarse entre sí con artículos, tutoriales, estudios de casos, etc. y conocer personas de ideas afines.", + "JoinTheABPCommunityInfo": "¡Participe en una comunidad vibrante y conviértase en colaborador del Marco ABP!", + "AllArticles": "Todos los artículos", + "SubmitYourArticle": "Envía tu artículo", + "DynamicClientProxyDocument": "Ver la documentación del cliente proxy dinámico para JavaScript & C#.", + "EmailSMSAbstractionsDocument": "Ver los documentos de emailing y envío SMS para más información.", + "CreateProjectWizard": "Este asistente crea un nuevo proyecto a partir de la plantilla de inicio que está correctamente configurado para comenzar con su proyecto.", + "TieredOption": "Crea una solución por niveles en la que las capas de API Web y HTTP están separadas físicamente. Si no se marca, crea una solución en capas que es menos compleja y adecuada para la mayoría de los escenarios.", + "SeparateIdentityServerOption": "Separa el lado del servidor en dos aplicaciones: la primera es para el servidor de identidad y la segunda es para la API HTTP del lado del servidor.", + "UseslatestPreVersion": "Usar la última versión pre-release", + "ReadTheDocumentation": "LeerLa Documentación", + "Documentation": "Documentación", + "GettingStartedTutorial": "Tutorial para iniciarse", + "ApplicationDevelopmentTutorial": "Tutorial de desarrollo de aplicación", + "TheStartupTemplate": "La Plantilla de Inicio", + "InstallABPCLIInfo": "ABP CLI es la forma más rápida de iniciar una nueva solución con el marco ABP. Instale la CLI de ABP mediante una ventana de línea de comandos:", + "DifferentLevelOfNamespaces": "Tu puedes usar diferentes niveles de espacio de nombres; ej. BookStore, Acme.BookStore or Acme.Retail.BookStore.", + "ABPCLIExamplesInfo": "nuevo comando crea una aplicación MVC por capas con Entity Framework Core como proveedor de base de datos. Sin embargo, tiene distintas opciones. Ejemplos:", + "SeeCliDocumentForMoreInformation": "Ver el documento ABP CLI para más opciones o selecciona la \"Direct Download\" pestaña de arriba.", + "Optional": "Opcional", + "LocalFrameworkRef": "Mantén la referencia al proyecto local para los paquetes del framework." + } +} \ No newline at end of file diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/zh-Hans.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/zh-Hans.json index 7bd02b44ac..6e9d9bf0da 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/zh-Hans.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/zh-Hans.json @@ -89,10 +89,11 @@ "Features": "功能", "ABPCLI": "ABP CLI", "Modularity": "模块化", - "BootstrapTagHelpers": "Bootstrap Tag Helpers", + "BootstrapTagHelpers": "Bootstrap 标签助手", "DynamicForms": "动态表单", "BundlingMinification": "Bundling & Minification", "BackgroundJobs": "后台作业", + "BackgroundJobsExplanation": "定义简单的类以在队列中在后台执行作业. 使用内置的作业管理器或集成你自己的作业管理器. Hangfire & RabbitMQ集成已经可用.", "DDDInfrastructure": "DDD基础设施", "DomainDrivenDesignInfrastructure": "Domain Driven Design基础设施", "AutoRESTAPIs": "自动REST APIs", @@ -102,6 +103,7 @@ "TestInfrastructure": "测试基础设施", "AuditLoggingEntityHistories": "审计日志和实体历史", "ObjectToObjectMapping": "对象映射", + "ObjectToObjectMappingExplanation": "对象到对象映射 抽象AutoMapper集成.", "EmailSMSAbstractions": "电子邮件和短信抽象", "EmailSMSAbstractionsWithTemplatingSupport": "具有模板支持的电子邮件和短信抽象", "Localization": "本土化", @@ -112,7 +114,7 @@ "DependencyInjection": "依赖注入", "DependencyInjectionByConventions": "依据约定的依赖注入", "ABPCLIExplanation": "ABP CLI(命令行界面)是用于对ABP解决方案执行常见操作的命令行工具.", - "ModularityExplanation": "ABP提供了一个完整的基础设施来构建你自己的应用程序模块,这些模块可能具有实体,服务,数据库集成,API,UI组件等.", //TODO: strong "your own application modules",- + "ModularityExplanation": "ABP提供了一个完整的基础设施来构建你自己的应用程序模块,这些模块可能具有实体,服务,数据库集成,API,UI组件等.", "MultiTenancyExplanation": "ABP框架不仅支持开发多租户应用程序,而且使你的代码几乎无需知道多租户.", "MultiTenancyExplanation2": "可以自动确定当前租户,将不同租户的数据相互隔离.", "MultiTenancyExplanation3": "支持单一数据库,或每个租户单独数据库或者混合方式.", @@ -154,6 +156,41 @@ "SeeTheDocumentForMoreInformation": "查看{0} 文档获得更多信息", "IndexPageHeroSection": "asp.net core的开源Web应用程序
框架
", "UiFramework": "UI框架", - "EmailAddress": "电子邮件地址" + "EmailAddress": "电子邮件地址", + "Mobile": "移动", + "ReactNative": "React Native", + "Strong": "强大的", + "Complete": "完整的", + "BasedLayeringModel": "基于分层模型", + "Microservice": "微服务", + "Compatible": "兼容", + "MeeTTheABPCommunityInfo": "我们的使命是创建一个环境使开发人员可以在文章,教程,案例研究等方面互相帮助并结识志趣相投的人.", + "JoinTheABPCommunityInfo": "参与充满活力的社区并成为ABP框架的贡献者", + "AllArticles": "所有的文章", + "SubmitYourArticle": "提交你的文章", + "DynamicClientProxyDocument": "参阅JavaScript & C#的动态客户端代理文档.", + "EmailSMSAbstractionsDocument": "参阅emailing 和 SMS sending 文档获得更多信息.", + "CreateProjectWizard": "此向导让你从启动模板创建一个新项目,该启动模板已正确配置为可以快速启动你的项目.", + "TieredOption": "创建一个分层解决方案,其中Web和Http API层在物理上是分离的. 如果没有选中则创建一个不那么复杂且适合大多数场景的分层解决方案.", + "SeparateIdentityServerOption": "将服务器端分离为两个应用程序:第一个应用程序用于身份服务器,第二个应用程序用于服务器端HTTP API.", + "UseslatestPreVersion": "使用最新的预发布版本", + "ReadTheDocumentation": "阅读文档", + "Documentation": "文档", + "GettingStartedTutorial": "入门教程", + "ApplicationDevelopmentTutorial": "应用程序开发教程", + "TheStartupTemplate": "启动模板", + "InstallABPCLIInfo": "ABP CLI是使用ABP框架启动新解决方案的最快方式. 使用命令行窗口安装ABP CLI:", + "DifferentLevelOfNamespaces": "你可以使用不同级别的名称空间. 例如 BookStore, Acme.BookStore 或 Acme.Retail.BookStore", + "ABPCLIExamplesInfo": "new命令创建一个 分层的MVC应用程序 使用 Entity Framework Core 做为数据库提供程序. 它还有其他选项. 示例:", + "SeeCliDocumentForMoreInformation": "参阅 ABP CLI 文档 获得更多选项或选择上方的 \"直接下载\" 标签.", + "Optional": "可选的", + "LocalFrameworkRef": "保留框架包的本地项目引用.", + "BlobStoring": "BLOB存储", + "BlobStoringExplanation": "BLOB存储系统提供了BLOB的抽象. ABP提供了一些预构建的存储提供程序集成(Azure,AWS,文件系统,数据库等),你可以轻松的在你的应用程序中使用它们.", + "TextTemplating": "文本模板", + "TextTemplatingExplanation": "文本模板是基于模板和模型(数据对象)使用动态渲染内容. 例如你可以使用预构建的模板来创建动态的电子邮件内容.", + "MultipleUIOptions": "多个UI选项", + "MultipleDBOptions": "多个数据库提供程序", + "MultipleUIOptionsExplanation": "核心框架设计为独立与UI,可以和任何类型的UI系统一起使用. 同时提供了多个开箱即用的预构建集成选项." } } \ No newline at end of file diff --git a/build/common.ps1 b/build/common.ps1 index 18019a154e..0afe55f120 100644 --- a/build/common.ps1 +++ b/build/common.ps1 @@ -16,7 +16,9 @@ $solutionPaths = @( "../modules/tenant-management", "../modules/audit-logging", "../modules/background-jobs", - "../modules/account" + "../modules/account", + "../modules/cms-kit", + "../modules/blob-storing-database" ) if ($full -eq "-f") @@ -29,6 +31,8 @@ if ($full -eq "-f") "../modules/blogging", "../templates/module/aspnet-core", "../templates/app/aspnet-core", + "../templates/console", + "../templates/wpf", "../abp_io/AbpIoLocalization" ) }else{ diff --git a/common.DotSettings b/common.DotSettings index 6f40d029a7..7edbd05e75 100644 --- a/common.DotSettings +++ b/common.DotSettings @@ -20,6 +20,17 @@ False False SQL + False + Never + Never + False + Never + Never + Never + Never + Never + True + True False False False diff --git a/common.props b/common.props index 5671a3fc31..1528abbcc6 100644 --- a/common.props +++ b/common.props @@ -1,7 +1,7 @@ - - latest - 3.3.0 + + latest + 4.1.0 $(NoWarn);CS1591;CS0436 https://abp.io/assets/abp_nupkg.png https://abp.io/ diff --git a/docs/en/API/Auto-API-Controllers.md b/docs/en/API/Auto-API-Controllers.md index 77819c48c9..e139c16d20 100644 --- a/docs/en/API/Auto-API-Controllers.md +++ b/docs/en/API/Auto-API-Controllers.md @@ -75,17 +75,48 @@ Configure(options => Then the route for getting a book will be '**/api/volosoft/book-store/book/{id}**'. This sample uses two-level root path, but you generally use a single level depth. -* Continues with the **normalized controller/service name**. Normalization removes 'AppService', 'ApplicationService' and 'Service' postfixes and converts it to **camelCase**. If your application service class name is 'BookAppService' then it becomes only '/book'. +* Continues with the **normalized controller/service name**. Normalization removes 'AppService', 'ApplicationService' and 'Service' postfixes and converts it to **kebab-case**. If your application service class name is 'ReadingBookAppService' then it becomes only '/reading-book'. * If you want to customize naming, then set the `UrlControllerNameNormalizer` option. It's a func delegate which allows you to determine the name per controller/service. * If the method has an '**id**' parameter then it adds '**/{id}**' ro the route. * Then it adds the action name if necessary. Action name is obtained from the method name on the service and normalized by; * Removing '**Async**' postfix. If the method name is 'GetPhonesAsync' then it becomes 'GetPhones'. * Removing **HTTP method prefix**. 'GetList', 'GetAll', 'Get', 'Put', 'Update', 'Delete', 'Remove', 'Create', 'Add', 'Insert', 'Post' and 'Patch' prefixes are removed based on the selected HTTP method. So, 'GetPhones' becomes 'Phones' since 'Get' prefix is a duplicate for a GET request. - * Converting the result to **camelCase**. + * Converting the result to **kebab-case**. * If the resulting action name is **empty** then it's not added to the route. If it's not empty, it's added to the route (like '/phones'). For 'GetAllAsync' method name it will be empty, for 'GetPhonesAsync' method name it will be 'phones'. * Normalization can be customized by setting the `UrlActionNameNormalizer` option. It's an action delegate that is called for every method. * If there is another parameter with 'Id' postfix, then it's also added to the route as the final route segment (like '/phoneId'). +#### Customizing the Route Calculation + +`IConventionalRouteBuilder` is used to build the route. It is implemented by the `ConventionalRouteBuilder` by default and works as explained above. You can replace/override this service to customize the route calculation strategy. + +#### Version 3.x Style Route Calculation + +The route calculation was different before the version 4.0. It was using camelCase conventions, while the ABP Framework version 4.0+ uses kebab-case. If you use the old route calculation strategy, follow one of the approaches; + +* Set `UseV3UrlStyle` to `true` in the options of the `options.ConventionalControllers.Create(...)` method. Example: + +````csharp +options.ConventionalControllers + .Create(typeof(BookStoreApplicationModule).Assembly, opts => + { + opts.UseV3UrlStyle = true; + }); +```` + +This approach effects only the controllers for the `BookStoreApplicationModule`. + +* Set `UseV3UrlStyle` to `true` for the `AbpConventionalControllerOptions` to set it globally. Example: + +```csharp +Configure(options => +{ + options.UseV3UrlStyle = true; +}); +``` + +Setting it globally effects all the modules in a modular application. + ## Service Selection Creating conventional HTTP API controllers are not unique to application services actually. diff --git a/docs/en/API/Dynamic-CSharp-API-Clients.md b/docs/en/API/Dynamic-CSharp-API-Clients.md index 23ec336acf..b1d71e0bb1 100644 --- a/docs/en/API/Dynamic-CSharp-API-Clients.md +++ b/docs/en/API/Dynamic-CSharp-API-Clients.md @@ -1,10 +1,23 @@ -# Dynamic C# API Clients +# Dynamic C# API Client Proxies -ABP can dynamically create C# API client proxies to call remote HTTP services (REST APIs). In this way, you don't need to deal with `HttpClient` and other low level HTTP features to call remote services and get results. +ABP can dynamically create C# API client proxies to call your remote HTTP services (REST APIs). In this way, you don't need to deal with `HttpClient` and other low level details to call remote services and get results. + +Dynamic C# proxies automatically handles the following stuff for you; + +* Maps C# **method calls** to remote server **HTTP calls** by considering the HTTP method, route, query string parameters, request payload and other details. +* **Authenticates** the HTTP Client by adding access token to the HTTP header. +* **Serializes** to and deserialize from JSON. +* Handles HTTP API **versioning**. +* Add **correlation id**, current **tenant** id and the current **culture** to the request. +* Properly **handles the error messages** sent by the server and throws proper exceptions. + +This system can be used by any type of .NET client to consume your HTTP APIs. ## Service Interface -Your service/controller should implement an interface that is shared between the server and the client. So, first define a service interface in a shared library project. Example: +Your service/controller should implement an interface that is shared between the server and the client. So, first define a service interface in a shared library project, typically in the `Application.Contracts` project if you've created your solution using the startup templates. + +Example: ````csharp public interface IBookAppService : IApplicationService @@ -13,7 +26,7 @@ public interface IBookAppService : IApplicationService } ```` -Your interface should implement the `IRemoteService` interface to be automatically discovered. Since the `IApplicationService` inherits the `IRemoteService` interface, the `IBookAppService` above satisfies this condition. +> Your interface should implement the `IRemoteService` interface to be automatically discovered. Since the `IApplicationService` inherits the `IRemoteService` interface, the `IBookAppService` above satisfies this condition. Implement this class in your service application. You can use [auto API controller system](Auto-API-Controllers.md) to expose the service as a REST API endpoint. @@ -55,6 +68,8 @@ public class MyClientAppModule : AbpModule `AddHttpClientProxies` method gets an assembly, finds all service interfaces in the given assembly, creates and registers proxy classes. +> The startup templates already comes pre-configured for the client proxy generation, in the `HttpApi.Client` project. + ### Endpoint Configuration `RemoteServices` section in the `appsettings.json` file is used to get remote service address by default. Simplest configuration is shown below: @@ -106,7 +121,7 @@ While you can inject `IBookAppService` like above to use the client proxy, you c ### AbpRemoteServiceOptions -`AbpRemoteServiceOptions` is automatically set from the `appsettings.json` by default. Alternatively, you can use `Configure` method to set or override it. Example: +`AbpRemoteServiceOptions` is automatically set from the `appsettings.json` by default. Alternatively, you can configure it in the `ConfigureServices` method of your [module](../Module-Development-Basics.md) to set or override it. Example: ````csharp public override void ConfigureServices(ServiceConfigurationContext context) @@ -162,4 +177,30 @@ context.Services.AddHttpClientProxies( Using `asDefaultServices: false` may only be needed if your application has already an implementation of the service and you do not want to override/replace the other implementation by your client proxy. -> If you disable `asDefaultServices`, you can only use `IHttpClientProxy` interface to use the client proxies. See the *IHttpClientProxy Interface* section above. \ No newline at end of file +> If you disable `asDefaultServices`, you can only use `IHttpClientProxy` interface to use the client proxies. See the *IHttpClientProxy Interface* section above. + +### Retry/Failure Logic & Polly Integration + +If you want to add retry logic for the failing remote HTTP calls for the client proxies, you can configure the `AbpHttpClientBuilderOptions` in the `PreConfigureServices` method of your module class. + +**Example: Use the [Polly](https://github.com/App-vNext/Polly) library to re-try 3 times on a failure** + +````csharp +public override void PreConfigureServices(ServiceConfigurationContext context) +{ + PreConfigure(options => + { + options.ProxyClientBuildActions.Add((remoteServiceName, clientBuilder) => + { + clientBuilder.AddTransientHttpErrorPolicy(policyBuilder => + policyBuilder.WaitAndRetryAsync( + 3, + i => TimeSpan.FromSeconds(Math.Pow(2, i)) + ) + ); + }); + }); +} +```` + +This example uses the [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly) package. You also need to import the `Polly` namespace (`using Polly;`) to be able to use the `WaitAndRetryAsync` method. \ No newline at end of file diff --git a/docs/en/Application-Services.md b/docs/en/Application-Services.md index 9cfec614cb..7fe9825f2a 100644 --- a/docs/en/Application-Services.md +++ b/docs/en/Application-Services.md @@ -342,12 +342,12 @@ public class DistrictAppService { } - protected override async Task DeleteByIdAsync(DistrictKey id) + protected async override Task DeleteByIdAsync(DistrictKey id) { await Repository.DeleteAsync(d => d.CityId == id.CityId && d.Name == id.Name); } - protected override async Task GetEntityByIdAsync(DistrictKey id) + protected async override Task GetEntityByIdAsync(DistrictKey id) { return await AsyncQueryableExecuter.FirstOrDefaultAsync( Repository.Where(d => d.CityId == id.CityId && d.Name == id.Name) @@ -400,7 +400,7 @@ public class MyPeopleAppService : CrudAppService { } - protected override async Task CheckDeletePolicyAsync() + protected async override Task CheckDeletePolicyAsync() { await AuthorizationService.CheckAsync("..."); } @@ -445,6 +445,68 @@ These methods are used to convert Entities to DTOs and vice verse. They uses the * `MapToEntityAsync(TCreateInput)` is used to create an entity from `TCreateInput`. * `MapToEntityAsync(TUpdateInput, TEntity)` is used to update an existing entity from `TUpdateInput`. +## Miscellaneous + +### Working with Streams + +`Stream` object itself is not serializable. So, you may have problems if you directly use `Stream` as the parameter or the return value for your application service. ABP Framework provides a special type, `IRemoteStreamContent` to be used to get or return streams in the application services. + +**Example: Application Service Interface that can be used to get and return streams** + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; +using Volo.Abp.Content; + +namespace MyProject.Test +{ + public interface ITestAppService : IApplicationService + { + Task Upload(Guid id, IRemoteStreamContent streamContent); + Task Download(Guid id); + } +} +```` + +**Example: Application Service Implementation that can be used to get and return streams** + +````csharp +using System; +using System.IO; +using System.Threading.Tasks; +using Volo.Abp; +using Volo.Abp.Application.Services; +using Volo.Abp.Content; + +namespace MyProject.Test +{ + public class TestAppService : ApplicationService, ITestAppService + { + public Task Download(Guid id) + { + var fs = new FileStream("C:\\Temp\\" + id + ".blob", FileMode.OpenOrCreate); + return Task.FromResult( + (IRemoteStreamContent) new RemoteStreamContent(fs) { + ContentType = "application/octet-stream" + } + ); + } + + public async Task Upload(Guid id, IRemoteStreamContent streamContent) + { + using (var fs = new FileStream("C:\\Temp\\" + id + ".blob", FileMode.Create)) + { + await streamContent.GetStream().CopyToAsync(fs); + await fs.FlushAsync(); + } + } + } +} +```` + +`IRemoteStreamContent` is compatible with the [Auto API Controller](API/Auto-API-Controllers.md) and [Dynamic C# HTTP Proxy](API/Dynamic-CSharp-API-Clients.md) systems. + ## Lifetime Lifetime of application services are [transient](Dependency-Injection.md) and they are automatically registered to the dependency injection system. diff --git a/docs/en/AspNet-Boilerplate-Migration-Guide.md b/docs/en/AspNet-Boilerplate-Migration-Guide.md index c7cc8a9e53..f4c2ec712b 100644 --- a/docs/en/AspNet-Boilerplate-Migration-Guide.md +++ b/docs/en/AspNet-Boilerplate-Migration-Guide.md @@ -438,7 +438,7 @@ ABP Framework uses and extends ASP.NET Core's [distributed caching abstraction]( ### Logging -ASP.NET Boilerplate uses Castle Windsor's [logging facility](http://docs.castleproject.org/Windsor.Logging-Facility.ashx) as an abstraction and supports multiple logging providers including Log4Net (the default one comes with the startup projects) and Serilog. You typically property-inject the logger: +ASP.NET Boilerplate uses Castle Windsor's [logging facility](https://github.com/castleproject/Windsor/blob/master/docs/logging-facility.md) as an abstraction and supports multiple logging providers including Log4Net (the default one comes with the startup projects) and Serilog. You typically property-inject the logger: ````csharp using Castle.Core.Logging; //1: Import Logging namespace diff --git a/docs/en/Authentication/Social-External-Logins.md b/docs/en/Authentication/Social-External-Logins.md index 309d4977a5..e80e53d4bd 100644 --- a/docs/en/Authentication/Social-External-Logins.md +++ b/docs/en/Authentication/Social-External-Logins.md @@ -1,32 +1,3 @@ # Social/External Logins -The [Account Module](../Modules/Account.md) has already configured to handle social or external logins out of the box. You can follow the ASP.NET Core documentation to add a social/external login provider to your application. - -## Example: Facebook Authentication - -Follow the [ASP.NET Core Facebook integration document](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins) to support the Facebook login for your application. - -#### Add the NuGet Package - -Add the [Microsoft.AspNetCore.Authentication.Facebook](https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.Facebook) package to your project. Based on your architecture, this can be `.Web`, `.IdentityServer` (for tiered setup) or `.Host` project. - -#### Configure the Provider - -Use the `.AddFacebook(...)` extension method in the `ConfigureServices` method of your [module](../Module-Development-Basics.md), to configure the client: - -````csharp -context.Services.AddAuthentication() - .AddFacebook(facebook => - { - facebook.AppId = "..."; - facebook.AppSecret = "..."; - facebook.Scope.Add("email"); - facebook.Scope.Add("public_profile"); - }); -```` - -> It would be a better practice to use the `appsettings.json` or the ASP.NET Core User Secrets system to store your credentials, instead of a hard-coded value like that. Follow the [Microsoft's document](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins) to learn the user secrets usage. - -## Angular UI - -Beginning from the v3.1, the Angular UI uses authorization code flow (as a best practice) to authenticate the user by redirecting to the MVC UI login page. So, even if you are using the Angular UI, social/external login integration is same as explained above and it will work out of the box. \ No newline at end of file +> This document has been moved. See the [Account Module](../Modules/Account.md) documentation. \ No newline at end of file diff --git a/docs/en/Authorization.md b/docs/en/Authorization.md index eef4237039..bceca3548f 100644 --- a/docs/en/Authorization.md +++ b/docs/en/Authorization.md @@ -234,7 +234,7 @@ context When you write this code inside your permission definition provider, it finds the "role deletion" permission of the [Identity Module](Modules/Identity.md) and disabled the permission, so no one can delete a role on the application. -> Tip: It is better to check the value returned by the `GetPermissionOrNull` method since it may return null if the given permission was not defined. +> Tip: It is better to check the value returned by the `GetPermissionOrNull` method since it may return null if the given permission was not defined. ## IAuthorizationService @@ -354,7 +354,7 @@ public class SystemAdminPermissionValueProvider : PermissionValueProvider public override string Name => "SystemAdmin"; - public override async Task + public async override Task CheckAsync(PermissionValueCheckContext context) { if (context.Principal?.FindFirst("User_Type")?.Value == "SystemAdmin") @@ -406,5 +406,5 @@ This is already done for the startup template integration tests. ## See Also * [Permission Management Module](Modules/Permission-Management.md) -* [ASP.NET Core MVC / Razor Pages JavaScript Auth API](API/JavaScript-API/Auth.md) +* [ASP.NET Core MVC / Razor Pages JavaScript Auth API](UI/AspNetCore/JavaScript-API/Auth.md) * [Permission Management in Angular UI](UI/Angular/Permission-Management.md) diff --git a/docs/en/Background-Jobs-RabbitMq.md b/docs/en/Background-Jobs-RabbitMq.md index a984a2a3ab..2ee478ed17 100644 --- a/docs/en/Background-Jobs-RabbitMq.md +++ b/docs/en/Background-Jobs-RabbitMq.md @@ -1,3 +1,133 @@ # RabbitMQ Background Job Manager -TODO \ No newline at end of file +RabbitMQ is an industry standard message broker. While it is typically used for inter-process communication (messaging / distributed events), it is pretty useful to store and execute background jobs in FIFO (First In First Out) order. + +ABP Framework provides the [Volo.Abp.BackgroundJobs.RabbitMQ](https://www.nuget.org/packages/Volo.Abp.BackgroundJobs.RabbitMQ) NuGet package to use the RabbitMQ for background job execution. + +> See the [background jobs document](Background-Jobs.md) to learn how to use the background job system. This document only shows how to install and configure the RabbitMQ integration. + +## Installation + +Use the ABP CLI to add [Volo.Abp.BackgroundJobs.RabbitMQ](https://www.nuget.org/packages/Volo.Abp.BackgroundJobs.RabbitMQ) NuGet package to your project: + +* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed before. +* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.BackgroundJobs.RabbitMQ` package. +* Run `abp add-package Volo.Abp.BackgroundJobs.RabbitMQ` command. + +If you want to do it manually, install the [Volo.Abp.BackgroundJobs.RabbitMQ](https://www.nuget.org/packages/Volo.Abp.BackgroundJobs.RabbitMQ) NuGet package to your project and add `[DependsOn(typeof(AbpBackgroundJobsRabbitMqModule))]` to the [ABP module](Module-Development-Basics.md) class inside your project. + +## Configuration + +### Default Configuration + +The default configuration automatically connects to the local RabbitMQ server (localhost) with the standard port. **In this case, no configuration needed.** + +### RabbitMQ Connection(s) + +You can configure the RabbitMQ connections using the standard [configuration system](Configuration.md), like using the `appsettings.json` file, or using the [options](Options.md) classes. + +#### `appsettings.json` file configuration + +This is the simplest way to configure the RabbitMQ connections. It is also very strong since you can use any other configuration source (like environment variables) that is [supported by the AspNet Core](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/). + +**Example: Configuring the Default RabbitMQ Connection** + +````json +{ + "RabbitMQ": { + "Connections": { + "Default": { + "HostName": "123.123.123.123", + "Port": "5672" + } + } + } +} +```` + +You can use any of the [ConnectionFactry](http://rabbitmq.github.io/rabbitmq-dotnet-client/api/RabbitMQ.Client.ConnectionFactory.html#properties) properties as the connection properties. See [the RabbitMQ document](https://www.rabbitmq.com/dotnet-api-guide.html#exchanges-and-queues) to understand these options better. + +Defining multiple connections is allowed. In this case, you can use different connections for different background job types (see the `AbpRabbitMqBackgroundJobOptions` section below). + +**Example: Declare two connections** + +````json +{ + "RabbitMQ": { + "Connections": { + "Default": { + "HostName": "123.123.123.123" + }, + "SecondConnection": { + "HostName": "321.321.321.321" + } + } + } +} +```` + +#### AbpRabbitMqOptions + +`AbpRabbitMqOptions` class can be used to configure the connection strings for the RabbitMQ. You can configure this options inside the `ConfigureServices` of your [module](Module-Development-Basics.md). + +**Example: Configure the connection** + +````csharp +Configure(options => +{ + options.Connections.Default.UserName = "user"; + options.Connections.Default.Password = "pass"; + options.Connections.Default.HostName = "123.123.123.123"; + options.Connections.Default.Port = 5672; +}); +```` + +Using these options classes can be combined with the `appsettings.json` way. Configuring an option property in the code overrides the value in the configuration file. + +### AbpRabbitMqBackgroundJobOptions + +#### Job Queue Names + +By default, each job type uses a separate queue. Queue names are calculated by combining a standard prefix and the job name. Default prefix is `AbpBackgroundJobs.` So, if the job name is `EmailSending` then the queue name in the RabbitMQ becomes `AbpBackgroundJobs.EmailSending` + +> Use `BackgroundJobName` attribute on the background **job argument** class to specify the job name. Otherwise, the job name will be the full name (with namespace) of the job class. + +#### Job Connections + +By default, all the job types use the `Default` RabbitMQ connection. + +#### Customization + +`AbpRabbitMqBackgroundJobOptions` can be used to customize the queue names and the connections used by the jobs. + +**Example:** + +````csharp +Configure(options => +{ + options.DefaultQueueNamePrefix = "my_app_jobs."; + options.JobQueues[typeof(EmailSendingArgs)] = + new JobQueueConfiguration( + typeof(EmailSendingArgs), + queueName: "my_app_jobs.emails", + connectionName: "SecondConnection" + ); +}); +```` + +* This example sets the default queue name prefix to `my_app_jobs.`. If different applications use the same RabbitMQ server, it would be important to use different prefixes for each application to not consume jobs of each other. +* Also specifies a different connection string for the `EmailSendingArgs`. + +`JobQueueConfiguration` class has some additional options in its constructor; + +* `queueName`: The queue name that is used for this job. The prefix is not added, so you need to specify the full name of the queue. +* `connectionName`: The RabbitMQ connection name (see the connection configuration above). This is optional and the default value is `Default`. +* `durable` (optional, default: `true`). +* `exclusive` (optional, default: `false`). +* `autoDelete` (optional, default: `false`) + +See the RabbitMQ documentation if you want to understand the `durable`, `exclusive` and `autoDelete` options better, while most of the times the default configuration is what you want. + +## See Also + +* [Background Jobs](Background-Jobs.md) \ No newline at end of file diff --git a/docs/en/Background-Jobs.md b/docs/en/Background-Jobs.md index e5ef87bb2d..2e0b5d3f65 100644 --- a/docs/en/Background-Jobs.md +++ b/docs/en/Background-Jobs.md @@ -13,7 +13,7 @@ Background jobs are **persistent** that means they will be **re-tried** and **ex ABP provides an **abstraction** module and **several implementations** for background jobs. It has a built-in/default implementation as well as Hangfire, RabbitMQ and Quartz integrations. -`Volo.Abp.BackgroundJobs.Abstractions` nuget package provides needed services to create background jobs and queue background job items. If your module only depend on this package, it can be independent from the actual implementation/integration. +`Volo.Abp.BackgroundJobs.Abstractions` NuGet package provides needed services to create background jobs and queue background job items. If your module only depend on this package, it can be independent from the actual implementation/integration. > `Volo.Abp.BackgroundJobs.Abstractions` package is installed to the startup templates by default. @@ -24,23 +24,29 @@ A background job is a class that implements the `IBackgroundJob` interfac This example is used to send emails in background. First, define a class to store arguments of the background job: ````csharp -public class EmailSendingArgs +namespace MyProject { - public string EmailAddress { get; set; } - public string Subject { get; set; } - public string Body { get; set; } + public class EmailSendingArgs + { + public string EmailAddress { get; set; } + public string Subject { get; set; } + public string Body { get; set; } + } } ```` Then create a background job class that uses an `EmailSendingArgs` object to send an email: ````csharp +using System.Threading.Tasks; using Volo.Abp.BackgroundJobs; +using Volo.Abp.DependencyInjection; using Volo.Abp.Emailing; namespace MyProject { - public class EmailSendingJob : BackgroundJob, ITransientDependency + public class EmailSendingJob + : AsyncBackgroundJob, ITransientDependency { private readonly IEmailSender _emailSender; @@ -49,9 +55,9 @@ namespace MyProject _emailSender = emailSender; } - public override void Execute(EmailSendingArgs args) + public override async Task ExecuteAsync(EmailSendingArgs args) { - _emailSender.Send( + await _emailSender.SendAsync( args.EmailAddress, args.Subject, args.Body @@ -63,10 +69,35 @@ namespace MyProject This job simply uses `IEmailSender` to send emails (see [email sending document](Emailing.md)). +> `AsyncBackgroundJob` is used to create a job needs to perform async calls. You can inherit from `BackgroundJob` and override the `Execute` method if the method doesn't need to perform any async call. + #### Exception Handling A background job should not hide exceptions. If it throws an exception, the background job is automatically re-tried after a calculated waiting time. Hide exceptions only if you don't want to re-run the background job for the current argument. +#### Job Name + +Each background job has a name. Job names are used in several places. For example, RabbitMQ provider uses job names to determine the RabbitMQ Queue names. + +Job name is determined by the **job argument type**. For the `EmailSendingArgs` example above, the job name is `MyProject.EmailSendingArgs` (full name, including the namespace). You can use the `BackgroundJobName` attribute to set a different job name. + +**Example** + +```csharp +using Volo.Abp.BackgroundJobs; + +namespace MyProject +{ + [BackgroundJobName("emails")] + public class EmailSendingArgs + { + public string EmailAddress { get; set; } + public string Subject { get; set; } + public string Body { get; set; } + } +} +``` + ### Queue a Job Item Now, you can queue an email sending job using the `IBackgroundJobManager` service: diff --git a/docs/en/Background-Workers-Quartz.md b/docs/en/Background-Workers-Quartz.md index e1d8287019..ce82222c14 100644 --- a/docs/en/Background-Workers-Quartz.md +++ b/docs/en/Background-Workers-Quartz.md @@ -37,7 +37,7 @@ public class YourModule : AbpModule ```` > Quartz background worker integration provided `QuartzPeriodicBackgroundWorkerAdapter` to adapt `PeriodicBackgroundWorkerBase` and `AsyncPeriodicBackgroundWorkerBase` derived class. So, you can still fllow the [background workers document](Background-Workers.md) to define the background worker. -> `BackgroundJobWorker` checks todo jobs every 5 seconds, but quartz will not block when long time jobs are executing. So,after Added Quartz background worker integration, you also need to add [Quartz Background Jobs](Background-Jobs-Quartz.md) or [Hangfire Background Jobs](Background-Jobs-Hangfire.md) to avoid duplicate execution jobs. +> `BackgroundJobWorker` checks jobs every 5 seconds, but quartz will not block when long time jobs are executing. So,after Added Quartz background worker integration, you also need to add [Quartz Background Jobs](Background-Jobs-Quartz.md) or [Hangfire Background Jobs](Background-Jobs-Hangfire.md) to avoid duplicate execution jobs. ## Configuration diff --git a/docs/en/Background-Workers.md b/docs/en/Background-Workers.md index c8a617efec..2e1b9d2a90 100644 --- a/docs/en/Background-Workers.md +++ b/docs/en/Background-Workers.md @@ -54,7 +54,7 @@ public class PassiveUserCheckerWorker : AsyncPeriodicBackgroundWorkerBase Timer.Period = 600000; //10 minutes } - protected override async Task DoWorkAsync( + protected async override Task DoWorkAsync( PeriodicBackgroundWorkerContext workerContext) { Logger.LogInformation("Starting: Setting status of inactive users..."); diff --git a/docs/en/Best-Practices/Application-Services.md b/docs/en/Best-Practices/Application-Services.md index 3332ce08ea..ff8afe81d2 100644 --- a/docs/en/Best-Practices/Application-Services.md +++ b/docs/en/Best-Practices/Application-Services.md @@ -213,6 +213,11 @@ This method votes a question and returns the current score of the question. * **Do** always get all the related entities from repositories to perform the operations on them. * **Do** call repository's Update/UpdateAsync method after updating an entity. Because, not all database APIs support change tracking & auto update. +#### Handle files + +* **Do not** use any web components like `IFormFile` or `Stream` in the application services. If you want to serve a file you can use `byte[]`. +* **Do** use a `Controller` to handle file uploading then pass the `byte[]` of the file to the application service method. + #### Using Other Application Services * **Do not** use other application services of the same module/application. Instead; diff --git a/docs/en/Blob-Storing.md b/docs/en/Blob-Storing.md index f477e6178a..63281a5ee6 100644 --- a/docs/en/Blob-Storing.md +++ b/docs/en/Blob-Storing.md @@ -21,7 +21,7 @@ The ABP Framework has already the following storage provider implementations; * [Azure](Blob-Storing-Azure.md): Stores BLOBs on the [Azure BLOB storage](https://azure.microsoft.com/en-us/services/storage/blobs/). * [Aliyun](Blob-Storing-Aliyun.md): Stores BLOBs on the [Aliyun Storage Service](https://help.aliyun.com/product/31815.html). * [Minio](Blob-Storing-Minio.md): Stores BLOBs on the [MinIO Object storage](https://min.io/). -* [Aws](Blob-Storing-Aws.md): Stores BLOBs on the[Amazon Simple Storage Service](https://min.io/). +* [Aws](Blob-Storing-Aws.md): Stores BLOBs on the[Amazon Simple Storage Service](https://aws.amazon.com/s3/). More providers will be implemented by the time. You can [request](https://github.com/abpframework/abp/issues/new) it for your favorite provider or [create it yourself](Blob-Storing-Custom-Provider.md) and [contribute](Contribution/Index.md) to the ABP Framework. diff --git a/docs/en/Blog-Posts/2020-05-08 v2_7_Release/Post.md b/docs/en/Blog-Posts/2020-05-08 v2_7_Release/Post.md index b6c1d3f952..c09b0eb75c 100644 --- a/docs/en/Blog-Posts/2020-05-08 v2_7_Release/Post.md +++ b/docs/en/Blog-Posts/2020-05-08 v2_7_Release/Post.md @@ -16,7 +16,7 @@ ABP.IO Platform is rapidly growing and we are getting more and more contribution ### Object Extending System -In the last few releases, we've mostly focused on providing ways to extend existing modules when you use them as NuGet/NPM Packages. +In the last few releases, we've mostly focused on providing ways to extend existing modules when you use them as NuGet/NPM Packages. The Object Extending System allows module developers to create extensible modules and allows application developers to customize and extend a module easily. @@ -43,7 +43,7 @@ ObjectExtensionManager.Instance options.Attributes.Add(new RequiredAttribute()); options.Attributes.Add( new StringLengthAttribute(32) { - MinimumLength = 6 + MinimumLength = 6 } ); }); @@ -121,7 +121,7 @@ Just create a class derived from the `ExceptionSubscriber` class in your applica ````csharp public class MyExceptionSubscriber : ExceptionSubscriber { - public override async Task HandleAsync(ExceptionNotificationContext context) + public async override Task HandleAsync(ExceptionNotificationContext context) { //TODO... } @@ -244,4 +244,4 @@ We ([Volosoft](https://volosoft.com/) - the core team behind the ABP.IO platform [ABP Framework](https://abp.io/) provides all the infrastructure and application independent framework features to make you more productive, focus on your own business code and implement software development best practices. It provides you a well defined and comfortable development experience without repeating yourself. -[ABP Commercial](https://commercial.abp.io/) provides pre-built functionalities, themes and tooling to save your time if your requirements involve these functionalities in addition to the premium support for the framework and the pre-built modules. \ No newline at end of file +[ABP Commercial](https://commercial.abp.io/) provides pre-built functionalities, themes and tooling to save your time if your requirements involve these functionalities in addition to the premium support for the framework and the pre-built modules. diff --git a/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/POST.md b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/POST.md new file mode 100644 index 0000000000..4e19a294c1 --- /dev/null +++ b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/POST.md @@ -0,0 +1,271 @@ +# ABP Framework 3.3 RC Has Been Published + +We have released the [ABP Framework](https://abp.io/) (and the [ABP Commercial](https://commercial.abp.io/)) `3.3.0-rc.1` today. This blog post introduces the new features and important changes in the new version. + +## Get Started with the 3.3 RC.1 + +If you want to try the version `3.3.0-rc.1` today, follow the steps below; + +1) **Upgrade** the ABP CLI to the version `3.3.0-rc.1` using a command line terminal: + +````bash +dotnet tool update Volo.Abp.Cli -g --version 3.3.0-rc.1 +```` + +**or install** if you haven't installed before: + +````bash +dotnet tool install Volo.Abp.Cli -g --version 3.3.0-rc.1 +```` + +2) Create a **new application** with the `--preview` option: + +````bash +abp new BookStore --preview +```` + +See the [ABP CLI documentation](https://docs.abp.io/en/abp/3.3/CLI) for all the available options. + +> You can also use the *Direct Download* tab on the [Get Started](https://abp.io/get-started) page by selecting the Preview checkbox. + +## What's new with the ABP Framework 3.3 + +### The Blazor UI + +We had released an experimental early preview version of the Blazor UI with the [previous version](https://blog.abp.io/abp/ABP-Framework-ABP-Commercial-3.2-RC-With-The-New-Blazor-UI). In this version, we've completed most of the fundamental infrastructure features and the application modules (like identity and tenant management). + +It currently has almost the same functionalities as the other UI types (Angular & MVC / Razor Pages). + +**Example screenshot**: User management page of the Blazor UI + +![abp-blazor-ui](abp-blazor-ui.png) + +> We've adapted the [Lepton Theme](https://commercial.abp.io/themes) for the ABP Commercial, see the related section below. + +We are still working on the fundamentals. So, the next version may introduce breaking changes of the Blazor UI. We will work hard to keep them with the minimal effect on your application code. + +#### Breaking Changes on the Blazor UI + +There are some breaking changes with the Blazor UI. If you've built an application and upgrade it, your application might not properly work. See [the migration guide](https://docs.abp.io/en/abp/3.3/Migration-Guides/BlazorUI-3_3) for the changes you need to do after upgrading your application. + +### Automatic Validation for AntiForgery Token for HTTP APIs + +Starting with the version 3.3, all your HTTP API endpoints are **automatically protected** against CSRF attacks, unless you disable it for your application. So, no configuration needed, just upgrade the ABP Framework. + +[See the documentation](https://docs.abp.io/en/abp/3.3/CSRF-Anti-Forgery) to if you want to understand why you need it and how ABP Framework solves the problem. + +### Rebus Integration Package for the Distributed Event Bus + +[Rebus](https://github.com/rebus-org/Rebus) describes itself as "Simple and lean service bus implementation for .NET". There are a lot of integration packages like RabbitMQ and Azure Service Bus for the Rebus. The new [Volo.Abp.EventBus.Rebus](https://www.nuget.org/packages/Volo.Abp.EventBus.Rebus) package allows you to use the Rebus as the [distributed event bus](https://docs.abp.io/en/abp/latest/Distributed-Event-Bus) for the ABP Framework. + +See [the documentation](https://docs.abp.io/en/abp/3.3/Distributed-Event-Bus-Rebus-Integration) to learn how to use Rebus with the ABP Framework. + +### Async Repository LINQ Extension Methods + +You have a problem when you want to use **Async LINQ Extension Methods** (e.g. `FirstOrDefaultAsync(...)`) in your **domain** and **application** layers. These async methods are **not included in the standard LINQ extension methods**. Those are defined by the [Microsoft.EntityFrameworkCore](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore) NuGet package (see [the code](https://github.com/dotnet/efcore/blob/main/src/EFCore/Extensions/EntityFrameworkQueryableExtensions.cs)). To be able to use these `async` methods, you need to reference to the `Microsoft.EntityFrameworkCore` package. + +If you don't want to depend on the EF Core in your business layer, then ABP Framework provides the `IAsyncQueryableExecuter` service to execute your queries asynchronously without depending on the EF Core package. You can see [the documentation](https://docs.abp.io/en/abp/latest/Repositories#option-3-iasyncqueryableexecuter) to get more information about this service. + +ABP Framework version 3.3 takes this one step further and allows you to directly execute the async LINQ extension methods on the `IRepository` interface. + +**Example: Use `CountAsync` and `FirstOrDefaultAsync` methods on the repositories** + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; +using Volo.Abp.Domain.Repositories; + +namespace MyCompanyName.MyProjectName +{ + public class BookAppService : ApplicationService, IBookAppService + { + private readonly IRepository _bookRepository; + + public BookAppService(IRepository bookRepository) + { + _bookRepository = bookRepository; + } + + public async Task DemoAsync() + { + var countAll = await _bookRepository + .CountAsync(); + + var count = await _bookRepository + .CountAsync(x => x.Name.Contains("A")); + + var book1984 = await _bookRepository + .FirstOrDefaultAsync(x => x.Name == "1984"); + } + } +} +```` + +All the standard LINQ methods are supported: *AllAsync, AnyAsync, AverageAsync, ContainsAsync, CountAsync, FirstAsync, FirstOrDefaultAsync, LastAsync, LastOrDefaultAsync, LongCountAsync, MaxAsync, MinAsync, SingleAsync, SingleOrDefaultAsync, SumAsync, ToArrayAsync, ToListAsync*. + +This approach still has a limitation. You need to execute the extension method directly on the repository object. For example, the below usage is **not supported**: + +````csharp +var count = await _bookRepository.Where(x => x.Name.Contains("A")).CountAsync(); +```` + +This is because the object returned from the `Where` method is not a repository object, it is a standard `IQueryable`. In such cases, you can still use the `IAsyncQueryableExecuter`: + +````csharp +var count = await AsyncExecuter.CountAsync( + _bookRepository.Where(x => x.Name.Contains("A")) +); +```` + +`AsyncExecuter` has all the standard extension methods, so you don't have any restriction here. See [the repository documentation](https://docs.abp.io/en/abp/latest/Repositories#iqueryable-async-operations) for all the options you have. + +> ABP Framework does its best to not depend on the EF Core and still be able to use the async LINQ extension methods. However, there is no problem to depend on the EF Core for your application, you can add the `Microsoft.EntityFrameworkCore` NuGet package and use the native methods. + +### Stream Support for the Application Service Methods + +[Application services](https://docs.abp.io/en/abp/latest/Application-Services) are consumed by clients and the parameters and return values (typically [Data Transfer Objects](https://docs.abp.io/en/abp/latest/Data-Transfer-Objects)). In case of the client is a remote application, then these objects should be serialized & deserialized. + +Until the version 3.3, we hadn't suggest to use the `Stream` in the application service contracts, since it is not serializable/deserializable. However, with the version 3.3, ABP Framework properly supports this scenario by introducing the new `IRemoteStreamContent` interface. + +Example: An application service that can get or return streams + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; +using Volo.Abp.Content; + +namespace MyProject.Test +{ + public interface ITestAppService : IApplicationService + { + Task Upload(Guid id, IRemoteStreamContent streamContent); + Task Download(Guid id); + } +} +```` + +The implementation can be as shown below: + +````csharp +using System; +using System.IO; +using System.Threading.Tasks; +using Volo.Abp; +using Volo.Abp.Application.Services; +using Volo.Abp.Content; + +namespace MyProject.Test +{ + public class TestAppService : ApplicationService, ITestAppService + { + public Task Download(Guid id) + { + var fs = new FileStream("C:\\Temp\\" + id + ".blob", FileMode.OpenOrCreate); + return Task.FromResult( + (IRemoteStreamContent) new RemoteStreamContent(fs) { + ContentType = "application/octet-stream" + } + ); + } + + public async Task Upload(Guid id, IRemoteStreamContent streamContent) + { + using (var fs = new FileStream("C:\\Temp\\" + id + ".blob", FileMode.Create)) + { + await streamContent.GetStream().CopyToAsync(fs); + await fs.FlushAsync(); + } + } + } +} +```` + +> This is just a demo code. Do it better in your production code :) + +Thanks to [@alexandru-bagu](https://github.com/alexandru-bagu) for the great contribution! + +### Other Changes + +* Upgraded all the .NET Core / ASP.NET Core related packages to the version 3.1.8. If you have additional dependencies to the .NET Core / ASP.NET Core related packages, we suggest you to updates your packages to the version 3.1.8 to have the latest bug and security fixes published by Microsoft. +* The blogging module now uses the [BLOB Storing](https://docs.abp.io/en/abp/latest/Blob-Storing) system to store images & files of the blog posts. If you are using this module, then you need to manually migrate the local files to the BLOB Storing system after the upgrade. +* The Angular UI is now redirecting to the profile management page of the MVC UI instead of using its own UI, if you've configured the authorization code flow (which is default since the version 3.2.0). + +## What's new with the ABP Commercial 3.3 + +### The Blazor UI + +We have good news for the ABP Commercial Blazor UI too. We have implemented the [Lepton Theme](https://commercial.abp.io/themes) integration, so it is now available with the Blazor UI. Also, implemented most of the fundamental [modules](https://commercial.abp.io/modules). + +**A screenshot from the ABP Commercial startup template with the Blazor UI** + +![abp-commercial-blazor-ui](abp-commercial-blazor-ui.png) + +There are still missing features and modules. However, we are working on it to have a more complete version in the next release. + +#### Breaking Changes on the Blazor UI + +There are some breaking changes with the Blazor UI. If you've built an application and upgrade it, your application might not properly work. See the [ABP Commercial Blazor UI v 3.3 Migration Guide](https://docs.abp.io/en/commercial/3.3/migration-guides/blazor-ui-3_3) for the changes you need to do after upgrading your application. + +#### Known Issues + +When you create a new project, profile management doesn't work, you get an exception because it can't find the `/libs/cropperjs/css/cropper.min.css` file. To fix the issue; + +* Add `"@volo/account": "^3.3.0-rc.1"` to the `package.json` in the `.Host` project. +* Run `yarn` (or `npm install`), then `gulp` on a command line terminal in the root folder of the `.Host` project. + +### Multi-Tenant Social Logins + +[Account module](https://commercial.abp.io/modules/Volo.Account.Pro) now supports to manage the social/external logins in the UI. You can **enable/disable** and **set options** in the settings page. It also supports to use **different credentials for the tenants** and it is also **configured on the runtime**. + +![abp-commercial-setting-account-external-logins](abp-commercial-setting-account-external-logins.png) + +### Linked Accounts + +Linked user system allows you to link other accounts (including account in a different tenant) with your account, so you can switch between different accounts with a single-click. It is practical since you no longer need to logout and login again with entering the credentials of the target account. + +To manage the linked accounts, go to the profile management page from the user menu; + +![abp-commercial-linked-users](abp-commercial-linked-users.png) + +### Paypal & Stripe Integrations + +The [Payment Module](https://commercial.abp.io/modules/Volo.Payment) was supporting PayU and 2Checkout providers until the version 3.3. It's now integrated to PayPal and Stripe. See the [technical documentation](https://docs.abp.io/en/commercial/latest/modules/payment) to learn how to use it. + +### ABP Suite Improvements + +We've done a lot of small improvements for the [ABP Suite](https://commercial.abp.io/tools/suite). Some of the enhancements are; + +* Show the previously installed modules as *installed* on the module list. +* Switch between the latest stable, the latest [preview](https://docs.abp.io/en/abp/latest/Previews) and the latest [nightly build](https://docs.abp.io/en/abp/latest/Nightly-Builds) versions of the ABP related packages. +* Moved the file that stores the *previously created entities* into the solution folder to allow you to store it in your source control system. + +### Others + +* Added an option to the Account Module to show reCAPTCHA on the login & the registration forms. + +Besides the new features introduced in this post, we've done a lot of small other enhancements and bug fixes to provide a better development experience and increase the developer productivity. + +## New Articles + +The core ABP Framework team & the community continue to publish new articles on the [ABP Community](https://community.abp.io/) web site. The recently published articles are; + +* [Replacing Email Templates and Sending Emails](https://community.abp.io/articles/replacing-email-templates-and-sending-emails-jkeb8zzh) (by [@EngincanV](https://community.abp.io/members/EngincanV)) +* [How to Add Custom Properties to the User Entity](https://community.abp.io/articles/how-to-add-custom-property-to-the-user-entity-6ggxiddr) (by [@berkansasmaz](https://community.abp.io/members/berkansasmaz)) +* [Using the AdminLTE Theme with the ABP Framework MVC / Razor Pages UI](https://community.abp.io/articles/using-the-adminlte-theme-with-the-abp-framework-mvc-razor-pages-ui-gssbhb7m) (by [@mucahiddanis](https://community.abp.io/members/mucahiddanis)) +* [Using DevExtreme Angular Components With the ABP Framework](https://community.abp.io/articles/using-devextreme-angular-components-with-the-abp-framework-x5nyvj3i) (by [@bunyamin](https://community.abp.io/members/bunyamin)) + +It is appreciated if you want to [submit an article](https://community.abp.io/articles/submit) related to the ABP Framework. + +## About the Next Release + +The next version will be `4.0.0`. We are releasing a major version, since we will move the ABP Framework to .NET 5.0. We see that for most of the applications this will not be a breaking change and we hope you easily upgrade to it. + +The planned 4.0.0-rc.1 (Release Candidate) version date is **November 11**, just after the Microsoft releases the .NET 5.0 final. The planned 4.0.0 final release date is **November 26**. + +Follow the [GitHub milestones](https://github.com/abpframework/abp/milestones) for all the planned ABP Framework version release dates. + +## Feedback + +Please check out the ABP Framework 3.3.0 RC and [provide feedback](https://github.com/abpframework/abp/issues/new) to help us to release a more stable version. The planned release date for the [3.3.0 final](https://github.com/abpframework/abp/milestone/44) version is October 27th. diff --git a/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-blazor-ui.png b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-blazor-ui.png new file mode 100644 index 0000000000..ea61f2a488 Binary files /dev/null and b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-blazor-ui.png differ diff --git a/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-blazor-ui.png b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-blazor-ui.png new file mode 100644 index 0000000000..8da48af76e Binary files /dev/null and b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-blazor-ui.png differ diff --git a/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-linked-users.png b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-linked-users.png new file mode 100644 index 0000000000..ef957aecd5 Binary files /dev/null and b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-linked-users.png differ diff --git a/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-setting-account-external-logins.png b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-setting-account-external-logins.png new file mode 100644 index 0000000000..8be08af686 Binary files /dev/null and b/docs/en/Blog-Posts/2020-10-15 v3_3_Preview/abp-commercial-setting-account-external-logins.png differ diff --git a/docs/en/Blog-Posts/2020-10-27 v3_3_Release_Stable/POST.md b/docs/en/Blog-Posts/2020-10-27 v3_3_Release_Stable/POST.md new file mode 100644 index 0000000000..4f7507cbfd --- /dev/null +++ b/docs/en/Blog-Posts/2020-10-27 v3_3_Release_Stable/POST.md @@ -0,0 +1,47 @@ +# ABP Framework & ABP Commercial 3.3 Final Have Been Released + +ABP Framework & ABP Commercial 3.3.0 have been released today. + +Since all the new features are already explained in details with the [3.3 RC Announcement Post](https://blog.abp.io/abp/ABP-Framework-ABP-Commercial-v3.3-RC-Have-Been-Released), I will not repeat all the details again. Please read [the RC post](https://blog.abp.io/abp/ABP-Framework-ABP-Commercial-v3.3-RC-Have-Been-Released) for **new feature and changes** you may need to do for your solution while upgrading to the version 3.3. + +## Creating New Solutions + +You can create a new solution with the ABP Framework version 3.3 by either using the `abp new` command or using the **direct download** tab on the [get started page](https://abp.io/get-started). + +> See the [getting started document](https://docs.abp.io/en/abp/latest/Getting-Started) for details. + +## How to Upgrade an Existing Solution + +### Install/Update the ABP CLI + +First of all, install the ABP CLI or upgrade to the latest version. + +If you haven't installed yet: + +````bash +dotnet tool install -g Volo.Abp.Cli +```` + +To update an existing installation: + +```bash +dotnet tool update -g Volo.Abp.Cli +``` + +### ABP UPDATE Command + +[ABP CLI](https://docs.abp.io/en/abp/latest/CLI) provides a handy command to update all the ABP related NuGet and NPM packages in your solution with a single command: + +````bash +abp update +```` + +Run this command in the root folder of your solution. After the update command, check [the RC blog post](https://blog.abp.io/abp/ABP-Framework-ABP-Commercial-v3.3-RC-Have-Been-Released) to learn if you need to make any changes in your solution. + +> You may want to see the new [upgrading document](https://docs.abp.io/en/abp/latest/Upgrading). + +## About the Next Version: 4.0 + +The next version will be 4.0 and it will be mostly related to completing the Blazor UI features and upgrading the ABP Framework & ecosystem to the .NET 5.0. + +The goal is to complete the version 4.0 with a stable Blazor UI with the fundamental features implemented and publish it just after the Microsoft lunches .NET 5 in this November. The planned 4.0 preview release date is November 11th. \ No newline at end of file diff --git a/docs/en/Blog-Posts/2020-11-12 v4_0_Preview/POST.md b/docs/en/Blog-Posts/2020-11-12 v4_0_Preview/POST.md new file mode 100644 index 0000000000..03e3d31f97 --- /dev/null +++ b/docs/en/Blog-Posts/2020-11-12 v4_0_Preview/POST.md @@ -0,0 +1,143 @@ +# ABP Framework 4.0 RC Has Been Published based on .NET 5.0! + +Today, we have released the [ABP Framework](https://abp.io/) (and the [ABP Commercial](https://commercial.abp.io/)) 4.0.0 RC that is based on the **.NET 5.0**. This blog post introduces the new features and important changes in the new version. + +> **The planned release date for the [4.0.0 final](https://github.com/abpframework/abp/milestone/45) version is November 26, 2020**. + +## Get Started with the 4.0 RC + +If you want to try the version `4.0.0` today, follow the steps below; + +1) **Upgrade** the ABP CLI to the version `4.0.0-rc.3` using a command line terminal: + +````bash +dotnet tool update Volo.Abp.Cli -g --version 4.0.0-rc.3 +```` + +**or install** if you haven't installed before: + +````bash +dotnet tool install Volo.Abp.Cli -g --version 4.0.0-rc.3 +```` + +2) Create a **new application** with the `--preview` option: + +````bash +abp new BookStore --preview +```` + +See the [ABP CLI documentation](https://docs.abp.io/en/abp/3.3/CLI) for all the available options. + +> You can also use the *Direct Download* tab on the [Get Started](https://abp.io/get-started) page by selecting the **Preview checkbox**. + +## Migrating From 3.x to 4.0 + +The version 4.0 comes with some major changes including the **migration from .NET Core 3.1 to .NET 5.0**. + +We've prepared a **detailed [migration document](https://docs.abp.io/en/abp/4.0/Migration-Guides/Abp-4_0)** to explain all the changes and the actions you need to take while upgrading your existing solutions. + +## What's new with the ABP Framework 4.0 + +### The Blazor UI + +The Blazor UI is now stable and officially supported. The [web application development tutorial](https://docs.abp.io/en/abp/4.0/Tutorials/Part-1?UI=Blazor) has been updated based on the version 4.0. + +#### abp bundle command + +Introducing the `abp bundle` CLI command to manage static JavaScript & CSS file dependencies of a Blazor application. This command is currently used to add the dependencies to the `index.html` file in the dependency order by respecting to modularity. In the next version it will automatically unify & minify the files. The documentation is being prepared. + +#### Removed the JQuery & Bootstrap JavaScript + +Removed JQuery & Bootstrap JavaScript dependencies for the Blazor UI. + +>There are some other changes in the startup template and some public APIs. Follow the [Migration Guide](https://docs.abp.io/en/abp/4.0/Migration-Guides/Abp-4_0) to apply changes for existing solutions that you're upgrading from the version 3.3. While we will continue to make improvements add new features, we no longer make breaking changes on the existing APIs until the version 5.0. + +#### Others + +A lot of minor and major improvements have been done for the Blazor UI. Some of them are listed below: + +* Implemented `IComponentActivator` to resolve the component from the `IServiceProvider`. So, you can now inject dependencies into the constructor of your razor component. +* Introduced the `AbpComponentBase` base class that you derive your components from. It has useful base properties that you can use in your pages/components. +* Introduced `IUiNotificationService` service to show toast notifications on the UI. +* Improved the `IUiMessageService` to show message & confirmation dialogs. + +### System.Text.Json + +ABP Framework 4.0 uses the System.Text.Json by default as the JSON serialization library. It, actually, using a hybrid approach: Continues to use the Newtonsoft.Json when it needs to use the features not supported by the System.Text.Json. + +Follow the [Migration Guide](https://docs.abp.io/en/abp/4.0/Migration-Guides/Abp-4_0) to learn how to configure to use the Newtonsoft.Json for some specific types or switch back to the Newtonsoft.Json as the default JSON serializer. + +### Identity Server 4 Upgrade + +ABP Framework upgrades the [IdentityServer4](https://www.nuget.org/packages/IdentityServer4) library from 3.x to 4.1.1 with the ABP Framework version 4.0. IdentityServer 4.x has a lot of changes. Some of them are **breaking changes in the data structure**. + +Follow the [Migration Guide](https://docs.abp.io/en/abp/4.0/Migration-Guides/Abp-4_0) to upgrade existing solutions. + +### Creating a New Module Inside the Application + +ABP CLI has now a command to create a new module and add it to an existing solution. In this way, you can create modular applications easier than before. + +Example: Create a *ProductManagement* module into your solution. + +````bash +abp add-module ProductManagement --new --add-to-solution-file +```` + +Execute this command in a terminal in the root folder of your solution. If you don't specify the `--add-to-solution-file` option, then the module projects will not be added to the main solution, but the project references still be added. In this case, you need to open the module's solution to develop the module. + +See the [CLI document](https://docs.abp.io/en/abp/4.0/CLI) for other options. + +### WPF Startup Template + +Introducing the WPF startup template for the ABP Framework. Use the ABP CLI new command to create a new WPF application: + +````bash +abp new MyWpfApp -t wpf +```` + +This is a minimalist, empty project template that is integrated to the ABP Framework. + +### New Languages + +**Thanks to the contributors** from the ABP Community, the framework modules and the startup template have been localized to **German** language by [Alexander Pilhar](https://github.com/alexanderpilhar) & [Nico Lachmuth](https://github.com/tntwist). + +### Other Notes + +* Upgraded to Angular 11. +* Since [Mongo2Go](https://github.com/Mongo2Go/Mongo2Go) library not supports transactions, you can use transactions in unit tests for MongoDB. + +## What's new with the ABP Commercial 4.0 + +### The Blazor UI + +The Blazor UI for the ABP Commercial is also becomes stable and feature rich with the version 4.0; + +* [ABP Suite](https://commercial.abp.io/tools/suite) now supports to generate CRUD pages for the Blazor UI. +* Completed the [Lepton Theme](https://commercial.abp.io/themes) for the Blazor UI. +* Implemented the [File Management](https://commercial.abp.io/modules/Volo.FileManagement) module for the Blazor UI. + +### The ABP Suite + +While creating create/edit modals with a navigation property, we had two options: A dropdown to select the target entity and a modal to select the entity by searching with a data table. + +Dropdown option now supports **lazy load, search and auto-complete**. In this way, selecting a navigation property becomes much easier and supports large data sets on the dropdown. + +**Example: Select an author while creating a new book** + +![abp-suite-auto-complete-dropdown](abp-suite-auto-complete-dropdown.png) + +With the new version, you can **disable backend code generation** on CRUD page generation. This is especially useful if you want to regenerate the page with a different UI framework, but don't want to regenerate the server side code. + +### Identity Server Management UI Revised + +Completely revised the Identity Server Management UI based on the IDS 4.x changes. + +## About the Next Release + +The next feature version, `4.1.0`, will mostly focus on completing the missing documents, fixing bugs, performance optimizations and improving the Blazor UI features. The planned preview release date for the version `4.1.0` is December 10 and the final (stable) version release date is December 24. + +Follow the [GitHub milestones](https://github.com/abpframework/abp/milestones) for all the planned ABP Framework version release dates. + +## Feedback + +Please check out the ABP Framework 4.0.0 RC and [provide feedback](https://github.com/abpframework/abp/issues/new) to help us to release a more stable version. **The planned release date for the [4.0.0 final](https://github.com/abpframework/abp/milestone/45) version is November 26**. diff --git a/docs/en/Blog-Posts/2020-11-12 v4_0_Preview/abp-suite-auto-complete-dropdown.png b/docs/en/Blog-Posts/2020-11-12 v4_0_Preview/abp-suite-auto-complete-dropdown.png new file mode 100644 index 0000000000..2021ef42bd Binary files /dev/null and b/docs/en/Blog-Posts/2020-11-12 v4_0_Preview/abp-suite-auto-complete-dropdown.png differ diff --git a/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/POST.md b/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/POST.md new file mode 100644 index 0000000000..840b5585fd --- /dev/null +++ b/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/POST.md @@ -0,0 +1,87 @@ +# ABP.IO Platform 4.0 with .NET 5.0 in the 4th Year! + +Today, we are extremely happy to release ABP Framework 4.0 with **.NET 5.0 support**! + +## 4 Years of Work + +As a nice coincidence, today is the **4th year** since the first commit made in the [abp repository](https://github.com/abpframework/abp)! So, we can say "*Happy Birthday ABP Framework!*". + +![abp-contribution-graph-4-years](abp-contribution-graph-4-years.png) + +### Some Statistics + +ABP.IO Platform and the ABP Community is growing. Here, a summary of these 4 years. + +From GitHub, only from the main [abp repository](https://github.com/abpframework/abp); + +* **15,297 commits** done. +* **3,764 issues** are closed. +* **2,133 pull requests** are merged. +* **158 contributors**. +* **88 releases** published. +* **5.2K stars** on GitHub. + +From NuGet & NPM; + +* **220 NuGet** packages & **52 NPM** packages. +* **1,000,000 downloads** only for the core NuGet package. + +From Website; + +* **200,000 visitors**. +* **1,000,000+ sessions**. + +## What's New With 4.0? + +Since all the new features are already explained in details with the [4.0 RC Announcement Post](https://blog.abp.io/abp/ABP.IO-Platform-v4.0-RC-Has-Been-Released-based-on-.NET-5.0), I will not repeat all the details again. Please read [the RC post](https://blog.abp.io/abp/ABP.IO-Platform-v4.0-RC-Has-Been-Released-based-on-.NET-5.0) for **new feature and changes** you may need to do for your solution while upgrading to the version 4.0. + +Here, a brief list of major features and changes; + +* Migrated to **.NET 5.0**. +* Stable **Blazor** UI. +* Moved to **System.Text.Json**. +* Upgraded to **IdentityServer** version 4.0. +* **WPF** startup template. + +## Creating New Solutions + +You can create a new solution with the ABP Framework version 4.0 by either using the `abp new` command or using the **direct download** tab on the [get started page](https://abp.io/get-started). + +> See the [getting started document](https://docs.abp.io/en/abp/latest/Getting-Started) for details. + +## How to Upgrade an Existing Solution + +This is a **major version** and requires some **manual work**, especially related to **.NET 5.0** and **IdentityServer** 4.0 upgrades. + +* See the [MIGRATION GUIDE](https://docs.abp.io/en/abp/latest/Migration-Guides/Abp-4_0) that covers all the details about the upgrade progress. + +* You can also see the [upgrading document](https://docs.abp.io/en/abp/latest/Upgrading). + +## New Guides / Documents + +We are constantly improving the documentation. Our purpose is not only document the ABP Framework, but also write architectural and practical guides for developers. + +### Implementing Domain Driven Design + +[Implementing Domain Driven Design](https://docs.abp.io/en/abp/latest/Domain-Driven-Design-Implementation-Guide) is a practical guide for they want to implement the DDD principles in their solutions. While the implementation details rely on the ABP Framework infrastructure, core concepts, principles and patterns are applicable in any kind of solution, even if it is not a .NET solution. + +![ddd-implementation-guide-sample](ddd-implementation-guide-sample.png) + +### Testing + +The new [Testing document](https://docs.abp.io/en/abp/latest/Testing) discusses different kind of automated tests and explains how you can write tests for your ABP based solutions. + +### UI Documents + +We've created a lot of documents for the [MVC](https://docs.abp.io/en/abp/latest/UI/AspNetCore/Overall), [Blazor](https://docs.abp.io/en/abp/latest/UI/Blazor/Overall) and the [Angular](https://docs.abp.io/en/abp/latest/UI/Angular/Quick-Start) UI. + +## About the Next Version + +The next versions 4.1 will mostly focus on; + +* Improving current features. +* Complete module features for the Blazor UI. +* Improve developer experience and productivity. +* More documentation and examples. + +Planned preview date for the version **4.1 is December 17, 2020**. See the [Road Map](https://docs.abp.io/en/abp/latest/Road-Map) document and [GitHub Milestones](https://github.com/abpframework/abp/milestones) to learn what's planned for the next versions. We are trying to be clear about the coming features and the next release dates. \ No newline at end of file diff --git a/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/abp-contribution-graph-4-years.png b/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/abp-contribution-graph-4-years.png new file mode 100644 index 0000000000..cb778d8dfe Binary files /dev/null and b/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/abp-contribution-graph-4-years.png differ diff --git a/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/ddd-implementation-guide-sample.png b/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/ddd-implementation-guide-sample.png new file mode 100644 index 0000000000..3aab36e979 Binary files /dev/null and b/docs/en/Blog-Posts/2020-12-04 v4_0_Release_Stable/ddd-implementation-guide-sample.png differ diff --git a/docs/en/CLI.md b/docs/en/CLI.md index 8713bc9019..d51dd91b5d 100644 --- a/docs/en/CLI.md +++ b/docs/en/CLI.md @@ -41,6 +41,7 @@ Here, the list of all available commands before explaining their details: * **`login`**: Authenticates on your computer with your [abp.io](https://abp.io/) username and password. * **`logout`**: Logouts from your computer if you've authenticated before. * **`build`**: Builds a GIT repository and depending repositories or a single .NET solution. +* **`bundle`**: Generates script and style references for an ABP Blazor project. ### help @@ -106,6 +107,7 @@ abp new Acme.BookStore * `--create-solution-folder` or `-csf`: Specifies if the project will be in a new folder in the output folder or directly the output folder. * `--connection-string` or `-cs`: Overwrites the default connection strings in all `appsettings.json` files. The default connection string is `Server=localhost;Database=MyProjectName;Trusted_Connection=True;MultipleActiveResultSets=true` for EF Core and it is configured to use the SQL Server. If you want to use the EF Core, but need to change the DBMS, you can change it as [described here](Entity-Framework-Core-Other-DBMS.md) (after creating the solution). * `--local-framework-ref --abp-path`: Uses local projects references to the ABP framework instead of using the NuGet packages. This can be useful if you download the ABP Framework source code and have a local reference to the framework from your application. +* `--no-random-port`: Uses template's default ports. ### update @@ -159,6 +161,8 @@ abp add-package Volo.Abp.MongoDB Adds a [multi-package application module](Modules/Index) to a solution by finding all packages of the module, finding related projects in the solution and adding each package to the corresponding project in the solution. +It can also create a new module for your solution and add it to your solution. See `--new-template` option. + > A business module generally consists of several packages (because of layering, different database provider options or other reasons). Using `add-module` command dramatically simplifies adding a module to a solution. However, each module may require some additional configurations which is generally indicated in the documentation of the related module. Usage @@ -167,21 +171,29 @@ Usage abp add-module [options] ```` -Example: +Examples: ```bash abp add-module Volo.Blogging ``` -* This example add the Volo.Blogging module to the solution. +* This example adds the `Volo.Blogging` module to the solution. + +```bash +abp add-module ProductManagement --new --add-to-solution-file +``` + +* This command creates a fresh new module customized for your solution (named `ProductManagement`) and adds it to your solution. + #### Options * `--solution` or `-s`: Specifies the solution (.sln) file path. If not specified, CLI tries to find a .sln file in the current directory. * `--skip-db-migrations`: For EF Core database provider, it automatically adds a new code first migration (`Add-Migration`) and updates the database (`Update-Database`) if necessary. Specify this option to skip this operation. * `-sp` or `--startup-project`: Relative path to the project folder of the startup project. Default value is the current folder. -* `--with-source-code`: Downloads the source code of the module to your solution folder and uses local project references instead of NuGet/NPM packages. -* `--add-to-solution-file`: Adds the downloaded module to your solution file, so you will also see the projects of the module when you open the solution on a IDE. (only available when `--with-source-code` is used.) +* `--new`: Creates a fresh new module (customized for your solution) and adds it to your solution. +* `--with-source-code`: Downloads the source code of the module to your solution folder and uses local project references instead of NuGet/NPM packages. This options is always `True` if `--new` is used. +* `--add-to-solution-file`: Adds the downloaded/created module to your solution file, so you will also see the projects of the module when you open the solution on a IDE. (only available when `--with-source-code` is `True`.) ### get-source @@ -383,10 +395,27 @@ abp build --build-name "prod" --dotnet-build-arguments "\"--no-dependencies\"" #### Options -* ```--working-directory``` or ```-w```: Specifies the working directory. This option is useful when the command is executed outside of a GIT repository or when executing directory doesn't contain a .NET solution file. +* ```--working-directory``` or ```-wd```: Specifies the working directory. This option is useful when the command is executed outside of a GIT repository or when executing directory doesn't contain a .NET solution file. * ```--build-name``` or ```-n```: Specifies a name for the build. This option is useful when same repository is used for more than one different builds. * ```--dotnet-build-arguments``` or ```-a```: Arguments to pass ```dotnet build``` when building project files. This parameter must be passed like ```"\"{params}\""``` . * ```--force``` or ```-f```: Forces to build projects even they are not changed from the last successful build. For more details, see [build command documentation](CLI-BuildCommand.md). + +#### bundle + +This command generates script and style references for an ABP Blazor project and updates the **index.html** file. It helps developers to manage dependencies required by ABP modules easily. In order ```bundle``` command to work, its **executing directory** or passed ```--working-directory``` parameter's directory must contain a Blazor project file(*.csproj). + +Usage: + +````bash +abp bundle [options] +```` + +#### Options + +* ```--working-directory``` or ```-wd```: Specifies the working directory. This option is useful when executing directory doesn't contain a Blazor project file. +* ```--force``` or ```-f```: Forces to build project before generating references. + +For more details about managing style and script references in Blazor apps, see [Managing Global Scripts & Styles](UI/Blazor/Global-Scripts-Styles.md) \ No newline at end of file diff --git a/docs/en/CSRF-Anti-Forgery.md b/docs/en/CSRF-Anti-Forgery.md new file mode 100644 index 0000000000..720edc5924 --- /dev/null +++ b/docs/en/CSRF-Anti-Forgery.md @@ -0,0 +1,147 @@ +# CSRF/XSRF & Anti Forgery System + +"*Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated*" ([OWASP](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet)). + +**ABP Framework completely automates CSRF preventing** and works out of the box without any configuration. Read this documentation only if you want to understand it better or need to customize. + +## The Problem + +ASP.NET Core [provides infrastructure](https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery) to prevent CSRF attacks by providing a system to **generate** and **validate antiforgery tokens**. However, the standard implementation has a few drawbacks; + +Antiforgery token validation is only **enabled for razor pages by default** and not enabled for **HTTP APIs**. You need to enable it yourself for the Controllers. You can use the `[ValidateAntiForgeryToken]` attribute for a specific API Controller/Action or the `[AutoValidateAntiforgeryToken]` attribute to prevent attacks globally. + +Once you enable it; + +* You need to manually add an HTTP header, named `RequestVerificationToken` to every **AJAX request** made in your application. You should care about obtaining the token, saving in the client side and adding to the HTTP header on every HTTP request. +* All your clients, including **non-browser clients**, should care about obtaining and sending the antiforgery token in every request. In fact, non-browser clients has no CSRF risk and should not care about this. + +Especially, the second point is a pain for your clients and unnecessarily consumes your server resources. + +> You can read more about the ASP.NET Core antiforgery system in its own [documentation](https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery). + +## The Solution + +ABP Framework provides `[AbpValidateAntiForgeryToken]` and `[AbpAutoValidateAntiforgeryToken]` attributes, just like the attributes explained above. `[AbpAutoValidateAntiforgeryToken]` is already added to the global filters, so you should do nothing to enable it for your application. + +ABP Framework also automates the following infrastructure; + +* Server side sets a **special cookie**, named `XSRF-TOKEN` by default, that is used make the antiforgery token value available to the browser. This is **done automatically** (by the [application configuration](API/Application-Configuration.md) endpoint). Nothing to do in the client side. +* In the client side, it reads the token from the cookie and sends it in the **HTTP header** (named `RequestVerificationToken` by default). This is implemented for all the supported UI types. +* Server side validates the antiforgery token **only for same and cross site requests** made by the browser. It bypasses the validation for non-browser clients. + +That's all. The systems works smoothly. + +## Configuration / Customization + +### AbpAntiForgeryOptions + +`AbpAntiForgeryOptions` is the main [options class](Options.md) to configure the ABP Antiforgery system. It has the following properties; + +* `TokenCookie`: Can be used to configure the cookie details. This cookie is used to store the antiforgery token value in the client side, so clients can read it and sends the value as the HTTP header. Default cookie name is `XSRF-TOKEN`, expiration time is 10 years (yes, ten years! It should be a value longer than the authentication cookie max life time, for the security). +* `AuthCookieSchemaName`: The name of the authentication cookie used by your application. Default value is `Identity.Application` (which becomes `AspNetCore.Identity.Application` on runtime). The default value properly works with the ABP startup templates. **If you change the authentication cookie name, you also must change this.** +* `AutoValidate`: The single point to enable/disable the ABP automatic antiforgery validation system. Default value is `true`. +* `AutoValidateFilter`: A predicate that gets a type and returns a boolean. ABP uses this predicate to check a controller type. If it returns false for a controller type, the controller is excluded from the automatic antiforgery token validation. +* `AutoValidateIgnoredHttpMethods`: A list of HTTP Methods to ignore on automatic antiforgery validation. Default value: "GET", "HEAD", "TRACE", "OPTIONS". These HTTP Methods are safe to skip antiforgery validation since they don't change the application state. + +If you need to change these options, do it in the `ConfigureServices` method of your [module](Module-Development-Basics.md). + +**Example: Configuring the AbpAntiForgeryOptions** + +```csharp +Configure(options => +{ + options.TokenCookie.Expiration = TimeSpan.FromDays(365); + options.AutoValidateIgnoredHttpMethods.Remove("GET"); + options.AutoValidateFilter = + type => !type.Namespace.StartsWith("MyProject.MyIgnoredNamespace"); +}); +``` + +This configuration; + +* Sets the antiforgery token expiration time to ~1 year. +* Enables antiforgery token validation for GET requests too. +* Ignores the controller types in the specified namespace. + +### AntiforgeryOptions + +`AntiforgeryOptions` is the standard [options class](Options.md) of the ASP.NET Core. **You can find all the information about this class in its [own documentation](https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery)**. + +`HeaderName` option is especially important for the ABP Framework point of view. Default value of this value is `RequestVerificationToken` and the clients uses this name while sending the token value in the header. So, if you change this option, you should also arrange your clients to align the change. If you don't have a good reason, leave it as default. + +### AbpValidateAntiForgeryToken Attribute + +If you disable the automatic validation or want to perform the validation for an endpoint that is not validated by default (for example, an endpoint with HTTP GET Method), you can use the `[AbpValidateAntiForgeryToken]` attribute for a **controller type or method** (action). + +**Example: Add `[AbpValidateAntiForgeryToken]` to a HTTP GET method** + +```csharp +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Volo.Abp.AspNetCore.Mvc; +using Volo.Abp.AspNetCore.Mvc.AntiForgery; + +namespace MyCompanyName.MyProjectName.Controllers +{ + [Route("api/products")] + public class ProductController : AbpController + { + [HttpGet] + [AbpValidateAntiForgeryToken] + public async Task GetAsync() + { + //TODO: ... + } + } +} +``` + +### Angular UI + +Angular supports CSRF Token out of box, but the token header name is `X-XSRF-TOKEN`. Since ABP Framework follows the ASP.NET Core conventions, it changes this value to `RequestVerificationToken` in the core package. + +You don't need to make anything unless you need to change the `AntiforgeryOptions.HeaderName` as explained before. If you change it, remember to change the header name for the Angular application too. To do that, add an import declaration for the `HttpClientXsrfModule` into your root module. + +**Example: Change the header name to *MyCustomHeaderName*** + +```typescript +@NgModule({ + // ... + imports: [ + //... + HttpClientXsrfModule.withOptions({ + cookieName: 'XSRF-TOKEN', + headerName: 'MyCustomHeaderName' + }) + ], +}) +export class AppModule {} +``` + +**Note:** XSRF-TOKEN is only valid if both frontend application and APIs run on the same domain. Therefore, when you make a request, you should use a relative path. + +For example, let's say your APIs is hosted at `https://testdomain.com/ws` +and your angular application is hosted at `https://testdomain.com/admin` + +So if your API request should look like this `https://testdomain.com/ws/api/identity/users` + +your `environment.prod.ts` has to be as follows: + +```typescript +export const environment = { + production: true, + // .... + apis: { + default: { + url: '/ws', // <- just use the context root here + // ... + }, + }, +} as Config.Environment; +``` + +Let's talk about why. + +First, take a look at [Angular's code](https://github.com/angular/angular/blob/master/packages/common/http/src/xsrf.ts#L81) + +It does not intercept any request that starts with `http://` or `https://`. There is a good reason for that. Any cross-site request does not need this token for security. This verification is only valid if the request is made to the same domain from which the web page is served. So, simply put, if you serve everything from a single domain, you just use a relative path. \ No newline at end of file diff --git a/docs/en/Community-Articles/2020-04-19-Customize-the-SignIn-Manager/POST.md b/docs/en/Community-Articles/2020-04-19-Customize-the-SignIn-Manager/POST.md index d46049526d..1342407880 100644 --- a/docs/en/Community-Articles/2020-04-19-Customize-the-SignIn-Manager/POST.md +++ b/docs/en/Community-Articles/2020-04-19-Customize-the-SignIn-Manager/POST.md @@ -1,6 +1,6 @@ # How to Customize the SignIn Manager for ABP Applications -After creating a new application using the [application startup template](https://docs.abp.io/en/abp/latest/Startup-Templates/Application), you may want extend or change the default behavior of the SignIn Manager for your authentication and registration flow needs. ABP [Account Module](https://docs.abp.io/en/abp/latest/Modules/Account) uses the [Identity Management Module](https://docs.abp.io/en/abp/latest/Modules/Identity) for SignIn Manager and the [Identity Management Module](https://docs.abp.io/en/abp/latest/Modules/Identity) uses default [Microsoft Identity SignIn Manager](https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs) ([see here](https://github.com/abpframework/abp/blob/be32a55449e270d2d456df3dabdc91f3ffdd4fa9/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs#L17)). +After creating a new application using the [application startup template](https://docs.abp.io/en/abp/latest/Startup-Templates/Application), you may want extend or change the default behavior of the SignIn Manager for your authentication and registration flow needs. ABP [Account Module](https://docs.abp.io/en/abp/latest/Modules/Account) uses the [Identity Management Module](https://docs.abp.io/en/abp/latest/Modules/Identity) for SignIn Manager and the [Identity Management Module](https://docs.abp.io/en/abp/latest/Modules/Identity) uses default [Microsoft Identity SignIn Manager](https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs) ([see here](https://github.com/abpframework/abp/blob/be32a55449e270d2d456df3dabdc91f3ffdd4fa9/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs#L17)). To write your Custom SignIn Manager, you need to extend [Microsoft Identity SignIn Manager](https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs) class and register it to the DI container. @@ -27,7 +27,7 @@ public class CustomSignInManager : Microsoft.AspNetCore.Identity.SignInManager It is important to use **Volo.Abp.Identity.IdentityUser** type for SignInManager to inherit, not the AppUser of your application. +> It is important to use **Volo.Abp.Identity.IdentityUser** type for SignInManager to inherit, not the AppUser of your application. Afterwards you can override any of the SignIn Manager methods you need and add new methods and properties needed for your authentication or registration flow. @@ -38,7 +38,7 @@ In this case we'll be overriding the `GetExternalLoginInfoAsync` method which is A good way to override a method is copying its [source code](https://github.com/dotnet/aspnetcore/blob/c56aa320c32ee5429d60647782c91d53ac765865/src/Identity/Core/src/SignInManager.cs#L638-L674). In this case, we will be using a minorly modified version of the source code which explicitly shows the namespaces of the methods and properties to help better understanding of the concept. ````csharp -public override async Task GetExternalLoginInfoAsync(string expectedXsrf = null) +public async override Task GetExternalLoginInfoAsync(string expectedXsrf = null) { var auth = await Context.AuthenticateAsync(Microsoft.AspNetCore.Identity.IdentityConstants.ExternalScheme); var items = auth?.Properties?.Items; @@ -93,4 +93,4 @@ PreConfigure(identityBuilder => ## The Source Code -You can find the source code of the completed example [here](https://github.com/abpframework/abp-samples/tree/master/Authentication-Customization). \ No newline at end of file +You can find the source code of the completed example [here](https://github.com/abpframework/abp-samples/tree/master/Authentication-Customization). diff --git a/docs/en/Community-Articles/2020-08-07-Passwordless-Authentication/POST.md b/docs/en/Community-Articles/2020-08-07-Passwordless-Authentication/POST.md index b31ea023f2..9489c004bd 100644 --- a/docs/en/Community-Articles/2020-08-07-Passwordless-Authentication/POST.md +++ b/docs/en/Community-Articles/2020-08-07-Passwordless-Authentication/POST.md @@ -33,7 +33,7 @@ namespace PasswordlessAuthentication.Web } //We need to override this method as well. - public override async Task GetUserModifierAsync(string purpose, UserManager manager, TUser user) + public async override Task GetUserModifierAsync(string purpose, UserManager manager, TUser user) { var userId = await manager.GetUserIdAsync(user); @@ -105,7 +105,7 @@ namespace PasswordlessAuthentication.Web.Pages UserManager = userManager; _userRepository = userRepository; } - + public ActionResult OnGet() { if (!CurrentUser.IsAuthenticated) @@ -115,15 +115,15 @@ namespace PasswordlessAuthentication.Web.Pages return Page(); } - + //added for passwordless authentication public async Task OnPostGeneratePasswordlessTokenAsync() { var adminUser = await _userRepository.FindByNormalizedUserNameAsync("admin"); - + var token = await UserManager.GenerateUserTokenAsync(adminUser, "PasswordlessLoginProvider", "passwordless-auth"); - + PasswordlessLoginUrl = Url.Action("Login", "Passwordless", new {token = token, userId = adminUser.Id.ToString()}, Request.Scheme); @@ -238,7 +238,7 @@ namespace PasswordlessAuthentication.Web.Controllers return Redirect("/"); } - + private static IEnumerable CreateClaims(IUser user, IEnumerable roles) { var claims = new List @@ -272,4 +272,4 @@ That's all! We created a passwordless login with 7 steps. ## Source Code -The completed sample is available on [GitHub repository](https://github.com/abpframework/abp-samples/tree/master/PasswordlessAuthentication). \ No newline at end of file +The completed sample is available on [GitHub repository](https://github.com/abpframework/abp-samples/tree/master/PasswordlessAuthentication). diff --git a/docs/en/Community-Articles/2020-08-31-Adding-User-Navigation-In-Suite/POST.md b/docs/en/Community-Articles/2020-08-31-Adding-User-Navigation-In-Suite/POST.md index 7bfd20637f..3fd6b845a9 100644 --- a/docs/en/Community-Articles/2020-08-31-Adding-User-Navigation-In-Suite/POST.md +++ b/docs/en/Community-Articles/2020-08-31-Adding-User-Navigation-In-Suite/POST.md @@ -22,6 +22,8 @@ Then add a string property called `Title`, as an example property. ### Create AppUserDto +_Note that, creating `AppUserDto` is not necessary after ABP v4.X_ + ABP Suite needs a DTO for the target entity (user, in this case) in order to define a navigation property. To do this, create a new folder called "Users" in `*.Application.Contracts` then add a new class called `AppUserDto` inherited from `IdentityUserDto`. diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/POST.md b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/POST.md new file mode 100644 index 0000000000..049171731b --- /dev/null +++ b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/POST.md @@ -0,0 +1,477 @@ +# Replacing Email Templates and Sending Emails + +## Introduction + +Hi, in this step by step article, we will send an email by using standard email template and then we will replace the standard email template with our new created template, thanks to [Text Templating System](https://docs.abp.io/en/abp/latest/Text-Templating#replacing-the-existing-templates) and [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System). Let's start by explaining what these systems do. + +* ABP framework provides a strong and flexible [Text Templating System](https://docs.abp.io/en/abp/latest/Text-Templating). So, we can use the text templating system to create dynamic email contents on a template and a model. + +* In this article, we will use `StandardEmailTemplates.Message` as standard email template. Then we will create a new template and replace the standard email template with our new template by using [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System). + +* The `Virtual File System` makes it possible to manage files that do not physically exist on the file system. That means we can override `StandardEmailTemplates.Message` template by changing it's path with our new template's path. + +## Creating the Solution + +> ABP Framework offers startup templates to get into the business faster. + +In this article, I will create a new startup template and perform the operations on this template. But if you already have a project you don't need to create a new startup template, you can implement the following steps to your existing project. (These steps can be applied to any project. (MVC, Angular etc.)) + +> If you have already a project you can skip this section. + +Before starting to development, we will create a solution named `TemplateReplace` (or whatever you want). We can create a new startup template by using [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) : + +````bash +abp new TemplateReplace +```` + +Our project boilerplate will be ready after the download is finished. Then, open the solution in the Visual Studio (or your favorite IDE). + +Run the `TemplateReplace.DbMigrator` application as below to create the database and seed initial data (which creates the admin user, admin role, permissions etc.). + +![db-migrator-1](db-migrator-1.jpg) + +* Right click to `TemplateReplace.DbMigrator` and choose the `Debug`. + +![db-migrator-2](db-migrator-2.jpg) + +* After that, click the `Start new instance` option to start the database migrations. + +![db-migrator-3](db-migrator-3.jpg) + +Then we can run the `TemplateReplace.Web` project to see our application working. + +> _Default login credentials for admin: username is **admin** and password is **1q2w3E\***_ + +## Starting the Development + +First thing we need to do is, creating a email service to sending emails. ABP Framework provides `IEmailSender` service that is used to send emails. + +### Step - 1 + +Create an `Emailing` folder in the `TemplateReplace.Domain` project and add a class named `EmailService` inside of it. + +```csharp +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Emailing; +using Volo.Abp.Emailing.Templates; +using Volo.Abp.TextTemplating; + +namespace TemplateReplace.Emailing +{ + public class EmailService : ITransientDependency + { + private readonly IEmailSender _emailSender; + private readonly ITemplateRenderer _templateRenderer; + + public EmailService(IEmailSender emailSender, ITemplateRenderer templateRenderer) + { + _emailSender = emailSender; + _templateRenderer = templateRenderer; + } + + public async Task SendAsync(string targetEmail) + { + var emailBody = await _templateRenderer.RenderAsync( + StandardEmailTemplates.Message, + new + { + message = "ABP Framework provides IEmailSender service that is used to send emails." + } + ); + + await _emailSender.SendAsync( + targetEmail, + "Subject", + emailBody + ); + } + } +} +``` + +* To create an email content, we need to inject `ITemplateRenderer` and use the `RenderAsync` method to render a template. + +* We've used `StandardEmailTemplates.Message` as standart email template. This provides us a standard and simple message template to send mails. + +* The resulting email body should be like shown below: + +```html + + + + + + + ABP Framework provides IEmailSender service that is used to send emails. + + +``` + +### Step - 2 (Configuring Email Settings) + +* Now, we need to configure some email settings by following [settings documentation](https://docs.abp.io/en/abp/latest/Settings#setting-values-in-the-application-configuration). For achieve this, open the `appsettings.json` file under `TemplateReplace.Web` and configure your email settings in **settings** section like below. + +![appsettings.json](settings.jpg) + +* Here, I used Google's SMTP settings to send emails via Gmail. You can change these setting values by your need. + +> **Note:** If you want to use Google's SMTP server settings and send emails via Gmail, you should confirm [this](https://myaccount.google.com/u/0/lesssecureapps). + +### Step - 3 + +* After that we need to open `TemplateReplaceDomainModule.cs` file and change its contents as below to sending real-time emails. + +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using TemplateReplace.MultiTenancy; +using Volo.Abp.AuditLogging; +using Volo.Abp.BackgroundJobs; +using Volo.Abp.Emailing; +using Volo.Abp.FeatureManagement; +using Volo.Abp.Identity; +using Volo.Abp.IdentityServer; +using Volo.Abp.Modularity; +using Volo.Abp.MultiTenancy; +using Volo.Abp.PermissionManagement.Identity; +using Volo.Abp.PermissionManagement.IdentityServer; +using Volo.Abp.SettingManagement; +using Volo.Abp.TenantManagement; + +namespace TemplateReplace +{ + [DependsOn( + typeof(TemplateReplaceDomainSharedModule), + typeof(AbpAuditLoggingDomainModule), + typeof(AbpBackgroundJobsDomainModule), + typeof(AbpFeatureManagementDomainModule), + typeof(AbpIdentityDomainModule), + typeof(AbpPermissionManagementDomainIdentityModule), + typeof(AbpIdentityServerDomainModule), + typeof(AbpPermissionManagementDomainIdentityServerModule), + typeof(AbpSettingManagementDomainModule), + typeof(AbpTenantManagementDomainModule), + typeof(AbpEmailingModule) + )] + public class TemplateReplaceDomainModule : AbpModule + { + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + var settingManager = context.ServiceProvider.GetService(); + //encrypts the password on set and decrypts on get + settingManager.SetGlobalAsync(EmailSettingNames.Smtp.Password, "your_password"); + } + + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.IsEnabled = MultiTenancyConsts.IsEnabled; + }); + + // #if DEBUG + // context.Services.Replace(ServiceDescriptor.Singleton()); + // #endif + } + } +} + +``` + +* `NullEmailSender` is a built-in class that implements the `IEmailSender`, but writes email contents to the standard log system, rather than actually sending the emails. This class can be useful especially in development time where you generally don't want to send real emails. Therefore ABP framework defined this by default. But in our case we want to send real emails, so we must remove these lines or we must take it to the comment line. + +* `Abp.Mailing.Smtp.Password` must be an encrypted value. Therefore we used `SettingManager` in here to set the password. It internally **encrypts** the values on set and **decrypts** on get. + +* After all these steps, whenever we want to send an email, we can do it by using our `EmailService` class. We can inject this class and invoke the `SendAsync` method to sending email where its needed. + +After sending the email we should see the template like below. + +![email-message](message.jpg) + +### Step - 4 (Defining New Template) + +* So far we've sent mail by using standard email template of ABP. But we may want to replace the email template with the new one. We can achieve this by following the `Text Templating` [documentation](https://docs.abp.io/en/abp/latest/Text-Templating#replacing-the-existing-templates). + +* In this article, I will create a email template by using free template generator named **Bee**. You can reach the free templates from [here](https://beefree.io/templates/free/). + +* When we find a template for our purpose, we can hover the link and click the **get started** button to edit the template. (I chose a template named "gdpr".) + +* Here, you can edit your template as below. (You can delete or add sections, edit texts, and so on.) + +![bee](bee.gif) + +> **Note:** After editing our template, we need to export it to reach our created template's content. You can see the **export** button top-right of the template editing page. + +* After choosing and editing our free template, we can create a new **email template** in our project. For this, create a folder named `Templates` under `Emailing` folder in `TemplateReplace.Domain` and add `EmailTemplate.tpl` file inside of it. And copy-paste the below content or your template's content. + +```tpl + + + + + + + + + + + + + + + + + + + +``` + +* Then we need to make the template file as "Embedded Resource". We can do this as below. + +* First right click to **EmailTemplate.tpl** and choose `Properties`. + +![embedded-resource](embedded-resource.jpg) + +* Then be sure about build action is **Embedded resource**. + +![embedded-resource-2](embedded-resource-2.jpg) + +### Step - 4 (Replacing the Email Template) + +* To replace the current email template with our new email template, we need to override it. To achieve this, create a class named `EmailTemplateDefinitionProvider` under `Emailing` folder in `TemplateReplace.Domain` and fill it with the below content. + +```csharp +using Volo.Abp.DependencyInjection; +using Volo.Abp.Emailing.Templates; +using Volo.Abp.TextTemplating; + +namespace TemplateReplace.Emailing +{ + public class EmailTemplateDefinitionProvider : TemplateDefinitionProvider, ITransientDependency + { + public override void Define(ITemplateDefinitionContext context) + { + var emailLayoutTemplate = context.GetOrNull(StandardEmailTemplates.Message); + + emailLayoutTemplate + .WithVirtualFilePath( + "/Emailing/Templates/EmailTemplate.tpl", + isInlineLocalized: true + ); + } + } +} +``` + +* In here we've created a template definition provider class that gets the email layout template and change the virtual file path for the template. + +* This approach allows us to locate templates in any folder instead of the folder defined by the depended module. For more detail, check the [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System). + +### Step - 5 + +* Lastly, we need to configure the [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System). To do this open your `TemplateReplaceDomainModule.cs` in `TemplateReplace.Domain` and update the content as below. + +```csharp +using TemplateReplace.MultiTenancy; +using Volo.Abp.AuditLogging; +using Volo.Abp.BackgroundJobs; +using Volo.Abp.Emailing; +using Volo.Abp.FeatureManagement; +using Volo.Abp.Identity; +using Volo.Abp.IdentityServer; +using Volo.Abp.Modularity; +using Volo.Abp.MultiTenancy; +using Volo.Abp.PermissionManagement.Identity; +using Volo.Abp.PermissionManagement.IdentityServer; +using Volo.Abp.SettingManagement; +using Volo.Abp.TenantManagement; +using Volo.Abp.VirtualFileSystem; + +namespace TemplateReplace +{ + [DependsOn( + typeof(TemplateReplaceDomainSharedModule), + typeof(AbpAuditLoggingDomainModule), + typeof(AbpBackgroundJobsDomainModule), + typeof(AbpFeatureManagementDomainModule), + typeof(AbpIdentityDomainModule), + typeof(AbpPermissionManagementDomainIdentityModule), + typeof(AbpIdentityServerDomainModule), + typeof(AbpPermissionManagementDomainIdentityServerModule), + typeof(AbpSettingManagementDomainModule), + typeof(AbpTenantManagementDomainModule), + typeof(AbpEmailingModule) + )] + public class TemplateReplaceDomainModule : AbpModule + { + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.IsEnabled = MultiTenancyConsts.IsEnabled; + }); + + //Add this configuration + Configure(options => + { + options.FileSets.AddEmbedded(); + }); + } + } +} + +``` + +* And now when we send a new email, we should see our newly defined template as the message like below. + +![email-last](email-last.jpg) + +## Text Template Management + +* Generally, more than one e-mail is required in applications. We create email templates for **"password changes"** or **"welcome"** etc in our applications. In such cases, it is necessary to create different templates for each mail. ABP Commercial allows us to perform these operations on UI in a simple way. Text Template Management provides UI to easily create and manage email templates. + +![template-definitions](template-definitions.png) + +* ABP Commercial's [Text Template Management](https://commercial.abp.io/modules/Volo.TextTemplateManagement) module is really fascinating. It makes it super easy to stores and edits template contents. We can list all templates on a page, editing them, localizing them, and so on. + +![inline-content](inline-content.png) + +* ABP Commercial's text template management module, allows us to modify a template through the UI. + +* I highly recommend you to [check it out](https://commercial.abp.io/modules/Volo.TextTemplateManagement). + +## References + +* [Text Templating](https://docs.abp.io/en/abp/latest/Text-Templating) +* [Emailing](https://docs.abp.io/en/abp/latest/Emailing) +* [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System) \ No newline at end of file diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/bee.gif b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/bee.gif new file mode 100644 index 0000000000..15a3a01e65 Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/bee.gif differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-1.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-1.jpg new file mode 100644 index 0000000000..8a0c4c345b Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-1.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-2.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-2.jpg new file mode 100644 index 0000000000..4adc9614c3 Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-2.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-3.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-3.jpg new file mode 100644 index 0000000000..16b365b8a5 Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/db-migrator-3.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/email-last.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/email-last.jpg new file mode 100644 index 0000000000..898d75568f Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/email-last.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/embedded-resource-2.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/embedded-resource-2.jpg new file mode 100644 index 0000000000..1abdba48cb Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/embedded-resource-2.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/embedded-resource.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/embedded-resource.jpg new file mode 100644 index 0000000000..b03739e6c0 Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/embedded-resource.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/inline-content.png b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/inline-content.png new file mode 100644 index 0000000000..cbbf188f37 Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/inline-content.png differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/message.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/message.jpg new file mode 100644 index 0000000000..fe80c2ac0c Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/message.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/settings.jpg b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/settings.jpg new file mode 100644 index 0000000000..e60fdcc2db Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/settings.jpg differ diff --git a/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/template-definitions.png b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/template-definitions.png new file mode 100644 index 0000000000..aaf46b353e Binary files /dev/null and b/docs/en/Community-Articles/2020-09-09-Replacing-Email-Template-and-Sending-Emails/template-definitions.png differ diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/How-To-Add-Custom-Property-To-The-User-Entity.md b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/How-To-Add-Custom-Property-To-The-User-Entity.md new file mode 100644 index 0000000000..3e8a3e9da2 --- /dev/null +++ b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/How-To-Add-Custom-Property-To-The-User-Entity.md @@ -0,0 +1,160 @@ +# How to Add Custom Properties to the User Entity + +## Introduction + +In this step-by-step article, I will explain how you can customize the user entity class, which is available in every web application you create using the ABP framework, according to your needs. When you read this article, you will learn how to override the services of built-in modules, extend the entities, extend data transfer objects and customize the user interface in the applications you develop using the ABP framework. + +You can see the screenshots below which we will reach at the end of the article. + +![custom-identity-user-list](./custom-identity-user-list.png) + +![new-user](./new-user.png) + +## Preparing the Project + +### Startup template and the initial run + +Abp Framework offers startup templates to get into the work faster. We can create a new startup template using Abp CLI: + +`abp new CustomizeUserDemo` + +> In this article, I will go through the MVC application, but it will work also in the [Angular](https://docs.abp.io/en/abp/latest/Getting-Started?UI=NG&DB=EF&Tiered=No) application. + +After the download is finished, we can run **CustomizeUserDemo.DbMigrator** project to create the database migrations and seed the initial data (admin user, role, etc). Then we can run `CustomizeUserDemo.Web` to see that our application is working. + +> Default admin username is **admin** and password is **1q2w3E\*** + +![initial-project](./initial-project.png) + +In this article, we will go through a scenario together and find the solutions to our questions through this scenario. However, since the scenario is not a real-life scenario, it may be strange, please don't get too about this issue :) + +## Step-1 + +Add two new properties to the `AppUser` in the Users folder of the **CustomizeUserDemo.Domain** project as follows: + +```csharp +public string Title { get; protected set; } + +public int Reputation { get; protected set; } +``` + +## Step-2 + +Create the Users folder in the **CustomizeUserDemo.Domain.Shared** project, create the class `UserConsts` inside the folder and update the class you created as below: + +```csharp +public static class UserConsts +{ + public const string TitlePropertyName = "Title"; + + public const string ReputationPropertyName = "Reputation"; + + public const int MaxTitleLength = 64; + + public const double MaxReputationValue = 1_000; + + public const double MinReputationValue = 1; +} +``` + +## Step-3 + +Update the `CustomizeUserDemoEfCoreEntityExtensionMappings` class in the **CustomizeUserDemo.EntityFramework** project in the EntityFrameworkCore folder as below: + +```csharp +public static class CustomizeUserDemoEfCoreEntityExtensionMappings +{ + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + + public static void Configure() + { + CustomizeUserDemoGlobalFeatureConfigurator.Configure(); + CustomizeUserDemoModuleExtensionConfigurator.Configure(); + + OneTimeRunner.Run(() => + { + ObjectExtensionManager.Instance + .MapEfCoreProperty( + nameof(AppUser.Title), + (entityBuilder, propertyBuilder) => + { + propertyBuilder.IsRequired(); + propertyBuilder.HasMaxLength(UserConsts.MaxTitleLength); + } + ).MapEfCoreProperty( + nameof(AppUser.Reputation), + (entityBuilder, propertyBuilder) => + { + propertyBuilder.HasDefaultValue(UserConsts.MinReputationValue); + } + ); + }); + } +} +``` + +This class can be used to map these extra properties to table fields in the database. Please read [this](https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities) article to improve your understanding of what we are doing. + +So far, we have added our extra features to the `User` entity and matched these features with the `ef core`. + +Now we need to add migration to see what has changed in our database. This for, open the Package Manager Console (PMC) under the menu Tools > NuGet Package Manager. + +![nuget-package-manager](./nuget-package-manager.png) + +Select the **CustomizeUserDemo.EntityFramework.DbMigrations** as the **default project** and execute the following command: + +```bash +Add-Migration "Updated-User-Entity" +``` + +![added-new-migration](./added-new-migration.png) + +This will create a new migration class inside the `Migrations` folder of the **CustomizeUserDemo.EntityFrameworkCore.DbMigrations** project. + +> If you are using another IDE than the Visual Studio, you can use `dotnet-ef` tool as [documented here](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli#create-a-migration). + +Finally, run the **CustomizeUserDemo.DbMigrator** project to update the database. + +When we updated the database, you can see that the `Title` and `Reputation` columns are added to the `Users` table. + +![user-table](./user-table.png) + +## Step-4 +Open the `CustomizeUserDemoModuleExtensionConfigurator` in the **CustomizeUserDemo.Domain.Shared** project, and change the contents of the `ConfigureExtraProperties` method as shown below: +```csharp +private static void ConfigureExtraProperties() +{ + ObjectExtensionManager.Instance.Modules().ConfigureIdentity(identity => + { + identity.ConfigureUser(user => + { + user.AddOrUpdateProperty( + UserConsts.TitlePropertyName, + options => + { + options.Attributes.Add(new RequiredAttribute()); + options.Attributes.Add( + new StringLengthAttribute(UserConsts.MaxTitleLength) + ); + } + ); + user.AddOrUpdateProperty( + UserConsts.ReputationPropertyName, + options => + { + options.DefaultValue = UserConsts.MinReputationValue; + options.Attributes.Add( + new RangeAttribute(UserConsts.MinReputationValue, UserConsts.MaxReputationValue) + ); + } + ); + }); + }); +} +``` + +That's it. Now let's run the application and look at the Identity user page. You can also try to edit and recreate a record if you want, it will work even though we haven't done anything extra. Here is the magic code behind ABP framework. + +If there is a situation you want to add, you can click the contribute button or make a comment. Also, if you like the article, don't forget to share it :) + +Happy coding :) diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/added-new-migration.png b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/added-new-migration.png new file mode 100755 index 0000000000..d459fdeed2 Binary files /dev/null and b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/added-new-migration.png differ diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/custom-identity-user-list.png b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/custom-identity-user-list.png new file mode 100644 index 0000000000..896ed947aa Binary files /dev/null and b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/custom-identity-user-list.png differ diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/initial-project.png b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/initial-project.png new file mode 100755 index 0000000000..6e08833853 Binary files /dev/null and b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/initial-project.png differ diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/new-user.png b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/new-user.png new file mode 100644 index 0000000000..d3a5c66198 Binary files /dev/null and b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/new-user.png differ diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/nuget-package-manager.png b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/nuget-package-manager.png new file mode 100755 index 0000000000..680bc9d2e7 Binary files /dev/null and b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/nuget-package-manager.png differ diff --git a/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/user-table.png b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/user-table.png new file mode 100755 index 0000000000..5bb71b8325 Binary files /dev/null and b/docs/en/Community-Articles/2020-10-08-How-To-Add-Custom-Property-To-The-User-Entity/user-table.png differ diff --git a/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/POST.md b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/POST.md new file mode 100644 index 0000000000..f1387b2a50 --- /dev/null +++ b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/POST.md @@ -0,0 +1,46 @@ +# How to add a new language to your ABP project? + +Adding a new language to your ABP project is pretty simple. Let's add the German language to our ABP project: + + + +1. Go to your solution's root folder and write the following CLI command. This command will generate an empty translation file from English. + ```bash + abp translate -c de-DE + ``` + + Check out for [the complete supported culture codes](https://docs.microsoft.com/en-us/bingmaps/rest-services/common-parameters-and-types/supported-culture-codes). + (For internal development `D:\Github\abp` and `D:\Github\volo\abp`) + +2. Fill the `target` fields in your target language. + + ![Fill target fields](language-target.png) + +3. Copy `abp-translation.json` your solution's root folder (Do not change the filename!) + +4. Run the following command. This command will create the necessary `json` files. + ```bash + abp translate --apply + ``` + +5. Open your solution and add the new language to the language list. To do this; + + * open `MyProjectNameDomainModule.cs` and in `ConfigureServices` you'll find `Configure`. If you have `HttpApi.Host` project then you need to add this in `MyProjectNameHttpApiHostModule.cs` + + ``` + options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch", "de")); + ``` + + ![Add to languages](add-to-languages.png) + + The last parameter is the flag icon. You can find the list of flag icons on https://flagicons.lipis.dev/ + + 6. The last step is running the DbMigrator project. It will seed the database for the new language. + ![The database table](database-table.png) + + + +Close the IIS Express / Kestrel to invalidate the language cache and run the project. You will see the new language on your website. + +![See the final result](website-new-language.png) + diff --git a/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/add-to-languages.png b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/add-to-languages.png new file mode 100644 index 0000000000..1dda317685 Binary files /dev/null and b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/add-to-languages.png differ diff --git a/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/database-table.png b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/database-table.png new file mode 100644 index 0000000000..2d512fabeb Binary files /dev/null and b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/database-table.png differ diff --git a/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/language-target.png b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/language-target.png new file mode 100644 index 0000000000..7b5f104003 Binary files /dev/null and b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/language-target.png differ diff --git a/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/website-new-language.png b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/website-new-language.png new file mode 100644 index 0000000000..1e04841983 Binary files /dev/null and b/docs/en/Community-Articles/2020-11-02-How-To-Add-New-Language/website-new-language.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/Post.md b/docs/en/Community-Articles/2020-12-04-Event-Organizer/Post.md new file mode 100644 index 0000000000..b36d83d0ba --- /dev/null +++ b/docs/en/Community-Articles/2020-12-04-Event-Organizer/Post.md @@ -0,0 +1,936 @@ +# Creating an Event Organizer Application with the ABP Framework & Blazor UI. + +## Introduction + +In this article, we will create an example application that is a simple **meeting/event organizer**: People create events and other people registers to the event. + +The application has been developed with **Blazor** as the UI framework and **MongoDB** as the database provider. + +> This tutorial is based on my notes that I'd created to implement this application in a workshop. It shows the necessary steps to build the application rather than detailed explanations. + +### Source Code + +Source code of the completed application is [available on GitHub](https://github.com/abpframework/abp-samples/tree/master/EventOrganizer). + +### Screenshots + +Here, the pages of the final application. + +**Home Page - Event List** + +![event-list-ui](images/event-list-ui.png) + +**Creating a new Event** + +![event-create-ui](images/event-create-ui.png) + +**Event Detail Page** + +![event-detail-ui](images/event-detail-ui.png) + +## Requirements + +The following tools are needed to be able to run the solution. + +* .NET 5.0 SDK +* Visual Studio 2019 16.8.0+ or another compatible IDE +* MongoDB Server (with MongoDB Compass) + +## Development + +### Creating a new Application + +* Use the following ABP CLI command: + +````bash +abp new EventOrganizer -u blazor -d mongodb +```` + +### Open & Run the Application + +* Open the solution in Visual Studio (or your favorite IDE). +* Run the `EventOrganizer.DbMigrator` application to seed the initial data. +* Run the `EventOrganizer.HttpApi.Host` application that starts the server side. +* Run the `EventOrganizer.Blazor` application to start the UI. + +### Apply the Custom Styles + +* Add styles to `wwwroot/main.css`: + +````css +body.abp-application-layout { + background-color: #222 !important; + font-size: 18px; +} +nav#main-navbar.bg-dark { + background-color: #222 !important; + box-shadow: none !important; +} +.event-pic { + width: 100%; + border-radius: 12px; + box-shadow: 5px 5px 0px 0px rgba(0,0,0,.5); + margin-bottom: 10px; +} +.event-link:hover, .event-link:hover *{ + text-decoration: none; +} +.event-link:hover .event-pic { + box-shadow: 5px 5px 0px 0px #ffd800; +} +.event-form { + background-color: #333 !important; + box-shadow: 5px 5px 0px 0px rgba(0,0,0,.5); + border-radius: 12px; +} +.table { + background: #fff; + border-radius: 12px; + box-shadow: 5px 5px 0px 0px rgba(0,0,0,.5); +} +.table th{ + border: 0 !important; +} +.modal { + color: #333; +} +.page-item:first-child .page-link { + margin-left: 0; + border-top-left-radius: 12px; + border-bottom-left-radius: 12px; +} +.page-item:last-child .page-link { + border-top-right-radius: 12px; + border-bottom-right-radius: 12px; +} +.btn { + border-radius: 8px; +} +.att-list { + list-style: none; + padding: 0; +} +.att-list li { + padding: 4px 0 0 0; +} +```` + +* `wwwroot/index.html`: Remove `bg-light` class from the `body` tag and add `bg-dark text-light`. + +### Domain Layer + +* Add the following `Event` aggregate (with `EventAttendee`) to the solution: + +**Event** + +````csharp +using System; +using System.Collections.Generic; +using Volo.Abp.Domain.Entities.Auditing; + +namespace EventOrganizer.Events +{ + public class Event : FullAuditedAggregateRoot + { + public string Title { get; set; } + + public string Description { get; set; } + + public bool IsFree { get; set; } + + public DateTime StartTime { get; set; } + + public ICollection Attendees { get; set; } + + public Event() + { + Attendees = new List(); + } + } +} +```` + +**EventAttendee** + +```csharp +using System; +using Volo.Abp.Auditing; + +namespace EventOrganizer.Events +{ + public class EventAttendee : IHasCreationTime + { + public Guid UserId { get; set; } + + public DateTime CreationTime { get; set; } + } +} +``` + +### MongoDB Mapping + +* Add the following property to the `EventOrganizerMongoDbContext`: + +````csharp +public IMongoCollection Events => Collection(); +```` + +### Clean Index.razor & Add the Header & "Create Event" button + +* Clean the `Index.razor` file. +* Replace the content with the following code: + +````html +@page "/" +@inherits EventOrganizerComponentBase + + +

Upcoming Events

+
+ + @if (CurrentUser.IsAuthenticated) + { + + @L["CreateEvent"] + + } + +
+```` + +* Open `Localization/EventOrganizer/en.json` in the `EventOrganizer.Domain.Shared` project and add the following entry: + +````json +"CreateEvent": "Create a new event!" +```` + +The Result (run the `EventOrganizer.Blazor` application to see): + +![index-title](images/index-title.png) + +### Event Creation + +* Create the Initial `IEventAppService` with the `CreateAsync` method: + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace EventOrganizer.Events +{ + public interface IEventAppService : IApplicationService + { + Task CreateAsync(EventCreationDto input); + } +} +```` + +* Add `EventCreationDto` class: + +````csharp +using System; +using System.ComponentModel.DataAnnotations; + +namespace EventOrganizer.Events +{ + public class EventCreationDto + { + [Required] + [StringLength(100)] + public string Title { get; set; } + + [Required] + [StringLength(2000)] + public string Description { get; set; } + + public bool IsFree { get; set; } + + public DateTime StartTime { get; set; } + } +} +```` + +* Implement the `EventAppService`: + +````csharp +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Volo.Abp.Domain.Repositories; + +namespace EventOrganizer.Events +{ + public class EventAppService : EventOrganizerAppService, IEventAppService + { + private readonly IRepository _eventRepository; + + public EventAppService(IRepository eventRepository) + { + _eventRepository = eventRepository; + } + + [Authorize] + public async Task CreateAsync(EventCreationDto input) + { + var eventEntity = ObjectMapper.Map(input); + await _eventRepository.InsertAsync(eventEntity); + return eventEntity.Id; + } + } +} +```` + +* Add AutoMapper mapping to the `EventOrganizerApplicationAutoMapperProfile` class: + +````csharp +using AutoMapper; +using EventOrganizer.Events; + +namespace EventOrganizer +{ + public class EventOrganizerApplicationAutoMapperProfile : Profile + { + public EventOrganizerApplicationAutoMapperProfile() + { + CreateMap(); + } + } +} +```` + +This will automatically create the HTTP (REST) API for the application service (run the `EventOrganizer.HttpApi.Host` application to see it on the Swagger UI): + +![swagger-event-create](images/swagger-event-create.png) + +* Create the `CreateEvent.razor` file: + +````csharp +@page "/create-event" +@inherits EventOrganizerComponentBase +Create Event + + +
+ + + @L["Title"] + + + + @L["Description"] + + + + @L["Free"] + + + @L["StartTime"] + + + + +
+
+
+```` + +* Create a partial `CreateEvent` class in the same folder, with the `CreateEvent.razor.cs` as the file name: + +````csharp +using System.Threading.Tasks; +using EventOrganizer.Events; +using Microsoft.AspNetCore.Components; + +namespace EventOrganizer.Blazor.Pages +{ + public partial class CreateEvent + { + private EventCreationDto Event { get; set; } = new EventCreationDto(); + + private readonly IEventAppService _eventAppService; + private readonly NavigationManager _navigationManager; + + public CreateEvent( + IEventAppService eventAppService, + NavigationManager navigationManager) + { + _eventAppService = eventAppService; + _navigationManager = navigationManager; + } + + private async Task Create() + { + var eventId = await _eventAppService.CreateAsync(Event); + _navigationManager.NavigateTo("/events/" + eventId); + } + } +} +```` + +The final UI is (run the `EventOrganizer.Blazor` application and click to the "Create Event" button): + +![event-create-ui](images/event-create-ui.png) + +### Upcoming Events (Home Page) + +* Open the `IEventAppService` and add a `GetUpcomingAsync` method to get the list of upcoming events: + +````csharp +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace EventOrganizer.Events +{ + public interface IEventAppService : IApplicationService + { + Task CreateAsync(EventCreationDto input); + + Task> GetUpcomingAsync(); + } +} +```` + +* Add a `EventDto` class: + +````csharp +using System; +using Volo.Abp.Application.Dtos; + +namespace EventOrganizer.Events +{ + public class EventDto : EntityDto + { + public string Title { get; set; } + + public string Description { get; set; } + + public bool IsFree { get; set; } + + public DateTime StartTime { get; set; } + + public int AttendeesCount { get; set; } + } +} +```` + +* Implement the `GetUpcomingAsync` in the `EventAppService` class: + +````csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Volo.Abp.Domain.Repositories; + +namespace EventOrganizer.Events +{ + public class EventAppService : EventOrganizerAppService, IEventAppService + { + private readonly IRepository _eventRepository; + + public EventAppService(IRepository eventRepository) + { + _eventRepository = eventRepository; + } + + [Authorize] + public async Task CreateAsync(EventCreationDto input) + { + var eventEntity = ObjectMapper.Map(input); + await _eventRepository.InsertAsync(eventEntity); + return eventEntity.Id; + } + + public async Task> GetUpcomingAsync() + { + var events = await AsyncExecuter.ToListAsync( + _eventRepository + .Where(x => x.StartTime > Clock.Now) + .OrderBy(x => x.StartTime) + ); + + return ObjectMapper.Map, List>(events); + } + } +} +```` + +* Add the following line into the `EventOrganizerApplicationAutoMapperProfile` constructor: + +````csharp +CreateMap(); +```` + +Run the `EventOrganizer.HttpApi.Host` application to see the new `upcoming` endpoint on the Swagger UI: + +![swagger-event-upcoming](images/swagger-event-upcoming.png) + +* Change the `Pages/Index.razor.cs` content in the `EventOrganizer.Blazor` project as shown below: + +```csharp +using System.Collections.Generic; +using System.Threading.Tasks; +using EventOrganizer.Events; + +namespace EventOrganizer.Blazor.Pages +{ + public partial class Index + { + private List UpcomingEvents { get; set; } = new List(); + + private readonly IEventAppService _eventAppService; + + public Index(IEventAppService eventAppService) + { + _eventAppService = eventAppService; + } + + protected override async Task OnInitializedAsync() + { + UpcomingEvents = await _eventAppService.GetUpcomingAsync(); + } + } +} +``` + +* Change the `Pages/Index.razor` content in the `EventOrganizer.Blazor` project as shown below: + +````html +@page "/" +@inherits EventOrganizerComponentBase + + +

Upcoming Events

+
+ + @if (CurrentUser.IsAuthenticated) + { + + @L["CreateEvent"] + + } + +
+ + @foreach (var upcomingEvent in UpcomingEvents) + { + + +
+ @if (upcomingEvent.IsFree) + { + FREE + } + + + @upcomingEvent.AttendeesCount + +
+ +
+ @upcomingEvent.StartTime.ToLongDateString() +

@upcomingEvent.Title

+

@upcomingEvent.Description.TruncateWithPostfix(150)

+
+
+
+ } +
+```` + +The new home page is shown below: + +![event-list-ui](images/event-list-ui.png) + +### Event Detail Page + +* Add `GetAsync`, `RegisterAsync`, `UnregisterAsync` and `DeleteAsync` methods to the `IEventAppService`: + +````csharp +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace EventOrganizer.Events +{ + public interface IEventAppService : IApplicationService + { + Task CreateAsync(EventCreationDto input); + + Task> GetUpcomingAsync(); + + Task GetAsync(Guid id); + + Task RegisterAsync(Guid id); + + Task UnregisterAsync(Guid id); + + Task DeleteAsync(Guid id); + } +} +```` + +* Add `EventDetailDto` class: + +````csharp +using System; +using System.Collections.Generic; +using Volo.Abp.Application.Dtos; + +namespace EventOrganizer.Events +{ + public class EventDetailDto : CreationAuditedEntityDto + { + public string Title { get; set; } + + public string Description { get; set; } + + public bool IsFree { get; set; } + + public DateTime StartTime { get; set; } + + public List Attendees { get; set; } + } +} +```` + +* Add `EventAttendeeDto` class: + +````csharp +using System; + +namespace EventOrganizer.Events +{ + public class EventAttendeeDto + { + public Guid UserId { get; set; } + + public string UserName { get; set; } + + public DateTime CreationTime { get; set; } + } +} +```` + +* Implement the new methods in the `EventAppService`: + +````csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using EventOrganizer.Users; +using Microsoft.AspNetCore.Authorization; +using Volo.Abp; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Users; + +namespace EventOrganizer.Events +{ + public class EventAppService : EventOrganizerAppService, IEventAppService + { + private readonly IRepository _eventRepository; + private readonly IRepository _userRepository; + + public EventAppService(IRepository eventRepository, IRepository userRepository) + { + _eventRepository = eventRepository; + _userRepository = userRepository; + } + + [Authorize] + public async Task CreateAsync(EventCreationDto input) + { + var eventEntity = ObjectMapper.Map(input); + await _eventRepository.InsertAsync(eventEntity); + return eventEntity.Id; + } + + public async Task> GetUpcomingAsync() + { + var events = await AsyncExecuter.ToListAsync( + _eventRepository + .Where(x => x.StartTime > Clock.Now) + .OrderBy(x => x.StartTime) + ); + + return ObjectMapper.Map, List>(events); + } + + public async Task GetAsync(Guid id) + { + var @event = await _eventRepository.GetAsync(id); + var attendeeIds = @event.Attendees.Select(a => a.UserId).ToList(); + var attendees = (await AsyncExecuter.ToListAsync(_userRepository.Where(u => attendeeIds.Contains(u.Id)))) + .ToDictionary(x => x.Id); + + var result = ObjectMapper.Map(@event); + + foreach (var attendeeDto in result.Attendees) + { + attendeeDto.UserName = attendees[attendeeDto.UserId].UserName; + } + + return result; + } + + [Authorize] + public async Task RegisterAsync(Guid id) + { + var @event = await _eventRepository.GetAsync(id); + if (@event.Attendees.Any(a => a.UserId == CurrentUser.Id)) + { + return; + } + + @event.Attendees.Add(new EventAttendee {UserId = CurrentUser.GetId(), CreationTime = Clock.Now}); + await _eventRepository.UpdateAsync(@event); + } + + [Authorize] + public async Task UnregisterAsync(Guid id) + { + var @event = await _eventRepository.GetAsync(id); + var removedItems = @event.Attendees.RemoveAll(x => x.UserId == CurrentUser.Id); + if (removedItems.Any()) + { + await _eventRepository.UpdateAsync(@event); + } + } + + [Authorize] + public async Task DeleteAsync(Guid id) + { + var @event = await _eventRepository.GetAsync(id); + + if (CurrentUser.Id != @event.CreatorId) + { + throw new UserFriendlyException("You don't have the necessary permission to delete this event!"); + } + + await _eventRepository.DeleteAsync(id); + } + } +} +```` + +* Add the following mappings into the `EventOrganizerApplicationAutoMapperProfile`: + +````csharp +CreateMap(); +CreateMap(); +```` + +Run the `EventOrganizer.HttpApi.Host` application to see the complete Event HTTP API in the Swagger UI: + +![swagger-event-all](images/swagger-event-all.png) + +* Create `EventDetail.razor` component with the following content: + +````html +@page "/events/{id}" +@inherits EventOrganizerComponentBase +@if (Event != null) +{ + + +

@Event.Title

+
+ + Back + @if (CurrentUser.IsAuthenticated && CurrentUser.Id == Event.CreatorId) + { + + } + +
+ + +
+
+ @if (Event.IsFree) + { + FREE + } + + + @Event.Attendees.Count + +
+ + Start time: @Event.StartTime.ToLongDateString() +

@Event.Description

+
+
+ +
+ @if (CurrentUser.IsAuthenticated) + { +
+ @if (!IsRegistered) + { + + } + else + { +

You are registered in this event

+ + } +
+ } + else + { + + Login to attend! + + } +
+
+ Attendees (@Event.Attendees.Count) +
    + @foreach (var attendee in Event.Attendees) + { +
  • @attendee.UserName
  • + } +
+
+
+
+} +```` + +* Create `EventDetail.razor.cs` file with the following content: + +````csharp +using System; +using System.Linq; +using System.Threading.Tasks; +using EventOrganizer.Events; +using Microsoft.AspNetCore.Components; + +namespace EventOrganizer.Blazor.Pages +{ + public partial class EventDetail + { + [Parameter] + public string Id { get; set; } + + private EventDetailDto Event { get; set; } + private bool IsRegistered { get; set; } + + private readonly IEventAppService _eventAppService; + private readonly NavigationManager _navigationManager; + + public EventDetail( + IEventAppService eventAppService, + NavigationManager navigationManager) + { + _eventAppService = eventAppService; + _navigationManager = navigationManager; + } + + protected override async Task OnInitializedAsync() + { + await GetEventAsync(); + } + + private async Task GetEventAsync() + { + Event = await _eventAppService.GetAsync(Guid.Parse(Id)); + if (CurrentUser.IsAuthenticated) + { + IsRegistered = Event.Attendees.Any(a => a.UserId == CurrentUser.Id); + } + } + + private async Task Register() + { + await _eventAppService.RegisterAsync(Guid.Parse(Id)); + await GetEventAsync(); + } + + private async Task UnRegister() + { + await _eventAppService.UnregisterAsync(Guid.Parse(Id)); + await GetEventAsync(); + } + + private async Task Delete() + { + if (!await Message.Confirm("This event will be deleted: " + Event.Title)) + { + return; + } + + await _eventAppService.DeleteAsync(Guid.Parse(Id)); + _navigationManager.NavigateTo("/"); + } + } +} +```` + +The resulting page is shown below: + +![event-detail-ui](images/event-detail-ui.png) + +### Integration Tests + +Create an `EventAppService_Tests` class in the `EventOrganizer.Application.Tests` project: + +````csharp +using System; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +namespace EventOrganizer.Events +{ + [Collection(EventOrganizerTestConsts.CollectionDefinitionName)] + public class EventAppService_Tests : EventOrganizerApplicationTestBase + { + private readonly IEventAppService _eventAppService; + + public EventAppService_Tests() + { + _eventAppService = GetRequiredService(); + } + + [Fact] + public async Task Should_Create_A_Valid_Event() + { + // Create an event + + var eventId = await _eventAppService.CreateAsync( + new EventCreationDto + { + Title = "My test event 1", + Description = "My test event description 1", + IsFree = true, + StartTime = DateTime.Now.AddDays(2) + } + ); + + eventId.ShouldNotBe(Guid.Empty); + + // Get the event + + var @event = await _eventAppService.GetAsync(eventId); + @event.Title.ShouldBe("My test event 1"); + + // Get upcoming events + + var events = await _eventAppService.GetUpcomingAsync(); + events.ShouldContain(x => x.Title == "My test event 1"); + } + } +} +```` + +## Source Code + +Source code of the completed application is [available on GitHub](https://github.com/abpframework/abp-samples/tree/master/EventOrganizer). \ No newline at end of file diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-create-ui.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-create-ui.png new file mode 100644 index 0000000000..c4b0c68a31 Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-create-ui.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-detail-ui.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-detail-ui.png new file mode 100644 index 0000000000..f916a129dc Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-detail-ui.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-list-ui.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-list-ui.png new file mode 100644 index 0000000000..4f049c2339 Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/event-list-ui.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/index-title.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/index-title.png new file mode 100644 index 0000000000..c06b8f5d80 Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/index-title.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-all.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-all.png new file mode 100644 index 0000000000..3b0fb24a7d Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-all.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-create.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-create.png new file mode 100644 index 0000000000..5c7e1d0204 Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-create.png differ diff --git a/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-upcoming.png b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-upcoming.png new file mode 100644 index 0000000000..48d0244797 Binary files /dev/null and b/docs/en/Community-Articles/2020-12-04-Event-Organizer/images/swagger-event-upcoming.png differ diff --git a/docs/en/Contribution/Index.md b/docs/en/Contribution/Index.md index 83ec0bf05d..07dc73ab24 100644 --- a/docs/en/Contribution/Index.md +++ b/docs/en/Contribution/Index.md @@ -2,31 +2,36 @@ ABP is an [open source](https://github.com/abpframework) and community driven project. This guide is aims to help anyone wants to contribute to the project. -## community.abp.io +## ABP Community Website -If you want to write articles or "how to" guides related to the ABP Framework and ASP.NET Core, please submit your article to the [community.abp.io](https://community.abp.io/) web site. +If you want to write **articles** or **how to guides** related to the ABP Framework and ASP.NET Core, please submit your article to the [community.abp.io](https://community.abp.io/) website. ## Code Contribution -You can always send pull requests to the Github repository. +You can always send pull requests to the GitHub repository. -- Clone the [ABP repository](https://github.com/abpframework/abp/) from Github. -- Make the required changes. +- Clone the [ABP repository](https://github.com/abpframework/abp/) from GitHub. +- Build the repository using the `/build/build-all.ps1 -f` for one time. +- Make the necessary changes, including unit/integration tests. - Send a pull request. +> When you open a solution in Visual Studio, you may need to execute `dotnet restore` in the root folder of the solution for one time, after it is fully opened in the Visual Studio. This is needed since VS can't properly resolves local references to projects out of the solution. + +### GitHub Issues + Before making any change, please discuss it on the [Github issues](https://github.com/abpframework/abp/issues). In this way, no other developer will work on the same issue and your PR will have a better chance to be accepted. -### Bug Fixes & Enhancements +#### Bug Fixes & Enhancements You may want to fix a known bug or work on a planned enhancement. See [the issue list](https://github.com/abpframework/abp/issues) on Github. -### Feature Requests +#### Feature Requests If you have a feature idea for the framework or modules, [create an issue](https://github.com/abpframework/abp/issues/new) on Github or attend to an existing discussion. Then you can implement it if it's embraced by the community. ## Document Translation -You may want to translate the complete [documentation](https://abp.io/documents/) (including this one) to your mother language. If so, follow these steps: +You may want to translate the complete [documentation](https://docs.abp.io) (including this one) to your mother language. If so, follow these steps: * Clone the [ABP repository](https://github.com/abpframework/abp/) from Github. * To add a new language, create a new folder inside the [docs](https://github.com/abpframework/abp/tree/master/docs) folder. Folder names can be "en", "es", "fr", "tr" and so on based on the language (see [all culture codes](https://msdn.microsoft.com/en-us/library/hh441729.aspx)). @@ -35,9 +40,9 @@ You may want to translate the complete [documentation](https://abp.io/documents/ There are some fundamental documents need to be translated before publishing a language on the [ABP documentation web site](https://docs.abp.io): -* Getting Started documents -* Tutorials -* CLI +* Index (Home) +* Getting Started +* Web Application Development Tutorial A new language is published after these minimum translations have been completed. diff --git a/docs/en/Customizing-Application-Modules-Overriding-Services.md b/docs/en/Customizing-Application-Modules-Overriding-Services.md index d0d8c8a8a1..ab6f29816b 100644 --- a/docs/en/Customizing-Application-Modules-Overriding-Services.md +++ b/docs/en/Customizing-Application-Modules-Overriding-Services.md @@ -29,7 +29,7 @@ public class TestAppService : IIdentityUserAppService, ITransientDependency } ```` -The dependency injection system allows to register multiple services for the same interface. The last registered one is used when the interface is injected. It is a good practice to explicitly replace the service. +The dependency injection system allows to register multiple services for the same interface. The last registered one is used when the interface is injected. It is a good practice to explicitly replace the service. Example: @@ -59,7 +59,6 @@ In most cases, you will want to change one or a few methods of the current imple ### Example: Overriding an Application Service ````csharp -//[RemoteService(IsEnabled = false)] // If you use dynamic controller feature you can disable remote service. Prevent creating duplicate controller for the application service. [Dependency(ReplaceServices = true)] [ExposeServices(typeof(IIdentityUserAppService), typeof(IdentityUserAppService), typeof(MyIdentityUserAppService))] public class MyIdentityUserAppService : IdentityUserAppService @@ -76,7 +75,7 @@ public class MyIdentityUserAppService : IdentityUserAppService { } - public override async Task CreateAsync(IdentityUserCreateDto input) + public async override Task CreateAsync(IdentityUserCreateDto input) { if (input.PhoneNumber.IsNullOrWhiteSpace()) { @@ -109,33 +108,33 @@ public class MyIdentityUserManager : IdentityUserManager { public MyIdentityUserManager( IdentityUserStore store, - IIdentityRoleRepository roleRepository, + IIdentityRoleRepository roleRepository, IIdentityUserRepository userRepository, - IOptions optionsAccessor, + IOptions optionsAccessor, IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, + IEnumerable> userValidators, + IEnumerable> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, - ILogger logger, - ICancellationTokenProvider cancellationTokenProvider) : + ILogger logger, + ICancellationTokenProvider cancellationTokenProvider) : base(store, roleRepository, - userRepository, - optionsAccessor, - passwordHasher, - userValidators, + userRepository, + optionsAccessor, + passwordHasher, + userValidators, passwordValidators, - keyNormalizer, - errors, - services, - logger, + keyNormalizer, + errors, + services, + logger, cancellationTokenProvider) { } - public override async Task CreateAsync(IdentityUser user) + public async override Task CreateAsync(IdentityUser user) { if (user.PhoneNumber.IsNullOrWhiteSpace()) { @@ -162,6 +161,50 @@ This example class inherits from the `IdentityUserManager` [domain service](Doma Check the [localization system](Localization.md) to learn how to localize the error messages. +### Example: Overriding a Controller + +````csharp +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Volo.Abp.Account; +using Volo.Abp.DependencyInjection; + +namespace MyProject.Controllers +{ + [Dependency(ReplaceServices = true)] + [ExposeServices(typeof(AccountController))] + public class MyAccountController : AccountController + { + public MyAccountController(IAccountAppService accountAppService) + : base(accountAppService) + { + + } + + public async override Task SendPasswordResetCodeAsync( + SendPasswordResetCodeDto input) + { + Logger.LogInformation("Your custom logic..."); + + await base.SendPasswordResetCodeAsync(input); + } + } +} +```` + +This example replaces the `AccountController` (An API Controller defined in the [Account Module](Modules/Account.md)) and overrides the `SendPasswordResetCodeAsync` method. + +**`[ExposeServices(typeof(AccountController))]` is essential** here since it registers this controller for the `AccountController` in the dependency injection system. `[Dependency(ReplaceServices = true)]` is also recommended to clear the old registration (even the ASP.NET Core DI system selects the last registered one). + +In addition, The `AccountController` will be removed from [`ApplicationModel`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.applicationmodels.applicationmodel.controllers) because it defines `ExposeServicesAttribute`. If you don't want to remove it, you can configure `AbpAspNetCoreMvcOptions`: + +```csharp +Configure(options => +{ + options.IgnoredControllersOnModelExclusion.AddIfNotContains(typeof(AccountController)); +}); +``` + ### Overriding Other Classes Overriding controllers, framework services, view component classes and any other type of classes registered to dependency injection can be overridden just like the examples above. @@ -179,7 +222,7 @@ Assuming that you've already added a `SocialSecurityNumber` as described in the You can use the [object extension system](Object-Extensions.md) to add the property to the `IdentityUserDto`. Write this code inside the `YourProjectNameDtoExtensions` class comes with the application startup template: ````csharp -ObjectExtensionManager.Instance +ObjectExtensionManager.Instance .AddOrUpdateProperty( "SocialSecurityNumber" ); @@ -251,8 +294,8 @@ ObjectExtensionManager.Instance .AddOrUpdateProperty( new[] { - typeof(IdentityUserDto), - typeof(IdentityUserCreateDto), + typeof(IdentityUserDto), + typeof(IdentityUserCreateDto), typeof(IdentityUserUpdateDto) }, "SocialSecurityNumber" diff --git a/docs/en/Data-Access.md b/docs/en/Data-Access.md index a37f77eb65..7ba85956b9 100644 --- a/docs/en/Data-Access.md +++ b/docs/en/Data-Access.md @@ -1,15 +1,13 @@ # Data Access -## Database Providers - -ABP framework was designed as database agnostic. It can work any type of data source by the help of the [repository](Repositories.md) and [unit of work](Unit-Of-Work.md) abstractions. However, currently the following providers are implemented: +ABP framework was designed as database agnostic. It can work any type of data source by the help of the [repository](Repositories.md) and [unit of work](Unit-Of-Work.md) abstractions. Currently, the following providers are implemented as official: * [Entity Framework Core](Entity-Framework-Core.md) (works with [various DBMS and providers](https://docs.microsoft.com/en-us/ef/core/providers/).) * [MongoDB](MongoDB.md) * [Dapper](Dapper.md) -More providers will be added in the future. - ## See Also -* [Connection Strings](Connection-Strings.md) \ No newline at end of file +* [Connection Strings](Connection-Strings.md) +* [Data Seeding](Data-Seeding.md) +* [Data Filtering](Data-Filtering.md) \ No newline at end of file diff --git a/docs/en/Data-Filtering.md b/docs/en/Data-Filtering.md index 626719b2fc..6df738cf18 100644 --- a/docs/en/Data-Filtering.md +++ b/docs/en/Data-Filtering.md @@ -32,6 +32,8 @@ namespace Acme.BookStore > `ISoftDelete` filter is enabled by default and you can not get deleted entities from database unless you explicitly disable it. See the `IDataFilter` service below. +> Soft-delete entities can be hard-deleted when you use `HardDeleteAsync` method on the repositories. + ### IMultiTenant [Multi-tenancy](Multi-Tenancy.md) is an efficient way of creating SaaS applications. Once you create a multi-tenant application, you typically want to isolate data between tenants. Implement `IMultiTenant` interface to make your entity "multi-tenant aware". diff --git a/docs/en/Data-Seeding.md b/docs/en/Data-Seeding.md index 8827fe96c0..f3e9414f0f 100644 --- a/docs/en/Data-Seeding.md +++ b/docs/en/Data-Seeding.md @@ -38,31 +38,37 @@ namespace Acme.BookStore { private readonly IRepository _bookRepository; private readonly IGuidGenerator _guidGenerator; + private readonly ICurrentTenant _currentTenant; public BookStoreDataSeedContributor( IRepository bookRepository, - IGuidGenerator guidGenerator) + IGuidGenerator guidGenerator, + ICurrentTenant currentTenant) { _bookRepository = bookRepository; _guidGenerator = guidGenerator; + _currentTenant = currentTenant; } public async Task SeedAsync(DataSeedContext context) { - if (await _bookRepository.GetCountAsync() > 0) + using (_currentTenant.Change(context?.TenantId)) { - return; + if (await _bookRepository.GetCountAsync() > 0) + { + return; + } + + var book = new Book( + id: _guidGenerator.Create(), + name: "The Hitchhiker's Guide to the Galaxy", + type: BookType.ScienceFiction, + publishDate: new DateTime(1979, 10, 12), + price: 42 + ); + + await _bookRepository.InsertAsync(book); } - - var book = new Book( - id: _guidGenerator.Create(), - name: "The Hitchhiker's Guide to the Galaxy", - type: BookType.ScienceFiction, - publishDate: new DateTime(1979, 10, 12), - price: 42 - ); - - await _bookRepository.InsertAsync(book); } } } diff --git a/docs/en/Distributed-Event-Bus-Rebus-Integration.md b/docs/en/Distributed-Event-Bus-Rebus-Integration.md new file mode 100644 index 0000000000..7499c1d837 --- /dev/null +++ b/docs/en/Distributed-Event-Bus-Rebus-Integration.md @@ -0,0 +1,65 @@ +# Distributed Event Bus Rebus Integration + +> This document explains **how to configure the [Rebus](http://mookid.dk/category/rebus/)** as the distributed event bus provider. See the [distributed event bus document](Distributed-Event-Bus.md) to learn how to use the distributed event bus system + +## Installation + +Use the ABP CLI to add [Volo.Abp.EventBus.Rebus](https://www.nuget.org/packages/Volo.Abp.EventBus.Rebus) NuGet package to your project: + +* Install the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI) if you haven't installed before. +* Open a command line (terminal) in the directory of the `.csproj` file you want to add the `Volo.Abp.EventBus.Rebus` package. +* Run `abp add-package Volo.Abp.EventBus.Rebus` command. + +If you want to do it manually, install the [Volo.Abp.EventBus.Rebus](https://www.nuget.org/packages/Volo.Abp.EventBus.Rebus) NuGet package to your project and add `[DependsOn(typeof(AbpEventBusRebusModule))]` to the [ABP module](Module-Development-Basics.md) class inside your project. + +## Configuration + +You can configure using the standard [configuration system](Configuration.md), like using the [options](Options.md) classes. + +### The Options Classes + +`AbpRebusEventBusOptions` classe can be used to configure the event bus options for the Rebus. + +You can configure this options inside the `PreConfigureServices` of your [module](Module-Development-Basics.md). + +**Example: Minimize configuration** + +```csharp +PreConfigure(options => +{ + options.InputQueueName = "eventbus"; +}); +``` + +Rebus has many options, you can use the `Configurer` property of `AbpRebusEventBusOptions` class to configure. + +Default events are **stored in memory**. See the [rebus document](https://github.com/rebus-org/Rebus/wiki/Transport) for more details. + +**Example: Configure the store** + +````csharp +PreConfigure(options => +{ + options.InputQueueName = "eventbus"; + options.Configurer = rebusConfigurer => + { + rebusConfigurer.Transport(t => t.UseMsmq("eventbus")); + rebusConfigurer.Subscriptions(s => s.UseJsonFile(@"subscriptions.json")); + }; +}); +```` + +You can use the `Publish` properpty of `AbpRebusEventBusOptions` class to change the publishing method + +**Example: Configure the event publishing** + +````csharp +PreConfigure(options => +{ + options.InputQueueName = "eventbus"; + options.Publish = async (bus, type, data) => + { + await bus.Publish(data); + }; +}); +```` diff --git a/docs/en/Distributed-Event-Bus.md b/docs/en/Distributed-Event-Bus.md index b1444d8eba..02216c7ac8 100644 --- a/docs/en/Distributed-Event-Bus.md +++ b/docs/en/Distributed-Event-Bus.md @@ -8,7 +8,8 @@ Distributed event bus system provides an **abstraction** that can be implemented * `LocalDistributedEventBus` is the default implementation that implements the distributed event bus to work as in-process. Yes! The **default implementation works just like the [local event bus](Local-Event-Bus.md)**, if you don't configure a real distributed provider. * `RabbitMqDistributedEventBus` implements the distributed event bus with the [RabbitMQ](https://www.rabbitmq.com/). See the [RabbitMQ integration document](Distributed-Event-Bus-RabbitMQ-Integration.md) to learn how to configure it. -* `KafkaDistributedEventBus` implements the distributed event bus with the [RabbitMQ](https://kafka.apache.org/). See the [Kafka integration document](Distributed-Event-Bus-Kafka-Integration.md) to learn how to configure it. +* `KafkaDistributedEventBus` implements the distributed event bus with the [Kafka](https://kafka.apache.org/). See the [Kafka integration document](Distributed-Event-Bus-Kafka-Integration.md) to learn how to configure it. +* `RebusDistributedEventBus` implements the distributed event bus with the [Rebus](http://mookid.dk/category/rebus/). See the [Rebus integration document](Distributed-Event-Bus-Rebus-Integration.md) to learn how to configure it. Using a local event bus as default has a few important advantages. The most important one is that: It allows you to write your code compatible to distributed architecture. You can write a monolithic application now that can be split into microservices later. It is a good practice to communicate between bounded contexts (or between application modules) via distributed events instead of local events. @@ -44,7 +45,7 @@ namespace AbpDemo public virtual async Task ChangeStockCountAsync(Guid productId, int newCount) { await _distributedEventBus.PublishAsync( - new StockCountChangedEvent + new StockCountChangedEto { ProductId = productId, NewCount = newCount @@ -300,4 +301,4 @@ namespace AbpDemo } ```` -This example uses the `AutoMap` attribute of the AutoMapper to configure the mapping. You could create a profile class instead. Please refer to the AutoMapper document for more options. \ No newline at end of file +This example uses the `AutoMap` attribute of the AutoMapper to configure the mapping. You could create a profile class instead. Please refer to the AutoMapper document for more options. diff --git a/docs/en/Domain-Driven-Design-Implementation-Guide.md b/docs/en/Domain-Driven-Design-Implementation-Guide.md new file mode 100644 index 0000000000..9341df703b --- /dev/null +++ b/docs/en/Domain-Driven-Design-Implementation-Guide.md @@ -0,0 +1,1978 @@ +# Implementing Domain Driven Design + +## Introduction + +This is a **practical guide** for implementing the Domain Driven Design (DDD). While the implementation details rely on the ABP Framework infrastructure, core concepts, principles and patterns are applicable in any kind of solution, even if it is not a .NET solution. + +### Goals + +The goals of this document are to + +* **Introduce and explain** the DDD architecture, concepts, principles, patterns and building blocks. +* Explain the **layered architecture** & solution structure offered by the ABP Framework. +* Introduce **explicit rules** to implement DDD patterns and best practices by giving **concrete examples**. +* Show what **ABP Framework provides** you as the infrastructure for implementing DDD in a proper way. +* And finally, provide **suggestions** based on software development **best practices** and our experiences to create a **maintainable codebase**. + +### Simple Code! + +> **Playing football** is very **simple**, but **playing simple football** is the **hardest thing** there is. +> — Johan Cruyff + +If we take this famous quote for programming, we can say; + +> **Writing code** is very **simple**, but **writing simple code** is the **hardest thing** there is. +> — ??? + +In this document, we will introduce **simple rules**, those are **easy to implement**. + +Once your **application grows**, it will be **hard to follow** these rules. Sometimes you find **breaking rules** will save you time in a short term. However, the saved time in the short term will bring much **more time loss** in the middle and long term. Your code base becomes **complicated** and hard to maintain. Most of the business applications are **re-written** just because you **can't maintain** it anymore. + +If you **follow the rules and best practices**, your code base will be simpler and easier to maintain. Your application **reacts to changes** faster. + +## What is the Domain Driven Design? + +Domain-driven design (DDD) is an approach to software development for **complex** needs by connecting the implementation to an **evolving** model; + +DDD is suitable for **complex domains** and **large-scale** applications rather than simple CRUD applications. It focuses on the **core domain logic** rather than the infrastructure details. It helps to build a **flexible**, modular and **maintainable** code base. + +### OOP & SOLID + +Implementing DDD highly relies on the Object Oriented Programming (OOP) and [SOLID](https://en.wikipedia.org/wiki/SOLID) principles. Actually, it **implements** and **extends** these principles. So, a **good understanding** of OOP & SOLID helps you a lot while truly implementing the DDD. + +### DDD Layers & Clean Architecture + +There are four fundamental layers of a Domain Driven Based Solution; + +![domain-driven-design-layers](images/domain-driven-design-layers.png) + +**Business Logic** places into two layers, the *Domain layer* and the *Application Layer*, while they contain different kinds of business logic; + +* **Domain Layer** implements the core, use-case independent business logic of the domain/system. +* **Application Layer** implements the use cases of the application based on the domain. A use case can be thought as a user interaction on the User Interface (UI). +* **Presentation Layer** contains the UI elements (pages, components) of the application. +* **Infrastructure Layer** supports other layer by implementing the abstractions and integrations to 3rd-party library and systems. + +The same layering can be shown as the diagram below and known as the **Clean Architecture**, or sometimes the **Onion Architecture**: + +![domain-driven-design-clean-architecture](images/domain-driven-design-clean-architecture.png) + +In the Clean Architecture, each layer only **depends on the layer directly inside it**. The most independent layer is shown in the most inner circle and it is the Domain Layer. + +### Core Building Blocks + +DDD mostly **focuses on the Domain & Application Layers** and ignores the Presentation and Infrastructure. They are seen as *details* and the business layers should not depend on them. + +That doesn't mean the Presentation and Infrastructure layers are not important. They are very important. UI frameworks and database providers have their own rules and best practices that you need to know and apply. However these are not in the topics of DDD. + +This section introduces the essential building blocks of the Domain & Application Layers. + +#### Domain Layer Building Blocks + +* **Entity**: An [Entity](Entities.md) is an object with its own properties (state, data) and methods that implements the business logic that is executed on these properties. An entity is represented by its unique identifier (Id). Two entity object with different Ids are considered as different entities. +* **Value Object**: A [Value Object](Value-Objects.md) is another kind of domain object that is identified by its properties rather than a unique Id. That means two Value Objects with same properties are considered as the same object. Value objects are generally implemented as immutable and mostly are much simpler than the Entities. +* **Aggregate & Aggregate Root**: An [Aggregate](Entities.md) is a cluster of objects (entities and value objects) bound together by an **Aggregate Root** object. The Aggregate Root is a specific type of an entity with some additional responsibilities. +* **Repository** (interface): A [Repository](Repositories.md) is a collection-like interface that is used by the Domain and Application Layers to access to the data persistence system (the database). It hides the complexity of the DBMS from the business code. Domain Layer contains the `interface`s of the repositories. +* **Domain Service**: A [Domain Service](Domain-Services.md) is a stateless service that implements core business rules of the domain. It is useful to implement domain logic that depends on multiple aggregate (entity) type or some external services. +* **Specification**: A [Specification](Specifications.md) is used to define named, reusable and combinable filters for entities and other business objects. +* **Domain Event**: A [Domain Event](Event-Bus.md) is a way of informing other services in a loosely coupled manner, when a domain specific event occurs. + +#### Application Layer Building Blocks + +* **Application Service**: An [Application Service](Application-Services.md) is a stateless service that implements use cases of the application. An application service typically gets and returns DTOs. It is used by the Presentation Layer. It uses and coordinates the domain objects to implement the use cases. A use case is typically considered as a Unit Of Work. +* **Data Transfer Object (DTO)**: A [DTO](Data-Transfer-Objects.md) is a simple object without any business logic that is used to transfer state (data) between the Application and Presentation Layers. +* **Unit of Work (UOW)**: A [Unit of Work](Unit-Of-Work.md) is an atomic work that should be done as a transaction unit. All the operations inside a UOW should be committed on success or rolled back on a failure. + +## Implementation: The Big Picture + +### Layering of a .NET Solution + +The picture below shows a Visual Studio Solution created using the ABP's [application startup template](Startup-Templates/Application.md): + +![domain-driven-design-vs-solution](images/domain-driven-design-vs-solution.png) + +The solution name is `IssueTracking` and it consists of multiple projects. The solution is layered by considering **DDD principles** as well as **development** and **deployment** practicals. The sub sections below explains the projects in the solution; + +> Your solution structure may be slightly different if you choose a different UI or Database provider. However, the Domain and Application layers will be same and this is the essential point for the DDD perspective. See the [Application Startup Template](Startup-Templates/Application.md) document if you want to know more about the solution structure. + +#### The Domain Layer + +The Domain Layer is splitted into two projects; + +* `IssueTracking.Domain` is the **essential domain layer** that contains all the **building blocks** (entities, value objects, domain services, specifications, repository interfaces, etc.) introduced before. +* `IssueTracking.Domain.Shared` is a thin project that contains some types those belong to the Domain Layer, but shared with all other layers. For example, it may contain some constants and `enum`s related to the Domain Objects but need to be **reused by other layers**. + +#### The Application Layer + +The Application Layer is also splitted into two projects; + +* `IssueTracking.Application.Contracts` contains the application service **interfaces** and the **DTO**s used by these interfaces. This project can be shared by the client applications (including the UI). +* `IssueTracking.Application` is the **essential application layer** that **implements** the interfaces defined in the Contracts project. + +#### The Presentation Layer + +* `IssueTracking.Web` is an ASP.NET Core MVC / Razor Pages application for this example. This is the only executable application that serves the application and the APIs. + +> ABP Framework also supports different kind of UI frameworks including [Angular](UI/Angular/Quick-Start.md) and [Blazor](UI/Blazor/Overall.md). In these cases, the `IssueTracking.Web` doesn't exist in the solution. Instead, an `IssueTracking.HttpApi.Host` application will be in the solution to serve the HTTP APIs as a standalone endpoint to be consumed by the UI applications via HTTP API calls. + +#### The Remote Service Layer + +* `IssueTracking.HttpApi` project contains HTTP APIs defined by the solution. It typically contains MVC `Controller`s and related models, if available. So, you write your HTTP APIs in this project. + +> Most of the time, API Controllers are just wrappers around the Application Services to expose them to the remote clients. Since ABP Framework's [Automatic API Controller System](API/Auto-API-Controllers.md) **automatically configures and exposes your Application Services as API Controllers**, you typically don't create Controllers in this project. However, the startup solution includes it for the cases you need to manually create API controllers. + +* `IssueTracking.HttpApi.Client` project is useful when you have a C# application that needs to consume your HTTP APIs. Once the client application references this project, it can directly [inject](Dependency-Injection.md) & use the Application Services. This is possible by the help of the ABP Framework's [Dynamic C# Client API Proxies System](API/Dynamic-CSharp-API-Clients.md). + +> There is a Console Application in the `test` folder of the solution, named `IssueTracking.HttpApi.Client.ConsoleTestApp`. It simply uses the `IssueTracking.HttpApi.Client` project to consume the APIs exposed by the application. It is just a demo application and you can safely delete it. You can even delete the `IssueTracking.HttpApi.Client` project if you think that you don't need to them. + +#### The Infrastructure Layer + +In a DDD implementation, you may have a single Infrastructure project to implement all the abstractions and integrations, or you may have different projects for each dependency. + +We suggest a balanced approach; Create separate projects for main infrastructure dependencies (like Entity Framework Core) and a common infrastructure project for other infrastructure. + +ABP's startup solution has two projects for the Entity Framework Core integration; + +* `IssueTracking.EntityFrameworkCore` is the essential integration package for the EF Core. Your application's `DbContext`, database mappings, implementations of the repositories and other EF Core related stuff are located here. +* `IssueTracking.EntityFrameworkCore.DbMigrations` is a special project to manage the Code First database migrations. There is a separate `DbContext` in this project to track the migrations. You typically don't touch this project much except you need to create a new database migration or add an [application module](Modules/Index.md) that has some database tables and naturally requires to create a new database migration. + +> You may wonder why there are two projects for the EF Core. It is mostly related to [modularity](Module-Development-Basics.md). Each module has its own independent `DbContext` and your application has also one `DbContext`. `DbMigrations` project contains a **union** of the modules to track and apply a **single migration path**. While most of the time you don't need to know it, you can see the [EF Core migrations](Entity-Framework-Core-Migrations.md) document for more information. + +#### Other Projects + +There is one more project, `IssueTracking.DbMigrator`, that is a simple Console Application that **migrates** the database schema and **[seeds](Data-Seeding.md) the initial** data when you execute it. It is a useful **utility application** that you can use it in development as well as in production environment. + +### Dependencies of the Projects in the Solution + +The diagram below shows the essential dependencies (project references) between the projects in the solution (`IssueTracking.` part is not shown to be simple) + +![domain-driven-design-project-relations](images/domain-driven-design-project-relations.png) + +The projects have been explained before. Now, we can explain the reasons of the dependencies; + +* `Domain.Shared` is the project that all other projects directly or indirectly depend on. So, all the types in this project are available to all projects. +* `Domain` only depends on the `Domain.Shared` because it is already a (shared) part of the domain. For example, an `IssueType` enum in the `Domain.Shared` can be used by an `Issue` entity in the `Domain` project. +* `Application.Contracts` depends on the `Domain.Shared`. In this way, you can reuse these types in the DTOs. For example, the same `IssueType` enum in the `Domain.Shared` can be used by a `CreateIssueDto` as a property. +* `Application` depends on the `Application.Contracts` since it implements the Application Service interfaces and uses the DTOs inside it. It also depends on the `Domain` since the Application Services are implemented using the Domain Objects defined inside it. +* `EntityFrameworkCore` depends on the `Domain` since it maps the Domain Objects (entities and value types) to database tables (as it is an ORM) and implements the repository interfaces defined in the `Domain`. +* `HttpApi` depends on the `Application.Contacts` since the Controllers inside it inject and use the Application Service interfaces as explained before. +* `HttpApi.Client` depends on the `Application.Contacts` since it can consume the Application Services as explained before. +* `Web` depends on the `HttpApi` since it serves the HTTP APIs defined inside it. Also, in this way, it indirectly depends on the `Application.Contacts` project to consume the Application Services in the Pages/Components. + +#### Dashed Dependencies + +When you investigate the solution, you will see two more dependencies shown with the dashed lines in the figure above. `Web` project depends on the `Application` and `EntityFrameworkCore` projects which *theoretically* should not be like that but actually it is. + +This is because the `Web` is the final project that runs and hosts the application and the **application needs the implementations of the Application Services and the Repositories** while running. + +This design decision potentially allows you to use Entities and EF Core objects in the Presentation Layer which **should be strictly avoided**. However, we find the alternative designs over complicated. Here, two of the alternatives if you want to remove this dependency; + +* Convert `Web` project to a razor class library and create a new project, like `Web.Host`, that depends on the `Web`, `Application` and `EntityFrameworkCore` projects and hosts the application. You don't write any UI code here, but use **only for hosting**. +* Remove `Application` and `EntityFrameworkCore` dependencies from the `Web` project and load their assemblies on application initialization. You can use ABP's [Plug-In Modules](PlugIn-Modules.md) system for that purpose. + +### Execution Flow a DDD Based Application + +The figure below shows a typical request flow for a web application that has been developed based on DDD patterns. + +![](images/domain-driven-design-web-request-flow.png) + +* The request typically begins with a user interaction on the UI (a *use case*) that causes an HTTP request to the server. +* An MVC Controller or a Razor Page Handler in the Presentation Layer (or in the Distributed Services Layer) handles the request and can perform some cross cutting concerns in this stage ([Authorization](Authorization.md), [Validation](Validation.md), [Exception Handling](Exception-Handling.md), etc.). A Controller/Page injects the related Application Service interface and calls its method(s) by sending and receiving DTOs. +* The Application Service uses the Domain Objects (Entities, Repository interfaces, Domain Services, etc.) to implement the *use case*. Application Layer implements some cross cutting concerns (Authorization, Validation, etc.). An Application Service method should be a [Unit Of Work](Unit-Of-Work.md). That means it should be atomic. + +Most of the cross cutting concerns are **automatically and conventionally implemented by the ABP Framework** and you typically don't need to write code for them. + +### Common Principles + +Before going into details, let's see some overall DDD principles; + +#### Database Provider / ORM Independence + +The domain and the application layers should be ORM / Database Provider agnostic. They should only depend on the Repository interfaces and the Repository interfaces don't use any ORM specific objects. + +Here, the main reasons of this principle; + +1. To make your domain/application **infrastructure independent** since the infrastructure may change in the future or you may need to support a second database type later. +2. To make your domain/application **focus on the business code** by hiding the infrastructure details behind the repositories. +3. To make your **automated tests** easier since you can mock the repositories in this case. + +> As a respect to this principle, none of the projects in the solution has reference to the `EntityFrameworkCore` project, except the startup application. + +##### Discussion About the Database Independence Principle + +Especially, the **reason 1** deeply effects your domain **object design** (especially, the entity relations) and **application code**. Assume that you are using [Entity Framework Core](Entity-Framework-Core.md) with a relational database. If you are willing to make your application switchable to [MongoDB](MongoDB.md) later, you can't use some very **useful EF Core features**. Examples; + +* You can't assume [Change Tracking](https://docs.microsoft.com/en-us/ef/core/querying/tracking) since MongoDB provider can't do it. So, you always need to explicitly update the changed entities. +* You can't use [Navigation Properties](https://docs.microsoft.com/en-us/ef/core/modeling/relationships) (or Collections) to other Aggregates in your entities since this is not possible for a Document Database. See the "Rule: Reference Other Aggregates Only By Id" section for more info. + +If you think such features are **important** for you and you **will never stray** from the EF Core, we believe that it is worth **stretching this principle**. We still suggest to use the repository pattern to hide the infrastructure details. But you can assume that you are using EF Core while designing your entity relations and writing your application code. You can even reference to the EF Core NuGet Package from your application layer to be able to directly use the asynchronous LINQ extension methods, like `ToListAsync()` (see the *IQueryable & Async Operations* section in the [Repositories](Repositories.md) document for more info). + +#### Presentation Technology Agnostic + +The presentation technology (UI Framework) is one of the most changed parts of a real world application. It is very important to design the **Domain and Application Layers** to be completely **unaware** of the presentation technology/framework. This principle is relatively easy to implement and ABP's startup template makes it even easier. + +In some cases, you may need to have **duplicate logic** in the application and presentation layers. For example, you may need to duplicate the **validation** and **authorization** checks in both layers. The checks in the UI layer is mostly for **user experience** while checks in the application and domain layers are for **security and data integrity**. That's perfectly normal and necessary. + +#### Focus on the State Changes, Not Reporting + +DDD focuses on how the domain objects **changes and interactions**; How to create an entity and change its properties by preserving the data **integrity/validity** and implementing the **business rules**. + +DDD **ignores reporting** and mass querying. That doesn't mean they are not important. If your application doesn't have fancy dashboards and reports, who would use it? However, reporting is another topic. You typically want to use the full power of the SQL Server or even use a separate data source (like ElasticSearch) for reporting purpose. You will write optimized queries, create indexes and even stored procedures(!). You are free to do all these things as long as you don't infect them into your business logic. + +## Implementation: The Building Blocks + +This is the essential part of this guide. We will introduce and explain some **explicit rules** with examples. You can follow these rules and apply in your solution while implementing the Domain Driven Design. + +### The Example Domain + +The examples will use some concepts those are used by GitHub, like `Issue`, `Repository`, `Label` and `User`, you are already familiar with. The figure below shows some of the aggregates, aggregate roots, entities, value object and the relations between them: + +![domain driven design example schema](images/domain-driven-design-example-domain-schema.png) + +**Issue Aggregate** consists of an `Issue` Aggregate Root that contains `Comment` and `IssueLabel` collections. Other aggregates are shown as simple since we will focus on the Issue Aggregate: + +![domain-driven-design-issue-aggregate-diagram](images/domain-driven-design-issue-aggregate-diagram.png) + +### Aggregates + +As said before, an [Aggregate](Entities.md) is a cluster of objects (entities and value objects) bound together by an Aggregate Root object. This section will introduce the principles and rules related to the Aggregates. + +> We refer the term *Entity* both for *Aggregate Root* and *sub-collection entities* unless we explicitly write *Aggregate Root* or *sub-collection entity*. + +#### Aggregate / Aggregate Root Principles + +##### Business Rules + +Entities are responsible to implement the business rules related to the properties of their own. The *Aggregate Root Entities* are also responsible for their sub-collection entities. + +An aggregate should maintain its self **integrity** and **validity** by implementing domain rules and constraints. That means, unlike the DTOs, Entities have **methods to implement some business logic**. Actually, we should try to implement business rules in the entities wherever possible. + +##### Single Unit + +An aggregate is **retrieved and saved as a single unit**, with all the sub-collections and properties. For example, if you want to add a `Comment` to an `Issue`, you need to; + +* Get the `Issue` from database with including all the sub-collections (`Comment`s and `IssueLabel`s). +* Use methods on the `Issue` class to add a new comment, like `Issue.AddComment(...);`. +* Save the `Issue` (with all sub-collections) to the database as a single database operation (update). + +That may seem strange to the developers used to work with **EF Core & Relational Databases** before. Getting the `Issue` with all details seems **unnecessary and inefficient**. Why don't we just execute an SQL `Insert` command to database without querying any data? + +The answer is that we should **implement the business** rules and preserve the data **consistency** and **integrity** in the **code**. If we have a business rule like "*Users can not comment on the locked issues*", how can we check the `Issue`'s lock state without retrieving it from the database? So, we can execute the business rules only if the related objects available in the application code. + +On the other hand, **MongoDB** developers will find this rule very natural. In MongoDB, an aggregate object (with sub-collections) is saved in a **single collection** in the database (while it is distributed into several tables in a relational database). So, when you get an aggregate, all the sub-collections are already retrieved as a part of the query, without any additional configuration. + +ABP Framework helps to implement this principle in your applications. + +**Example: Add a comment to an issue** + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IRepository _issueRepository; + + public IssueAppService(IRepository issueRepository) + { + _issueRepository = issueRepository; + } + + [Authorize] + public async Task CreateCommentAsync(CreateCommentDto input) + { + var issue = await _issueRepository.GetAsync(input.IssueId); + issue.AddComment(CurrentUser.GetId(), input.Text); + await _issueRepository.UpdateAsync(issue); + } +} +```` + +`_issueRepository.GetAsync` method retrieves the `Issue` with all details (sub-collections) as a single unit by default. While this works out of the box for MongoDB, you need to configure your aggregate details for the EF Core. But, once you configure, repositories automatically handle it. `_issueRepository.GetAsync` method gets an optional parameter, `includeDetails`, that you can pass `false` to disable this behavior when you need it. + +> See the *Loading Related Entities* section of the [EF Core document](Entity-Framework-Core.md) for the configuration and alternative scenarios. + +`Issue.AddComment` gets a `userId` and comment `text`, implements the necessary business rules and adds the comment to the Comments collection of the `Issue`. + +Finally, we use `_issueRepository.UpdateAsync` to save changes to the database. + +> EF Core has a **change tracking** feature. So, you actually don't need to call `_issueRepository.UpdateAsync`. It will be automatically saved thanks to ABP's Unit Of Work system that automatically calls `DbContext.SaveChanges()` at the end of the method. However, for MongoDB, you need to explicitly update the changed entity. +> +> So, if you want to write your code Database Provider independent, you should always call the `UpdateAsync` method for the changed entities. + +##### Transaction Boundary + +An aggregate is generally considered as a transaction boundary. If a use case works with a single aggregate, reads and saves it as a single unit, all the changes made to the aggregate objects are saved together as an atomic operation and you don't need to an explicit database transaction. + +However, in real life, you may need to change **more than one aggregate instances** in a single use case and you need to use database transactions to ensure **atomic update** and **data consistency**. Because of that, ABP Framework uses an explicit database transaction for a use case (an application service method boundary). See the [Unit Of Work](Unit-Of-Work.md) documentation for more info. + +##### Serializability + +An aggregate (with the root entity and sub-collections) should be serializable and transferrable on the wire as a single unit. For example, MongoDB serializes the aggregate to JSON document while saving to the database and deserializes from JSON while reading from the database. + +> This requirement is not necessary when you use relational databases and ORMs. However, it is an important practice of Domain Driven Design. + +The following rules will already bring the serializability. + +#### Aggregate / Aggregate Root Rules & Best Practices + +The following rules ensures implementing the principles introduced above. + +##### Reference Other Aggregates Only By Id + +The first rule says an Aggregate should reference to other aggregates only by their Id. That means you can not add navigation properties to other aggregates. + +* This rule makes it possible to implement the serializability principle. +* It also prevents different aggregates manipulate each other and leaking business logic of an aggregate to one another. + +You see two aggregate roots, `GitRepository` and `Issue` in the example below; + +![domain-driven-design-reference-by-id-sample](images/domain-driven-design-reference-by-id-sample.png) + +* `GitRepository` should not have a collection of the `Issue`s since they are different aggregates. +* `Issue` should not have a navigation property for the related `GitRepository` since it is a different aggregate. +* `Issue` can have `RepositoryId` (as a `Guid`). + +So, when you have an `Issue` and need to have `GitRepository` related to this issue, you need to explicitly query it from database by the `RepositoryId`. + +###### For EF Core & Relational Databases + +In MongoDB, it is naturally not suitable to have such navigation properties/collections. If you do that, you find a copy of the destination aggregate object in the database collection of the source aggregate since it is being serialized to JSON on save. + +However, EF Core & relational database developers may find this restrictive rule unnecessary since EF Core can handle it on database read and write. We see this an important rule that helps to **reduce the complexity** of the domain prevents potential problems and we strongly suggest to implement this rule. However, if you think it is practical to ignore this rule, see the *Discussion About the Database Independence Principle* section above. + +##### Keep Aggregates Small + +One good practice is to keep an aggregate simple and small. This is because an aggregate will be loaded and saved as a single unit and reading/writing a big object has performance problems. See the example below: + +![domain-driven-design-aggregate-keep-small](images/domain-driven-design-aggregate-keep-small.png) + +Role aggregate has a collection of `UserRole` value objects to track the users assigned for this role. Notice that `UserRole` is not another aggregate and it is not a problem for the rule *Reference Other Aggregates Only By Id*. However, it is a problem in practical. A role may be assigned to thousands (even millions) of users in a real life scenario and it is a significant performance problem to load thousands of items whenever you query a `Role` from database (remember: Aggregates are loaded by their sub-collections as a single unit). + +On the other hand, `User` may have such a `Roles` collection since a user doesn't have much roles in practical and it can be useful to have a list of roles while you are working with a User Aggregate. + +If you think carefully, there is one more problem when Role and User both have the list of relation when use a **non-relational database, like MongoDB**. In this case, the same information is duplicated in different collections and it will be hard to maintain data consistency (whenever you add an item to `User.Roles`, you need to add it to `Role.Users` too). + +So, determine your aggregate boundaries and size based on the following considerations; + +* Objects used together. +* Query (load/save) performance and memory consumption. +* Data integrity, validity and consistency. + +In practical; + +* Most of the aggregate roots will **not have sub-collections**. +* A sub-collection should not have more than **100-150 items** inside it at the most case. If you think a collection potentially can have more items, don't define the collection as a part of the aggregate and consider to extract another aggregate root for the entity inside the collection. + +##### Primary Keys of the Aggregate Roots / Entities + +* An aggregate root typically has a single `Id` property for its identifier (Primark Key: PK). We prefer `Guid` as the PK of an aggregate root entity (see the [Guid Genertation document](Guid-Generation.md) to learn why). +* An entity (that's not the aggregate root) in an aggregate can use a composite primary key. + +For example, see the Aggregate root and the Entity below: + +![domain-driven-design-entity-primary-keys](images/domain-driven-design-entity-primary-keys.png) + +* `Organization` has a `Guid` identifier (`Id`). +* `OrganizationUser` is a sub-collection of an `Organization` and has a composite primary key consists of the `OrganizationId` and `UserId`. + +That doesn't mean sub-collection entities should always have composite PKs. They may have single `Id` properties when it's needed. + +> Composite PKs are actually a concept of relational databases since the sub-collection entities have their own tables and needs to a PK. On the other hand, for example, in MongoDB you don't need to define PK for the sub-collection entities at all since they are stored as a part of the aggregate root. + +##### Constructors of the Aggregate Roots / Entities + +The constructor is located where the lifecycle of an entity begins. There are a some responsibilities of a well designed constructor: + +* Gets the **required entity properties** as parameters to **create a valid entity**. Should force to pass only for the required parameters and may get non-required properties as optional parameters. +* **Checks validity** of the parameters. +* Initializes **sub-collections**. + +**Example: `Issue` (Aggregate Root) constructor** + +````csharp +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Volo.Abp; +using Volo.Abp.Domain.Entities; + +namespace IssueTracking.Issues +{ + public class Issue : AggregateRoot + { + public Guid RepositoryId { get; set; } + public string Title { get; set; } + public string Text { get; set; } + public Guid? AssignedUserId { get; set; } + public bool IsClosed { get; set; } + public IssueCloseReason? CloseReason { get; set; } //enum + + public ICollection Labels { get; set; } + + public Issue( + Guid id, + Guid repositoryId, + string title, + string text = null, + Guid? assignedUserId = null + ) : base(id) + { + RepositoryId = repositoryId; + Title = Check.NotNullOrWhiteSpace(title, nameof(title)); + + Text = text; + AssignedUserId = assignedUserId; + + Labels = new Collection(); + } + + private Issue() { /* for deserialization & ORMs */ } + } +} +```` + +* `Issue` class properly **forces to create a valid entity** by getting minimum required properties in its constructor as parameters. +* The constructor **validates** the inputs (`Check.NotNullOrWhiteSpace(...)` throws `ArgumentException` if the given value is empty). +* It **initializes the sub-collections**, so you don't get a null reference exception when you try to use the `Labels` collection after creating the `Issue`. +* The constructor also **takes the `id`** and passes to the `base` class. We don't generate `Guid`s inside the constructor to be able to delegate this responsibility to another service (see [Guid Generation](Guid-Generation.md)). +* Private **empty constructor** is necessary for ORMs. We made it `private` to prevent accidently using it in our own code. + +> See the [Entities](Entities.md) document to learn more about creating entities with the ABP Framework. + +##### Entity Property Accessors & Methods + +The example above may seem strange to you! For example, we force to pass a non-null `Title` in the constructor. However, the developer may then set the `Title` property to `null` without any control. This is because the example code above just focuses on the constructor. + +If we declare all the properties with **public setters** (like the example `Issue` class above), we can't force **validity** and **integrity** of the entity in its lifecycle. So; + +* Use **private setter** for a property when you need to perform any **logic** while setting that property. +* Define public methods to manipulate such properties. + +**Example: Methods to change the properties in a controlled way** + +````csharp +using System; +using Volo.Abp; +using Volo.Abp.Domain.Entities; + +namespace IssueTracking.Issues +{ + public class Issue : AggregateRoot + { + public Guid RepositoryId { get; private set; } //Never changes + public string Title { get; private set; } //Needs validation + public string Text { get; set; } //No validation + public Guid? AssignedUserId { get; set; } //No validation + public bool IsClosed { get; private set; } //Should be changed with CloseReason + public IssueCloseReason? CloseReason { get; private set; } //Should be changed with IsClosed + + //... + + public void SetTitle(string title) + { + Title = Check.NotNullOrWhiteSpace(title, nameof(title)); + } + + public void Close(IssueCloseReason reason) + { + IsClosed = true; + CloseReason = reason; + } + + public void ReOpen() + { + IsClosed = false; + CloseReason = null; + } + } +} +```` + +* `RepositoryId` setter made private and there is no way to change it after creating an `Issue` because this is what we want in this domain: An issue can't be moved to another repository. +* `Title` setter made private and `SetTitle` method has been created if you want to change it later in a controlled way. +* `Text` and `AssignedUserId` has public setters since there is no restriction on them. They can be null or any other value. We think it is unnecessary to define separate methods to set them. If we need later, we can add methods and make the setters private. Breaking changes are not problem in the domain layer since the domain layer is an internal project, it is not exposed to clients. +* `IsClosed` and `IssueCloseReason` are pair properties. Defined `Close` and `ReOpen` methods to change them together. In this way, we prevent to close an issue without any reason. + +##### Business Logic & Exceptions in the Entities + +When you implement validation and business logic in the entities, you frequently need to manage the exceptional cases. In these cases; + +* Create **domain specific exceptions**. +* **Throw these exceptions** in the entity methods when necessary. + +**Example** + +````csharp +public class Issue : AggregateRoot +{ + //... + + public bool IsLocked { get; private set; } + public bool IsClosed { get; private set; } + public IssueCloseReason? CloseReason { get; private set; } + + public void Close(IssueCloseReason reason) + { + IsClosed = true; + CloseReason = reason; + } + + public void ReOpen() + { + if (IsLocked) + { + throw new IssueStateException( + "Can not open a locked issue! Unlock it first." + ); + } + + IsClosed = false; + CloseReason = null; + } + + public void Lock() + { + if (!IsClosed) + { + throw new IssueStateException( + "Can not open a locked issue! Unlock it first." + ); + } + + IsLocked = true; + } + + public void Unlock() + { + IsLocked = false; + } +} +```` + +There are two business rules here; + +* A locked issue can not be re-opened. +* You can not lock an open issue. + +`Issue` class throws an `IssueStateException` in these cases to force the business rules: + +````csharp +using System; + +namespace IssueTracking.Issues +{ + public class IssueStateException : Exception + { + public IssueStateException(string message) + : base(message) + { + + } + } +} +```` + +There are two potential problems of throwing such exceptions; + +1. In case of such an exception, should the **end user** see the exception (error) message? If so, how do you **localize** the exception message? You can not use the [localization](Localization.md) system, because you can't inject and use `IStringLocalizer` in the entities. +2. For a web application or HTTP API, what **HTTP Status Code** should return to the client? + +ABP's [Exception Handling](Exception-Handling.md) system solves these and similar problems. + +**Example: Throwing a business exception with code** + +````csharp +using Volo.Abp; + +namespace IssueTracking.Issues +{ + public class IssueStateException : BusinessException + { + public IssueStateException(string code) + : base(code) + { + + } + } +} +```` + +* `IssueStateException` class inherits the `BusinessException` class. ABP returns 403 (forbidden) HTTP Status code by default (instead of 500 - Internal Server Error) for the exceptions derived from the `BusinessException`. +* The `code` is used as a key in the localization resource file to find the localized message. + +Now, we can change the `ReOpen` method as shown below: + +````csharp +public void ReOpen() +{ + if (IsLocked) + { + throw new IssueStateException("IssueTracking:CanNotOpenLockedIssue"); + } + + IsClosed = false; + CloseReason = null; +} +```` + +> Use constants instead of magic strings. + +And add an entry to the localization resource like below: + +````json +"IssueTracking:CanNotOpenLockedIssue": "Can not open a locked issue! Unlock it first." +```` + +* When you throw the exception, ABP automatically uses this localized message (based on the current language) to show to the end user. +* The exception code (`IssueTracking:CanNotOpenLockedIssue` here) is also sent to the client, so it may handle the error case programmatically. + +> For this example, you could directly throw `BusinessException` instead of defining a specialized `IssueStateException`. The result will be same. See the [exception handling document](Exception-Handling.md) for all the details. + +##### Business Logic in Entities Requiring External Services + +It is simple to implement a business rule in an entity method when the business logic only uses the properties of that entity. What if the business logic requires to **query database** or **use any external services** that should be resolved from the [dependency injection](Dependency-Injection.md) system. Remember; **Entities can not inject services!** + +There are two common ways of implementing such a business logic: + +* Implement the business logic on an entity method and **get external dependencies as parameters** of the method. +* Create a **Domain Service**. + +Domain Services will be explained later. But, now let's see how it can be implemented in the entity class. + +**Example: Business Rule: Can not assign more than 3 open issues to a user concurrently** + +````csharp +public class Issue : AggregateRoot +{ + //... + public Guid? AssignedUserId { get; private set; } + + public async Task AssignToAsync(AppUser user, IUserIssueService userIssueService) + { + var openIssueCount = await userIssueService.GetOpenIssueCountAsync(user.Id); + + if (openIssueCount >= 3) + { + throw new BusinessException("IssueTracking:ConcurrentOpenIssueLimit"); + } + + AssignedUserId = user.Id; + } + + public void CleanAssignment() + { + AssignedUserId = null; + } +} +```` + +* `AssignedUserId` property setter made private. So, the only way to change it to use the `AssignToAsync` and `CleanAssignment` methods. +* `AssignToAsync` gets an `AppUser` entity. Actually, it only uses the `user.Id`, so you could get a `Guid` value, like `userId`. However, this way ensures that the `Guid` value is `Id` of an existing user and not a random `Guid` value. +* `IUserIssueService` is an arbitrary service that is used to get open issue count for a user. It's the responsibility of the code part (that calls the `AssignToAsync`) to resolve the `IUserIssueService` and pass here. +* `AssignToAsync` throws exception if the business rule doesn't meet. +* Finally, if everything is correct, `AssignedUserId` property is set. + +This method perfectly guarantees to apply the business logic when you want to assign an issue to a user. However, it has some problems; + +* It makes the entity class **depending on an external service** which makes the entity **complicated**. +* It makes **hard to use** the entity. The code that uses the entity now needs to inject `IUserIssueService` and pass to the `AssignToAsync` method. + +An alternative way of implementing this business logic is to introduce a **Domain Service**, which will be explained later. + +### Repositories + +A [Repository](Repositories.md) is a collection-like interface that is used by the Domain and Application Layers to access to the data persistence system (the database) to read and write the Business Objects, generally the Aggregates. + +Common Repository principles are; + +* Define a repository **interface in the Domain Layer** (because it is used in the Domain and Application Layers), **implement in the Infrastructure Layer** (*EntityFrameworkCore* project in the startup template). +* **Do not include business logic** inside the repositories. +* Repository interface should be **database provider / ORM independent**. For example, do not return a `DbSet` from a repository method. `DbSet` is an object provided by the EF Core. +* **Create repositories for aggregate roots**, not for all entities. Because, sub-collection entities (of an aggregate) should be accessed over the aggregate root. + +#### Do Not Include Domain Logic in Repositories + +While this rule seems obvious at the beginning, it is easy to leak business logic into repositories. + +**Example: Get inactive issues from a repository** + +````csharp +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Volo.Abp.Domain.Repositories; + +namespace IssueTracking.Issues +{ + public interface IIssueRepository : IRepository + { + Task> GetInActiveIssuesAsync(); + } +} +```` + +`IIssueRepository` extends the standard `IRepository<...>` interface by adding a `GetInActiveIssuesAsync` method. This repository works with such an `Issue` class: + +````csharp +public class Issue : AggregateRoot, IHasCreationTime +{ + public bool IsClosed { get; private set; } + public Guid? AssignedUserId { get; private set; } + public DateTime CreationTime { get; private set; } + public DateTime? LastCommentTime { get; private set; } + //... +} +```` + +(the code shows only the properties we need for this example) + +The rule says the repository shouldn't know the business rules. The question here is "**What is an inactive issue**? Is it a business rule definition?" + +Let's see the implementation to understand it: + +````csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using IssueTracking.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Volo.Abp.Domain.Repositories.EntityFrameworkCore; +using Volo.Abp.EntityFrameworkCore; + +namespace IssueTracking.Issues +{ + public class EfCoreIssueRepository : + EfCoreRepository, + IIssueRepository + { + public EfCoreIssueRepository( + IDbContextProvider dbContextProvider) + : base(dbContextProvider) + { + } + + public async Task> GetInActiveIssuesAsync() + { + var daysAgo30 = DateTime.Now.Subtract(TimeSpan.FromDays(30)); + + return await DbSet.Where(i => + + //Open + !i.IsClosed && + + //Assigned to nobody + i.AssignedUserId == null && + + //Created 30+ days ago + i.CreationTime < daysAgo30 && + + //No comment or the last comment was 30+ days ago + (i.LastCommentTime == null || i.LastCommentTime < daysAgo30) + + ).ToListAsync(); + } + } +} +```` + +(Used EF Core for the implementation. See the [EF Core integration document](Entity-Framework-Core.md) to learn how to create custom repositories with the EF Core.) + +When we check the `GetInActiveIssuesAsync` implementation, we see a **business rule that defines an in-active issue**: The issue should be **open**, **assigned to nobody**, **created 30+ days ago** and has **no comment in the last 30 days**. + +This is an implicit definition of a business rule that is hidden inside a repository method. The problem occurs when we need to reuse this business logic. + +For example, let's say that we want to add an `bool IsInActive()` method on the `Issue` entity. In this way, we can check activeness when we have an issue entity. + +Let's see the implementation: + +````csharp +public class Issue : AggregateRoot, IHasCreationTime +{ + public bool IsClosed { get; private set; } + public Guid? AssignedUserId { get; private set; } + public DateTime CreationTime { get; private set; } + public DateTime? LastCommentTime { get; private set; } + //... + + public bool IsInActive() + { + var daysAgo30 = DateTime.Now.Subtract(TimeSpan.FromDays(30)); + return + //Open + !IsClosed && + + //Assigned to nobody + AssignedUserId == null && + + //Created 30+ days ago + CreationTime < daysAgo30 && + + //No comment or the last comment was 30+ days ago + (LastCommentTime == null || LastCommentTime < daysAgo30); + } +} +```` + +We had to copy/paste/modify the code. What if the definition of the activeness changes? We should not forget to update both places. This is a duplication of a business logic, which is pretty dangerous. + +A good solution to this problem is the *Specification Pattern*! + +### Specifications + +A [specification](Specifications.md) is a **named**, **reusable**, **combinable** and **testable** class to filter the Domain Objects based on the business rules. + +ABP Framework provides necessary infrastructure to easily create specification classes and use them inside your application code. Let's implement the in-active issue filter as a specification class: + +````csharp +using System; +using System.Linq.Expressions; +using Volo.Abp.Specifications; + +namespace IssueTracking.Issues +{ + public class InActiveIssueSpecification : Specification + { + public override Expression> ToExpression() + { + var daysAgo30 = DateTime.Now.Subtract(TimeSpan.FromDays(30)); + return i => + + //Open + !i.IsClosed && + + //Assigned to nobody + i.AssignedUserId == null && + + //Created 30+ days ago + i.CreationTime < daysAgo30 && + + //No comment or the last comment was 30+ days ago + (i.LastCommentTime == null || i.LastCommentTime < daysAgo30); + } + } +} +```` + +`Specification` base class simplifies to create a specification class by defining an expression. Just moved the expression here, from the repository. + +Now, we can re-use the `InActiveIssueSpecification` in the `Issue` entity and `EfCoreIssueRepository` classes. + +#### Using within the Entity + +`Specification` class provides an `IsSatisfiedBy` method that returns `true` if the given object (entity) satisfies the specification. We can re-write the `Issue.IsInActive` method as shown below: + +````csharp +public class Issue : AggregateRoot, IHasCreationTime +{ + public bool IsClosed { get; private set; } + public Guid? AssignedUserId { get; private set; } + public DateTime CreationTime { get; private set; } + public DateTime? LastCommentTime { get; private set; } + //... + + public bool IsInActive() + { + return new InActiveIssueSpecification().IsSatisfiedBy(this); + } +} +```` + +Just created a new instance of the `InActiveIssueSpecification` and used its `IsSatisfiedBy` method to re-use the expression defined by the specification. + +#### Using with the Repositories + +First, starting from the repository interface: + +````csharp +public interface IIssueRepository : IRepository +{ + Task> GetIssuesAsync(ISpecification spec); +} +```` + +Renamed `GetInActiveIssuesAsync` to simple `GetIssuesAsync` by taking a specification object. Since the **specification (the filter) has been moved out of the repository**, we no longer need to create different methods to get issues with different conditions (like `GetAssignedIssues(...)`, `GetLockedIssues(...)`, etc.) + +Updated implementation of the repository can be like that: + +````csharp +public class EfCoreIssueRepository : + EfCoreRepository, + IIssueRepository +{ + public EfCoreIssueRepository( + IDbContextProvider dbContextProvider) + : base(dbContextProvider) + { + } + + public async Task> GetIssuesAsync(ISpecification spec) + { + return await DbSet + .Where(spec.ToExpression()) + .ToListAsync(); + } +} +```` + +Since `ToExpression()` method returns an expression, it can be directly passed to the `Where` method to filter the entities. + +Finally, we can pass any Specification instance to the `GetIssuesAsync` method: + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IIssueRepository _issueRepository; + + public IssueAppService(IIssueRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task DoItAsync() + { + var issues = await _issueRepository.GetIssuesAsync( + new InActiveIssueSpecification() + ); + } +} +```` + +##### With Default Repositories + +Actually, you don't have to create custom repositories to be able to use specifications. The standard `IRepository` already extends the `IQueryable`, so you can use the standard LINQ extension methods over it: + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IRepository _issueRepository; + + public IssueAppService(IRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task DoItAsync() + { + var issues = AsyncExecuter.ToListAsync( + _issueRepository.Where(new InActiveIssueSpecification()) + ); + } +} +```` + +`AsyncExecuter` is a utility provided by the ABP Framework to use asynchronous LINQ extension methods (like `ToListAsync` here) without depending on the EF Core NuGet package. See the [Repositories document](Repositories.md) for more information. + +#### Combining the Specifications + +One powerful side of the Specifications is they are combinable. Assume that we have another specification that returns `true` only if the `Issue` is in a Milestone: + +````csharp +public class MilestoneSpecification : Specification +{ + public Guid MilestoneId { get; } + + public MilestoneSpecification(Guid milestoneId) + { + MilestoneId = milestoneId; + } + + public override Expression> ToExpression() + { + return i => i.MilestoneId == MilestoneId; + } +} +```` + +This Specification is *parametric* as a difference from the `InActiveIssueSpecification`. We can combine both specifications to get a list of inactive issues in a specific milestone: + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IRepository _issueRepository; + + public IssueAppService(IRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task DoItAsync(Guid milestoneId) + { + var issues = AsyncExecuter.ToListAsync( + _issueRepository + .Where( + new InActiveIssueSpecification() + .And(new MilestoneSpecification(milestoneId)) + .ToExpression() + ) + ); + } +} +```` + +The example above uses the `And` extension method to combine the specifications. There are more combining methods are available, like `Or(...)` and `AndNot(...)`. + +> See the [Specifications document](Specifications.md) for more details about the specification infrastructure provided by the ABP Framework. + +### Domain Services + +Domain Services implement domain logic which; + +* Depends on **services and repositories**. +* Needs to work with **multiple aggregates**, so the logic doesn't properly fit in any of the aggregates. + +Domain Services work with Domain Objects. Their methods can **get and return entities, value objects, primitive types**... etc. However, **they don't get/return DTOs**. DTOs is a part of the Application Layer. + +**Example: Assigning an issue to a user** + +Remember how an issue assignment has been implemented in the `Issue` entity: + +````csharp +public class Issue : AggregateRoot +{ + //... + public Guid? AssignedUserId { get; private set; } + + public async Task AssignToAsync(AppUser user, IUserIssueService userIssueService) + { + var openIssueCount = await userIssueService.GetOpenIssueCountAsync(user.Id); + + if (openIssueCount >= 3) + { + throw new BusinessException("IssueTracking:ConcurrentOpenIssueLimit"); + } + + AssignedUserId = user.Id; + } + + public void CleanAssignment() + { + AssignedUserId = null; + } +} +```` + +Here, we will move this logic into a Domain Service. + +First, changing the `Issue` class: + +````csharp +public class Issue : AggregateRoot +{ + //... + public Guid? AssignedUserId { get; internal set; } +} +```` + +* Removed the assign-related methods. +* Changed `AssignedUserId` property's setter from `private` to `internal`, to allow to set it from the Domain Service. + +The next step is to create a domain service, named `IssueManager`, that has `AssignToAsync` to assign the given issue to the given user. + +````csharp +public class IssueManager : DomainService +{ + private readonly IRepository _issueRepository; + + public IssueManager(IRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task AssignToAsync(Issue issue, AppUser user) + { + var openIssueCount = await _issueRepository.CountAsync( + i => i.AssignedUserId == user.Id && !i.IsClosed + ); + + if (openIssueCount >= 3) + { + throw new BusinessException("IssueTracking:ConcurrentOpenIssueLimit"); + } + + issue.AssignedUserId = user.Id; + } +} +```` + +`IssueManager` can inject any service dependency and use to query open issue count on the user. + +> We prefer and suggest to use the `Manager` suffix for the Domain Services. + +The only problem of this design is that `Issue.AssignedUserId` is now open to set out of the class. However, it is not `public`. It is `internal` and changing it is possible only inside the same Assembly, the `IssueTracking.Domain` project for this example solution. We think this is reasonable; + +* Domain Layer developers are already aware of domain rules and they use the `IssueManager`. +* Application Layer developers are already forces to use the `IssueManager` since they don't directly set it. + +While there is a tradeoff between two approaches, we prefer to create Domain Services when the business logic requires to work with external services. + +> If you don't have a good reason, we think **there is no need to create interfaces** (like `IIssueManager` for the `IssueManager`) for Domain Services. + +### Application Services + +An [Application Service](Application-Services.md) is a stateless service that implements **use cases** of the application. An application service typically **gets and returns DTOs**. It is used by the Presentation Layer. It **uses and coordinates the domain objects** (entities, repositories, etc.) to implement the use cases. + +Common principles of an application service are; + +* Implement the **application logic** that is specific to the current use-case. Do not implement the core domain logic inside the application services. We will come back to differences between Application Domain logics. +* **Never get or return entities** for an application service method. This breaks the encapsulation of the Domain Layer. Always get and return DTOs. + +**Example: Assign an Issue to a User** + +````csharp +using System; +using System.Threading.Tasks; +using IssueTracking.Users; +using Microsoft.AspNetCore.Authorization; +using Volo.Abp.Application.Services; +using Volo.Abp.Domain.Repositories; + +namespace IssueTracking.Issues +{ + public class IssueAppService : ApplicationService, IIssueAppService + { + private readonly IssueManager _issueManager; + private readonly IRepository _issueRepository; + private readonly IRepository _userRepository; + + public IssueAppService( + IssueManager issueManager, + IRepository issueRepository, + IRepository userRepository) + { + _issueManager = issueManager; + _issueRepository = issueRepository; + _userRepository = userRepository; + } + + [Authorize] + public async Task AssignAsync(IssueAssignDto input) + { + var issue = await _issueRepository.GetAsync(input.IssueId); + var user = await _userRepository.GetAsync(input.UserId); + + await _issueManager.AssignToAsync(issue, user); + + await _issueRepository.UpdateAsync(issue); + } + } +} +```` + +An application service method typically has three steps those are implemented here; + +1. Get the related domain objects from database to implement the use case. +2. Use domain objects (domain services, entities, etc.) to perform the actual operation. +3. Update the changed entities in the database. + +> The last *Update* is not necessary if your are using EF Core since it has a Change Tracking system. If you want to take advantage of this EF Core feature, please see the *Discussion About the Database Independence Principle* section above. + +`IssueAssignDto` in this example is a simple DTO class: + +````csharp +using System; + +namespace IssueTracking.Issues +{ + public class IssueAssignDto + { + public Guid IssueId { get; set; } + public Guid UserId { get; set; } + } +} +```` + +### Data Transfer Objects + +A [DTO](Data-Transfer-Objects.md) is a simple object that is used to transfer state (data) between the Application and Presentation Layers. So, Application Service methods gets and returns DTOs. + +#### Common DTO Principles & Best Practices + +* A DTO **should be serializable**, by its nature. Because, most of the time it is transferred over network. So, it should have a **parameterless (empty) constructor**. +* Should not contain any **business logic**. +* **Never** inherit from or reference to **entities**. + +**Input DTOs** (those are passed to the Application Service methods) have different natures than **Output DTOs** (those are returned from the Application Service methods). So, they will be treated differently. + +#### Input DTO Best Practices + +##### Do not Define Unused Properties for Input DTOs + +Define **only the properties needed** for the use case! Otherwise, it will be **confusing for the clients** to use the Application Service method. You can surely define **optional properties**, but they should effect how the use case is working, when the client provides them. + +This rule seems unnecessary first. Who would define unused parameters (input DTO properties) for a method? But it happens, especially when you try to reuse input DTOs. + +##### Do not Re-Use Input DTOs + +Define a **specialized input DTO for each use case** (Application Service method). Otherwise, some properties are not used in some cases and this violates the rule defined above: *Do not Define Unused Properties for Input DTOs*. + +Sometimes, it seems appealing to reuse the same DTO class for two use cases, because they are almost same. Even if they are same now, they will probably become different by the time and you will come to the same problem. **Code duplication is a better practice than coupling use cases**. + +Another way of reusing input DTOs is **inheriting** DTOs from each other. While this can be useful in some rare cases, most of the time it brings you to the same point. + +**Example: User Application Service** + +````csharp +public interface IUserAppService : IApplicationService +{ + Task CreateAsync(UserDto input); + Task UpdateAsync(UserDto input); + Task ChangePasswordAsync(UserDto input); +} +```` + +`IUserAppService` uses `UserDto` as the input DTO in all methods (use cases). `UserDto` is defined below: + +````csharp +public class UserDto +{ + public Guid Id { get; set; } + public string UserName { get; set; } + public string Email { get; set; } + public string Password { get; set; } + public DateTime CreationTime { get; set; } +} +```` + +For this example; + +* `Id` is not used in *Create* since the server determines it. +* `Password` is not used in *Update* since we have another method for it. +* `CreationTime` is never used since we can't allow client to send the Creation Time. It should be set in the server. + +A true implementation can be like that: + +````csharp +public interface IUserAppService : IApplicationService +{ + Task CreateAsync(UserCreationDto input); + Task UpdateAsync(UserUpdateDto input); + Task ChangePasswordAsync(UserChangePasswordDto input); +} +```` + +With the given input DTO classes: + +````csharp +public class UserCreationDto +{ + public string UserName { get; set; } + public string Email { get; set; } + public string Password { get; set; } +} + +public class UserUpdateDto +{ + public Guid Id { get; set; } + public string UserName { get; set; } + public string Email { get; set; } +} + +public class UserChangePasswordDto +{ + public Guid Id { get; set; } + public string Password { get; set; } +} +```` + +This is more maintainable approach although more code is written. + +**Exceptional Case**: There can be some exceptions for this rule: If you always want to develop two methods **in parallel**, they may share the same input DTO (by inheritance or direct reuse). For example, if you have a reporting page that has some filters and you have multiple Application Service methods (like screen report, excel report and csv report methods) use the same filters but returns different results, you may want to reuse the same filter input DTO to **couple these use cases**. Because, in this example, whenever you change a filter, you have to make the necessary changes in all the methods to have a consistent reporting system. + +##### Input DTO Validation Logic + +* Implement only **formal validation** inside the DTO. Use Data Annotation Validation Attributes or implement `IValidatableObject` for formal validation. +* **Do not perform domain validation**. For example, don't try to check unique username constraint in the DTOs. + +**Example: Using Data Annotation Attributes** + +````csharp +using System.ComponentModel.DataAnnotations; + +namespace IssueTracking.Users +{ + public class UserCreationDto + { + [Required] + [StringLength(UserConsts.MaxUserNameLength)] + public string UserName { get; set; } + + [Required] + [EmailAddress] + [StringLength(UserConsts.MaxEmailLength)] + public string Email { get; set; } + + [Required] + [StringLength(UserConsts.MaxEmailLength, + MinimumLength = UserConsts.MinPasswordLength)] + public string Password { get; set; } + } +} +```` + +ABP Framework automatically validates input DTOs, throws `AbpValidationException` and returns HTTP Status `400` to the client in case of an invalid input. + +> Some developers think it is better to separate the validation rules and DTO classes. We think the declarative (Data Annotation) approach is practical and useful and doesn't cause any design problem. However, ABP also supports [FluentValidation integration](FluentValidation.md) if you prefer the other approach. + +> See the [Validation document](Validation.md) for all validation options. + +#### Output DTO Best Practices + +* Keep output **DTO count minimum**. **Reuse** where possible (exception: Do not reuse input DTOs as output DTOs). +* Output DTOs can contain **more properties** than used in the client code. +* Return entity DTO from **Create** and **Update** methods. + +The main goals of these suggestions are; + +* Make client code easy to develop and extend; + * Dealing with **similar, but not same** DTOs are problematic on the client side. + * It is common to **need to other properties** on the UI/client in the future. Returning all properties (by considering security and privileges) of an entity makes client code easy to improve without requiring to touch to the backend code. + * If you are opening your API to **3rd-party clients** that you don't know requirements of each client. +* Make the server side code easy to develop and extend; + * You have less class to **understand and maintain**. + * You can reuse the Entity->DTO **object mapping** code. + * Returning same types from different methods make it easy and clear to create **new methods**. + +**Example: Returning Different DTO types from different methods** + +````csharp +public interface IUserAppService : IApplicationService +{ + UserDto Get(Guid id); + List GetUserNameAndEmail(Guid id); + List GetRoles(Guid id); + List GetList(); + UserCreateResultDto Create(UserCreationDto input); + UserUpdateResultDto Update(UserUpdateDto input); +} +```` + +*(We didn't use async methods to make the example cleaner, but use async in your real world application!)* + +The example code above returns different DTO types for each method. As you can guess, there will be a lot of code duplications for querying data, mapping entities to DTOs. + +The `IUserAppService` service above can be simplified: + +````csharp +public interface IUserAppService : IApplicationService +{ + UserDto Get(Guid id); + List GetList(); + UserDto Create(UserCreationDto input); + UserDto Update(UserUpdateDto input); +} +```` + +With a single output DTO: + +````csharp +public class UserDto +{ + public Guid Id { get; set; } + public string UserName { get; set; } + public string Email { get; set; } + public DateTime CreationTime { get; set; } + public List Roles { get; set; } +} +```` + +* Removed `GetUserNameAndEmail` and `GetRoles` since `Get` method already returns the necessary information. +* `GetList` now returns the same with `Get`. +* `Create` and `Update` also returns the same `UserDto`. + +Using the same DTO has a lot of advantages as explained before. For example, think a scenario where you show a **data grid** of Users on the UI. After updating a user, you can get the return value and **update it on the UI**. So, you don't need to call `GetList` again. This is why we suggest to return the entity DTO (`UserDto` here) as return value from the `Create` and `Update` operations. + +##### Discussion + +Some of the output DTO suggestions may not fit in every scenario. These suggestions can be ignored for **performance** reasons, especially when **large data sets** returned or when you create services for your own UI and you have **too many concurrent requests**. + +In these cases, you may want to create **specialized output DTOs with minimal information**. The suggestions above are especially for applications where **maintaining the codebase** is more important than **negligible performance lost**. + +#### Object to Object Mapping + +Automatic [object to object mapping](Object-To-Object-Mapping.md) is a useful approach to copy values from one object to another when two objects have same or similar properties. + +DTO and Entity classes generally have same/similar properties and you typically need to create DTO objects from Entities. ABP's [object to object mapping system](Object-To-Object-Mapping.md) with [AutoMapper](http://automapper.org/) integration makes these operations much easier comparing to manual mapping. + +* **Use** auto object mapping only for **Entity to output DTO** mappings. +* **Do not use** auto object mapping for **input DTO to Entity** mappings. + +There are some reasons why you **should not use** input DTO to Entity auto mapping; + +1. An Entity class typically has a **constructor** that takes parameters and ensures valid object creation. Auto object mapping operation generally requires an empty constructor. +2. Most of the entity properties will have **private setters** and you should use methods to change these properties in a controlled way. +3. You typically need to **carefully validate and process** the user/client input rather than blindly mapping to the entity properties. + +While some of these problems can be solved through mapping configurations (For example, AutoMapper allows to define custom mapping rules), it makes your business code **implicit/hidden** and **tightly coupled** to the infrastructure. We think the business code should be explicit, clear and easy to understand. + +See the *Entity Creation* section below for an example implementation of the suggestions made in this section. + +## Example Use Cases + +This section will demonstrate some example use cases and discuss alternative scenarios. + +### Entity Creation + +Creating an object from an Entity / Aggregate Root class is the first step of the lifecycle of that entity. The *Aggregate / Aggregate Root Rules & Best Practices* section suggests to **create a primary constructor** for the Entity class that guarantees to **create a valid entity**. So, whenever we need to create an instance of that entity, we should always **use that constructor**. + +See the `Issue` Aggregate Root class below: + +````csharp +public class Issue : AggregateRoot +{ + public Guid RepositoryId { get; private set; } + public string Title { get; private set; } + public string Text { get; set; } + public Guid? AssignedUserId { get; internal set; } + + public Issue( + Guid id, + Guid repositoryId, + string title, + string text = null + ) : base(id) + { + RepositoryId = repositoryId; + Title = Check.NotNullOrWhiteSpace(title, nameof(title)); + Text = text; //Allow empty/null + } + + private Issue() { /* Empty constructor is for ORMs */ } + + public void SetTitle(string title) + { + Title = Check.NotNullOrWhiteSpace(title, nameof(title)); + } + + //... +} +```` + +* This class guarantees to create a valid entity by its constructor. +* If you need to change the `Title` later, you need to use the `SetTitle` method which continues to keep `Title` in a valid state. +* If you want to assign this issue to a user, you need to use `IssueManager` (it implements some business rules before the assignment - see the *Domain Services* section above to remember). +* The `Text` property has a public setter, because it also accepts null values and does not have any validation rules for this example. It is also optional in the constructor. + +Let's see an Application Service method that is used to create an issue: + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IssueManager _issueManager; + private readonly IRepository _issueRepository; + private readonly IRepository _userRepository; + + public IssueAppService( + IssueManager issueManager, + IRepository issueRepository, + IRepository userRepository) + { + _issueManager = issueManager; + _issueRepository = issueRepository; + _userRepository = userRepository; + } + + public async Task CreateAsync(IssueCreationDto input) + { + // Create a valid entity + var issue = new Issue( + GuidGenerator.Create(), + input.RepositoryId, + input.Title, + input.Text + ); + + // Apply additional domain actions + if (input.AssignedUserId.HasValue) + { + var user = await _userRepository.GetAsync(input.AssignedUserId.Value); + await _issueManager.AssignToAsync(issue, user); + } + + // Save + await _issueRepository.InsertAsync(issue); + + // Return a DTO represents the new Issue + return ObjectMapper.Map(issue); + } +} +```` + +`CreateAsync` method; + +* Uses the `Issue` **constructor** to create a valid issue. It passes the `Id` using the [IGuidGenerator](Guid-Generation.md) service. It doesn't use auto object mapping here. +* If the client wants to **assign this issue to a user** on object creation, it uses the `IssueManager` to do it by allowing the `IssueManager` to perform the necessary checks before this assignment. +* **Saves** the entity to the database. +* Finally uses the `IObjectMapper` to return an `IssueDto` that is automatically created by **mapping** from the new `Issue` entity. + +#### Applying Domain Rules on Entity Creation + +The example `Issue` entity has no business rule on entity creation, except some formal validations in the constructor. However, there maybe scenarios where entity creation should check some extra business rules. + +For example, assume that you **don't want** to allow to create an issue if there is already an issue with **exactly the same `Title`**. Where to implement this rule? It is **not proper** to implement this rule in the **Application Service**, because it is a **core business (domain) rule** that should always be checked. + +This rule should be implemented in a **Domain Service**, `IssueManager` in this case. So, we need to force the Application Layer always to use the `IssueManager` to create a new `Issue.` + +First, we can make the `Issue` constructor `internal`, instead of `public`: + +````csharp +public class Issue : AggregateRoot +{ + //... + + internal Issue( + Guid id, + Guid repositoryId, + string title, + string text = null + ) : base(id) + { + RepositoryId = repositoryId; + Title = Check.NotNullOrWhiteSpace(title, nameof(title)); + Text = text; //Allow empty/null + } + + //... +} +```` + +This prevents Application Services to directly use the constructor, so they will use the `IssueManager`. Then we can add a `CreateAsync` method to the `IssueManager`: + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Domain.Services; + +namespace IssueTracking.Issues +{ + public class IssueManager : DomainService + { + private readonly IRepository _issueRepository; + + public IssueManager(IRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task CreateAsync( + Guid repositoryId, + string title, + string text = null) + { + if (await _issueRepository.AnyAsync(i => i.Title == title)) + { + throw new BusinessException("IssueTracking:IssueWithSameTitleExists"); + } + + return new Issue( + GuidGenerator.Create(), + repositoryId, + title, + text + ); + } + } +} +```` + +* `CreateAsync` method checks if there is already an issue with the same title and throws a business exception in this case. +* If there is no duplication, it creates and returns a new `Issue`. + +The `IssueAppService` is changed as shown below in order to use the `IssueManager`'s `CreateAsync` method: + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IssueManager _issueManager; + private readonly IRepository _issueRepository; + private readonly IRepository _userRepository; + + public IssueAppService( + IssueManager issueManager, + IRepository issueRepository, + IRepository userRepository) + { + _issueManager = issueManager; + _issueRepository = issueRepository; + _userRepository = userRepository; + } + + public async Task CreateAsync(IssueCreationDto input) + { + // Create a valid entity using the IssueManager + var issue = await _issueManager.CreateAsync( + input.RepositoryId, + input.Title, + input.Text + ); + + // Apply additional domain actions + if (input.AssignedUserId.HasValue) + { + var user = await _userRepository.GetAsync(input.AssignedUserId.Value); + await _issueManager.AssignToAsync(issue, user); + } + + // Save + await _issueRepository.InsertAsync(issue); + + // Return a DTO represents the new Issue + return ObjectMapper.Map(issue); + } +} + +// *** IssueCreationDto class *** +public class IssueCreationDto +{ + public Guid RepositoryId { get; set; } + [Required] + public string Title { get; set; } + public Guid? AssignedUserId { get; set; } + public string Text { get; set; } +} +```` + +##### Discussion: Why is the Issue not saved to the database in `IssueManager`? + +You may ask "**Why didn't `IssueManager` save the `Issue` to the database?**". We think it is the responsibility of the Application Service. + +Because, the Application Service may require additional changes/operations on the `Issue` object before saving it. If Domain Service saves it, then the *Save* operation is duplicated; + +* It causes performance lost because of double database round trip. +* It requires explicit database transaction that covers both operations. +* If additional actions cancel the entity creation because of a business rule, the transaction should be rolled back in the database. + +When you check the `IssueAppService`, you will see the advantage of **not saving** `Issue` to the database in the `IssueManager.CreateAsync`. Otherwise, we would need to perform one *Insert* (in the `IssueManager`) and one *Update* (after the Assignment). + +##### Discussion: Why is the duplicate Title check not implemented in the Application Service? + +We could simple say "Because it is a **core domain logic** and should be implemented in the Domain Layer". However, it brings a new question "**How did you decide** that it is a core domain logic, but not an application logic?" (we will discuss the difference later with more details). + +For this example, a simple question can help us to make the decision: "If we have another way (use case) of creating an issue, should we still apply the same rule? Is that rule should *always* be implemented". You may think "Why do we have a second way of creating an issue?". However, in real life, you have; + +* **End users** of the application may create issues in your application's standard UI. +* You may have a second **back office** application that is used by your own employees and you may want to provide a way of creating issues (probably with different authorization rules in this case). +* You may have an HTTP API that is open to **3rd-party clients** and they create issues. +* You may have a **background worker** service that do something and creates issues if it detects some problems. In this way, it will create an issue without any user interaction (and probably without any standard authorization check). +* You may have a button on the UI that **converts** something (for example, a discussion) to an issue. + +We can give more examples. All of these are should be implemented by **different Application Service methods** (see the *Multiple Application Layers* section below), but they **always** follow the rule: Title of the new issue can not be same of any existing issue! That's why this logic is a **core domain logic**, should be located in the Domain Layer and **should not be duplicated** in all these application service methods. + +### Updating / Manipulating An Entity + +Once an entity is created, it is updated/manipulated by the use cases until it is deleted from the system. There can be different types of the use cases directly or indirectly changes an entity. + +In this section, we will discuss a typical update operation that changes multiple properties of an `Issue`. + +This time, beginning from the *Update* DTO: + +````csharp +public class UpdateIssueDto +{ + [Required] + public string Title { get; set; } + public string Text { get; set; } + public Guid? AssignedUserId { get; set; } +} +```` + +By comparing to `IssueCreationDto`, you see no `RepositoryId`. Because, our system doesn't allow to move issues across repositories (think as GitHub repositories). Only `Title` is required and the other properties are optional. + +Let's see the *Update* implementation in the `IssueAppService`: + +````csharp +public class IssueAppService : ApplicationService, IIssueAppService +{ + private readonly IssueManager _issueManager; + private readonly IRepository _issueRepository; + private readonly IRepository _userRepository; + + public IssueAppService( + IssueManager issueManager, + IRepository issueRepository, + IRepository userRepository) + { + _issueManager = issueManager; + _issueRepository = issueRepository; + _userRepository = userRepository; + } + + public async Task UpdateAsync(Guid id, UpdateIssueDto input) + { + // Get entity from database + var issue = await _issueRepository.GetAsync(id); + + // Change Title + await _issueManager.ChangeTitleAsync(issue, input.Title); + + // Change Assigned User + if (input.AssignedUserId.HasValue) + { + var user = await _userRepository.GetAsync(input.AssignedUserId.Value); + await _issueManager.AssignToAsync(issue, user); + } + + // Change Text (no business rule, all values accepted) + issue.Text = input.Text; + + // Update entity in the database + await _issueRepository.UpdateAsync(issue); + + // Return a DTO represents the new Issue + return ObjectMapper.Map(issue); + } +} +```` + +* `UpdateAsync` method gets `id` as a separate parameter. It is not included in the `UpdateIssueDto`. This is a design decision that helps ABP to properly define HTTP routes when you [auto expose](API/Auto-API-Controllers.md) this service as an HTTP API endpoint. So, that's not related to DDD. +* It starts by **getting** the `Issue` entity **from the database**. +* Uses `IssueManager`'s `ChangeTitleAsync` instead of directly calling `Issue.SetTitle(...)`. Because we need to implement the **duplicate Title check** as just done in the *Entity Creation*. This requires some changes in the `Issue` and `IssueManager` classes (will be explained below). +* Uses `IssueManager`'s `AssignToAsync` method if the **assigned user** is being changed with this request. +* Directly sets the `Issue.Text` since there is **no business rule** for that. If we need later, we can always refactor. +* **Saves changes** to the database. Again, saving changed entities is a responsibility of the Application Service method that coordinates the business objects and the transaction. If the `IssueManager` had saved internally in `ChangeTitleAsync` and `AssignToAsync` method, there would be double database operation (see the *Discussion: Why is the Issue not saved to the database in `IssueManager`?* above). +* Finally uses the `IObjectMapper` to return an `IssueDto` that is automatically created by **mapping** from the updated `Issue` entity. + +As said, we need some changes in the `Issue` and `IssueManager` classes. + +First, made `SetTitle` internal in the `Issue` class: + +````csharp +internal void SetTitle(string title) +{ + Title = Check.NotNullOrWhiteSpace(title, nameof(title)); +} +```` + +Then added a new method to the `IssueManager` to change the Title: + +````csharp +public async Task ChangeTitleAsync(Issue issue, string title) +{ + if (issue.Title == title) + { + return; + } + + if (await _issueRepository.AnyAsync(i => i.Title == title)) + { + throw new BusinessException("IssueTracking:IssueWithSameTitleExists"); + } + + issue.SetTitle(title); +} +```` + +## Domain Logic & Application Logic + +As mentioned before, *Business Logic* in the Domain Driven Design is spitted into two parts (layers): *Domain Logic* and *Application Logic*: + +![domain-driven-design-domain-vs-application-logic](images/domain-driven-design-domain-vs-application-logic.png) + +Domain Logic consists of the *Core Domain Rules* of the system while Application Logic implements application specific *Use Cases*. + +While the definition is clear, the implementation may not be easy. You may be undecided which code should stand in the Application Layer, which code should be in the Domain Layer. This section tries to explain the differences. + +### Multiple Application Layers + +DDD helps to **deal with complexity** when your system is large. Especially, if there are **multiple applications** are being developed in a **single domain,** then the **Domain Logic vs Application Logic separation** becomes much more important. + +Assume that you are building a system that has multiple applications; + +* A **Public Web Site Application**, built with ASP.NET Core MVC, to show your products to users. Such a web site doesn't require authentication to see the products. The users login to the web site, only if they are performing some actions (like adding a product to the basket). +* A **Back Office Application**, built with Angular UI (that uses REST APIs). This application used by office workers of the company to manage the system (like editing product descriptions). +* A **Mobile Application** that has much simpler UI compared to the Public Web Site. It may communicate to the server via REST APIs or another technology (like TCP sockets). + +![domain-driven-design-multiple-applications](images/domain-driven-design-multiple-applications.png) + +Every application will have different **requirements**, different **use cases** (Application Service methods), different **DTOs**, different **validation** and **authorization** rules... etc. + +Mixing all these logics into a single application layer makes your services contain too many `if` conditions with **complicated business logic** makes your code **harder to develop, maintain and test** and leads to potential bugs. + +If you've multiple applications with a single domain; + +* Create **separate application layers** for each application/client type and implement application specific business logic in these separate layers. +* Use a **single domain layer** to share the core domain logic. + +Such a design makes it even more important to distinguish between Domain logic and Application Logic. + +To be more clear about the implementation, you can create different projects (`.csproj`) for each application types. For example; + +* `IssueTracker.Admin.Application` & `IssueTracker.Admin.Application.Contacts` projects for the Back Office (admin) Application. +* `IssueTracker.Public.Application` & `IssueTracker.Public.Application.Contracts` projects for the Public Web Application. +* `IssueTracker.Mobile.Application` & `IssueTracker.Mobile.Application.Contracts` projects for the Mobile Application. + +### Examples + +This section contains some Application Service and Domain Service examples to discuss how to decide to place business logic inside these services. + +**Example: Creating a new `Organization` in a Domain Service** + +````csharp +public class OrganizationManager : DomainService +{ + private readonly IRepository _organizationRepository; + private readonly ICurrentUser _currentUser; + private readonly IAuthorizationService _authorizationService; + private readonly IEmailSender _emailSender; + + public OrganizationManager( + IRepository organizationRepository, + ICurrentUser currentUser, + IAuthorizationService authorizationService, + IEmailSender emailSender) + { + _organizationRepository = organizationRepository; + _currentUser = currentUser; + _authorizationService = authorizationService; + _emailSender = emailSender; + } + + public async Task CreateAsync(string name) + { + if (await _organizationRepository.AnyAsync(x => x.Name == name)) + { + throw new BusinessException("IssueTracking:DuplicateOrganizationName"); + } + + await _authorizationService.CheckAsync("OrganizationCreationPermission"); + + Logger.LogDebug($"Creating organization {name} by {_currentUser.UserName}"); + + var organization = new Organization(); + + await _emailSender.SendAsync( + "systemadmin@issuetracking.com", + "New Organization", + "A new organization created with name: " + name + ); + + return organization; + } +} +```` + +Let's see the `CreateAsync` method step by step to discuss if the code part should be in the Domain Service, or not; + +* **CORRECT**: It first checks for **duplicate organization name** and and throws exception in this case. This is something related to core domain rule and we never allow duplicated names. +* **WRONG**: Domain Services should not perform **authorization**. [Authorization](Authorization.md) should be done in the Application Layer. +* **WRONG**: It logs a message with including the [Current User](CurrentUser.md)'s `UserName`. Domain service should not be depend on the Current User. Domain Services should be usable even if there is no user in the system. Current User (Session) should be a Presentation/Application Layer related concept. +* **WRONG**: It sends an [email](Emailing.md) about this new organization creation. We think this is also a use case specific business logic. You may want to create different type of emails in different use cases or don't need to send emails in some cases. + +**Example: Creating a new `Organization` in an Application Service** + +````csharp +public class OrganizationAppService : ApplicationService +{ + private readonly OrganizationManager _organizationManager; + private readonly IPaymentService _paymentService; + private readonly IEmailSender _emailSender; + + public OrganizationAppService( + OrganizationManager organizationManager, + IPaymentService paymentService, + IEmailSender emailSender) + { + _organizationManager = organizationManager; + _paymentService = paymentService; + _emailSender = emailSender; + } + + [UnitOfWork] + [Authorize("OrganizationCreationPermission")] + public async Task CreateAsync(CreateOrganizationDto input) + { + await _paymentService.ChargeAsync( + CurrentUser.Id, + GetOrganizationPrice() + ); + + var organization = await _organizationManager.CreateAsync(input.Name); + + await _organizationManager.InsertAsync(organization); + + await _emailSender.SendAsync( + "systemadmin@issuetracking.com", + "New Organization", + "A new organization created with name: " + input.Name + ); + + return organization; // !!! + } + + private double GetOrganizationPrice() + { + return 42; //Gets from somewhere else... + } +} +```` + +Let's see the `CreateAsync` method step by step to discuss if the code part should be in the Application Service, or not; + +* **CORRECT**: Application Service methods should be unit of work (transactional). ABP's [Unit Of Work](Unit-Of-Work.md) system makes this automatic (even without need to add `[UnitOfWork]` attribute for the Application Services). +* **CORRECT**: [Authorization](Authorization.md) should be done in the application layer. Here, it is done by using the `[Authorize]` attribute. +* **CORRECT**: Payment (an infrastructure service) is called to charge money for this operation (Creating an Organization is a paid service in our business). +* **CORRECT**: Application Service method is responsible to save changes to the database. +* **CORRECT**: We can send [email](Emailing.md) as a notification to the system admin. +* **WRONG**: Do not return entities from the Application Services. Return a DTO instead. + +**Discussion: Why don't we move the payment logic into the domain service?** + +You may wonder why the payment code is not inside the `OrganizationManager`. It is an **important thing** and we never want to **miss the payment**. + +However, **being important is not sufficient** to consider a code as a Core Business Logic. We may have **other use cases** where we don't charge money to create a new Organization. Examples; + +* An admin user can use a Back Office Application to create a new organization without any payment. +* A background-working data import/integration/synchronization system may also need to create organizations without any payment operation. + +As you see, **payment is not a necessary operation to create a valid organization**. It is a use-case specific application logic. + +**Example: CRUD Operations** + +````csharp +public class IssueAppService +{ + private readonly IssueManager _issueManager; + + public IssueAppService(IssueManager issueManager) + { + _issueManager = issueManager; + } + + public async Task GetAsync(Guid id) + { + return await _issueManager.GetAsync(id); + } + + public async Task CreateAsync(IssueCreationDto input) + { + await _issueManager.CreateAsync(input); + } + + public async Task UpdateAsync(UpdateIssueDto input) + { + await _issueManager.UpdateAsync(input); + } + + public async Task DeleteAsync(Guid id) + { + await _issueManager.DeleteAsync(id); + } +} +```` + +This Application Service **does nothing** itself and **delegates all the work** to the *Domain Service*. It even passes the DTOs to the `IssueManager`. + +* **Do not** create Domain Service methods just for simple **CRUD** operations **without any domain logic**. +* **Never** pass **DTOs** to or return **DTOs** from the Domain Services. + +Application Services can directly work with repositories to query, create, update or delete data unless there are some domain logics should be performed during these operations. In such cases, create Domain Service methods, but only for those really necessary. + +> Do not create such CRUD domain service methods just by thinking that they may be needed in the future ([YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it))! Do it when you need and refactor the existing code. Since the Application Layer gracefully abstracts the Domain Layer, the refactoring process doesn't effect the UI Layer and other clients. + +## Reference Books + +If you are more interested in the Domain Driven Design and building large-scale enterprise systems, the following books are recommended as reference books; + +* "*Domain Driven Design*" by Eric Evans +* "*Implementing Domain Driven Design*" by Vaughn Vernon +* "*Clean Architecture*" by Robert C. Martin diff --git a/docs/en/Domain-Driven-Design.md b/docs/en/Domain-Driven-Design.md index ce33295492..f18c1882ef 100644 --- a/docs/en/Domain-Driven-Design.md +++ b/docs/en/Domain-Driven-Design.md @@ -10,7 +10,7 @@ ABP framework provides an **infrastructure** to make **Domain Driven Design** ba > - Basing complex designs on a model of the domain; > - Initiating a creative collaboration between technical and domain experts to iteratively refine a conceptual model that addresses particular domain problems. -### Layers +## Layers & Building Blocks ABP follows DDD principles and patterns to achieve a layered application model which consists of four fundamental layers: @@ -19,15 +19,19 @@ ABP follows DDD principles and patterns to achieve a layered application model w - **Domain Layer**: Includes business objects and the core (domain) business rules. This is the heart of the application. - **Infrastructure Layer**: Provides generic technical capabilities that support higher layers mostly using 3rd-party libraries. -## Contents +DDD mostly interest in the **Domain** and the **Application** layers, rather than the Infrastructure and the Presentation layers. The following documents explains the **infrastructure** provided by the ABP Framework to implement **Building Blocks** of the DDD: * **Domain Layer** * [Entities & Aggregate Roots](Entities.md) - * Value Objects * [Repositories](Repositories.md) - * Domain Services - * Specifications + * [Domain Services](Domain-Services.md) + * [Value Objects](Value-Objects.md) + * [Specifications](Specifications.md) * **Application Layer** * [Application Services](Application-Services.md) * [Data Transfer Objects (DTOs)](Data-Transfer-Objects.md) - * Unit of Work \ No newline at end of file + * [Unit of Work](Unit-Of-Work.md) + +## The Ultimate DDD Implementation Guide + +See the [Implementing Domain Driven Design](Domain-Driven-Design-Implementation-Guide.md) guide as a **complete reference**. The Guide explains the Domain Driven Design and introduces explicit **rules and examples** to give a deep understanding of the **implementation details**. \ No newline at end of file diff --git a/docs/en/Domain-Services.md b/docs/en/Domain-Services.md index 7eb6c917cd..5a4f6393e1 100644 --- a/docs/en/Domain-Services.md +++ b/docs/en/Domain-Services.md @@ -1,3 +1,135 @@ -# ABP Documentation +# Domain Services -TODO! \ No newline at end of file +## Introduction + +In a [Domain Driven Design](Domain-Driven-Design.md) (DDD) solution, the core business logic is generally implemented in aggregates ([entities](Entities.md)) and the Domain Services. Creating a Domain Service is especially needed when; + +* You implement a core domain logic that depends on some services (like repositories or other external services). +* The logic you need to implement is related to more than one aggregate/entity, so it doesn't properly fit in any of the aggregates. + +## ABP Domain Service Infrastructure + +Domain Services are simple, stateless classes. While you don't have to derive from any service or interface, ABP Framework provides some useful base classes and conventions. + +### DomainService & IDomainService + +Either derive a Domain Service from the `DomainService` base class or directly implement the `IDomainService` interface. + +**Example: Create a Domain Service deriving from the `DomainService` base class.** + +````csharp +using Volo.Abp.Domain.Services; + +namespace MyProject.Issues +{ + public class IssueManager : DomainService + { + + } +} +```` + +When you do that; + +* ABP Framework automatically registers the class to the Dependency Injection system with a Transient lifetime. +* You can directly use some common services as base properties, without needing to manually inject (e.g. [ILogger](Logging.md) and [IGuidGenerator](Guid-Generation.md)). + +> It is suggested to name a Domain Service with a `Manager` or `Service` suffix. We typically use the `Manager` suffix as used in the sample above. + +**Example: Implement the domain logic of assigning an Issue to a User** + +````csharp +public class IssueManager : DomainService +{ + private readonly IRepository _issueRepository; + + public IssueManager(IRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task AssignAsync(Issue issue, AppUser user) + { + var currentIssueCount = await _issueRepository + .CountAsync(i => i.AssignedUserId == user.Id); + + //Implementing a core business validation + if (currentIssueCount >= 3) + { + throw new IssueAssignmentException(user.UserName); + } + + issue.AssignedUserId = user.Id; + } +} +```` + +Issue is an [aggregate root](Entities.md) defined as shown below: + +````csharp +public class Issue : AggregateRoot +{ + public Guid? AssignedUserId { get; internal set; } + + //... +} +```` + +* Making the setter `internal` ensures that it can not directly set in the upper layers and forces to always use the `IssueManager` to assign an `Issue` to a `User`. + +### Using a Domain Service + +A Domain Service is typically used in an [application service](Application-Services.md). + +**Example: Use the `IssueManager` to assign an Issue to a User** + +````csharp +using System; +using System.Threading.Tasks; +using MyProject.Users; +using Volo.Abp.Application.Services; +using Volo.Abp.Domain.Repositories; + +namespace MyProject.Issues +{ + public class IssueAppService : ApplicationService, IIssueAppService + { + private readonly IssueManager _issueManager; + private readonly IRepository _userRepository; + private readonly IRepository _issueRepository; + + public IssueAppService( + IssueManager issueManager, + IRepository userRepository, + IRepository issueRepository) + { + _issueManager = issueManager; + _userRepository = userRepository; + _issueRepository = issueRepository; + } + + public async Task AssignAsync(Guid id, Guid userId) + { + var issue = await _issueRepository.GetAsync(id); + var user = await _userRepository.GetAsync(userId); + + await _issueManager.AssignAsync(issue, user); + await _issueRepository.UpdateAsync(issue); + } + } +} +```` + +Since the `IssueAppService` is in the Application Layer, it can't directly assign an issue to a user. So, it uses the `IssueManager`. + +## Application Services vs Domain Services + +While both of [Application Services](Application-Services.md) and Domain Services implement the business rules, there are fundamental logical and formal differences; + +* Application Services implement the **use cases** of the application (user interactions in a typical web application), while Domain Services implement the **core, use case independent domain logic**. +* Application Services get/return [Data Transfer Objects](Data-Transfer-Objects.md), Domain Service methods typically get and return the **domain objects** ([entities](Entities.md), [value objects](Value-Objects.md)). +* Domain services are typically used by the Application Services or other Domain Services, while Application Services are used by the Presentation Layer or Client Applications. + +## Lifetime + +Lifetime of Domain Services are [transient](https://docs.abp.io/en/abp/latest/Dependency-Injection) and they are automatically registered to the dependency injection system. \ No newline at end of file diff --git a/docs/en/Entity-Framework-Core-SQLite.md b/docs/en/Entity-Framework-Core-SQLite.md index 62a8ef815d..2a13bf530c 100644 --- a/docs/en/Entity-Framework-Core-SQLite.md +++ b/docs/en/Entity-Framework-Core-SQLite.md @@ -23,6 +23,16 @@ Find `UseSqlServer()` calls in your solution, replace with `UseSqlite()`. Check SQLite connection strings are different than SQL Server connection strings. So, check all `appsettings.json` files in your solution and replace the connection strings inside them. See the [connectionstrings.com]( https://www.connectionstrings.com/sqlite/ ) for details of SQLite connection string options. +An example connection string is + +``` +{ + "ConnectionStrings": { + "Default": "Filename=./MySQLiteDBFile.sqlite" + } +} +``` + You typically will change the `appsettings.json` inside the `.DbMigrator` and `.Web` projects, but it depends on your solution structure. ## Re-Generate the Migrations @@ -38,4 +48,4 @@ Run the `.DbMigrator` project to create the database and seed the initial data. ## Run the Application -It is ready. Just run the application and enjoy coding. \ No newline at end of file +It is ready. Just run the application and enjoy coding. diff --git a/docs/en/Entity-Framework-Core.md b/docs/en/Entity-Framework-Core.md index 98163e7c28..8c0a1c9cc9 100644 --- a/docs/en/Entity-Framework-Core.md +++ b/docs/en/Entity-Framework-Core.md @@ -92,7 +92,7 @@ protected override void OnModelCreating(ModelBuilder builder) b.ToTable("Books"); //Configure the base properties - b.ConfigureByConvention(); + b.ConfigureByConvention(); //Configure other properties (if you are using the fluent API) b.Property(x => x.Name).IsRequired().HasMaxLength(128); @@ -113,7 +113,7 @@ If you have multiple databases in your application, you can configure the connec [ConnectionStringName("MySecondConnString")] public class MyDbContext : AbpDbContext { - + } ``` @@ -174,7 +174,7 @@ public class Book : AggregateRoot } ``` -(`BookType` is a simple enum here) And you want to create a new `Book` entity in a [domain service](Domain-Services.md): +(`BookType` is a simple `enum` here and not important) And you want to create a new `Book` entity in a [domain service](Domain-Services.md): ````csharp public class BookManager : DomainService @@ -221,12 +221,13 @@ public interface IBookRepository : IRepository } ```` -You generally want to derive from the `IRepository` to inherit standard repository methods. However, you don't have to. Repository interfaces are defined in the domain layer of a layered application. They are implemented in the data/infrastructure layer (`EntityFrameworkCore` project in a [startup template](https://abp.io/Templates)). +You generally want to derive from the `IRepository` to inherit standard repository methods (while, you don't have to do). Repository interfaces are defined in the domain layer of a layered application. They are implemented in the data/infrastructure layer (`EntityFrameworkCore` project in a [startup template](https://abp.io/Templates)). Example implementation of the `IBookRepository` interface: ````csharp -public class BookRepository : EfCoreRepository, IBookRepository +public class BookRepository + : EfCoreRepository, IBookRepository { public BookRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) @@ -254,7 +255,7 @@ If you want to replace default repository implementation with your custom reposi context.Services.AddAbpDbContext(options => { options.AddDefaultRepositories(); - + //Replaces IRepository options.AddRepository(); }); @@ -263,7 +264,7 @@ context.Services.AddAbpDbContext(options => This is especially important when you want to **override a base repository method** to customize it. For instance, you may want to override `DeleteAsync` method to delete a specific entity in a more efficient way: ````csharp -public override async Task DeleteAsync( +public async override Task DeleteAsync( Guid id, bool autoSave = false, CancellationToken cancellationToken = default) @@ -272,6 +273,278 @@ public override async Task DeleteAsync( } ```` +## Loading Related Entities + +Assume that you've an `Order` with a collection of `OrderLine`s and the `OrderLine` has a navigation property to the `Order`: + +````csharp +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Volo.Abp.Auditing; +using Volo.Abp.Domain.Entities; + +namespace MyCrm +{ + public class Order : AggregateRoot, IHasCreationTime + { + public Guid CustomerId { get; set; } + public DateTime CreationTime { get; set; } + + public ICollection Lines { get; set; } //Sub collection + + public Order() + { + Lines = new Collection(); + } + } + + public class OrderLine : Entity + { + public Order Order { get; set; } //Navigation property + public Guid OrderId { get; set; } + + public Guid ProductId { get; set; } + public int Count { get; set; } + public double UnitPrice { get; set; } + } +} + +```` + +And defined the database mapping as shown below: + +````csharp +builder.Entity(b => +{ + b.ToTable("Orders"); + b.ConfigureByConvention(); + + //Define the relation + b.HasMany(x => x.Lines) + .WithOne(x => x.Order) + .HasForeignKey(x => x.OrderId) + .IsRequired(); +}); + +builder.Entity(b => +{ + b.ToTable("OrderLines"); + b.ConfigureByConvention(); +}); +```` + +When you query an `Order`, you may want to **include** all the `OrderLine`s in a single query or you may want to **load them later** on demand. + +> Actually these are not directly related to the ABP Framework. You can follow the [EF Core documentation](https://docs.microsoft.com/en-us/ef/core/querying/related-data/) to learn all the details. This section will cover some topics related to the ABP Framework. + +### Eager Loading / Load With Details + +You have different options when you want to load the related entities while querying an entity. + +#### Repository.WithDetails + +`IRepository.WithDetails(...)` can be used to include one relation collection/property to the query. + +**Example: Get an order with lines** + +````csharp +using System; +using System.Linq; +using System.Threading.Tasks; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Domain.Services; + +namespace MyCrm +{ + public class OrderManager : DomainService + { + private readonly IRepository _orderRepository; + + public OrderManager(IRepository orderRepository) + { + _orderRepository = orderRepository; + } + + public async Task TestWithDetails(Guid id) + { + var query = _orderRepository + .WithDetails(x => x.Lines) + .Where(x => x.Id == id); + + var order = await AsyncExecuter.FirstOrDefaultAsync(query); + } + } +} +```` + +> `AsyncExecuter` is used to execute async LINQ extensions without depending on the EF Core. If you add EF Core NuGet package reference to your project, then you can directly use `await _orderRepository.WithDetails(x => x.Lines).FirstOrDefaultAsync()`. But, this time you depend on the EF Core in your domain layer. See the [repository document](Repositories.md) to learn more. + +**Example: Get a list of orders with their lines** + +````csharp +public async Task TestWithDetails() +{ + var query = _orderRepository + .WithDetails(x => x.Lines); + + var orders = await AsyncExecuter.ToListAsync(query); +} +```` + +> `WithDetails` method can get more than one expression parameter if you need to include more than one navigation property or collection. + +#### DefaultWithDetailsFunc + +If you don't pass any expression to the `WithDetails` method, then it includes all the details using the `DefaultWithDetailsFunc` option you provide. + +You can configure `DefaultWithDetailsFunc` for an entity in the `ConfigureServices` method of your [module](Module-Development-Basics.md) in your `EntityFrameworkCore` project. + +**Example: Include `Lines` while querying an `Order`** + +````csharp +Configure(options => +{ + options.Entity(orderOptions => + { + orderOptions.DefaultWithDetailsFunc = query => query.Include(o => o.Lines); + }); +}); +```` + +> You can fully use the EF Core API here since this is located in the EF Core integration project. + +Then you can use the `WithDetails` without any parameter: + +````csharp +public async Task TestWithDetails() +{ + var query = _orderRepository.WithDetails(); + var orders = await AsyncExecuter.ToListAsync(query); +} +```` + +`WithDetails()` executes the expression you've setup as the `DefaultWithDetailsFunc`. + +#### Repository Get/Find Methods + +Some of the standard [Repository](Repositories.md) methods have optional `includeDetails` parameters; + +* `GetAsync` and `FindAsync` gets `includeDetails` with default value is `true`. +* `GetListAsync` and `GetPagedListAsync` gets `includeDetails` with default value is `false`. + +That means, the methods return a **single entity includes details** by default while list returning methods don't include details by default. You can explicitly pass `includeDetails` to change the behavior. + +> These methods use the `DefaultWithDetailsFunc` option that is explained above. + +**Example: Get an order with details** + +````csharp +public async Task TestWithDetails(Guid id) +{ + var order = await _orderRepository.GetAsync(id); +} +```` + +**Example: Get an order without details** + +````csharp +public async Task TestWithoutDetails(Guid id) +{ + var order = await _orderRepository.GetAsync(id, includeDetails: false); +} +```` + +**Example: Get list of entities with details** + +````csharp +public async Task TestWithDetails() +{ + var orders = await _orderRepository.GetListAsync(includeDetails: true); +} +```` + +#### Alternatives + +The repository patters tries to encapsulate the EF Core, so your options are limited. If you need an advanced scenario, you can follow one of the options; + +* Create a custom repository method and use the complete EF Core API. +* Reference to the `Volo.Abp.EntityFrameworkCore` package from your project. In this way, you can directly use `Include` and `ThenInclude` in your code. + +See also [eager loading document](https://docs.microsoft.com/en-us/ef/core/querying/related-data/eager) of the EF Core. + +### Explicit / Lazy Loading + +If you don't include relations while querying an entity and later need to access to a navigation property or collection, you have different options. + +#### EnsurePropertyLoadedAsync / EnsureCollectionLoadedAsync + +Repositories provide `EnsurePropertyLoadedAsync` and `EnsureCollectionLoadedAsync` extension methods to **explicitly load** a navigation property or sub collection. + +**Example: Load Lines of an Order when needed** + +````csharp +public async Task TestWithDetails(Guid id) +{ + var order = await _orderRepository.GetAsync(id, includeDetails: false); + //order.Lines is empty on this stage + + await _orderRepository.EnsureCollectionLoadedAsync(order, x => x.Lines); + //order.Lines is filled now +} +```` + +`EnsurePropertyLoadedAsync` and `EnsureCollectionLoadedAsync` methods do nothing if the property or collection was already loaded. So, calling multiple times has no problem. + +See also [explicit loading document](https://docs.microsoft.com/en-us/ef/core/querying/related-data/explicit) of the EF Core. + +#### Lazy Loading with Proxies + +Explicit loading may not be possible in some cases, especially when you don't have a reference to the `Repository` or `DbContext`. Lazy Loading is a feature of the EF Core that loads the related properties / collections when you first access to it. + +To enable lazy loading; + +1. Install the [Microsoft.EntityFrameworkCore.Proxies](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Proxies/) package into your project (typically to the EF Core integration project) +2. Configure `UseLazyLoadingProxies` for your `DbContext` (in the `ConfigureServices` method of your module in your EF Core project). Example: + +````csharp +Configure(options => +{ + options.PreConfigure(opts => + { + opts.DbContextOptions.UseLazyLoadingProxies(); //Enable lazy loading + }); + + options.UseSqlServer(); +}); +```` + +3. Make your navigation properties and collections `virtual`. Examples: + +````csharp +public virtual ICollection Lines { get; set; } //virtual collection +public virtual Order Order { get; set; } //virtual navigation property +```` + +Once you enable lazy loading and arrange your entities, you can freely access to the navigation properties and collections: + +````csharp +public async Task TestWithDetails(Guid id) +{ + var order = await _orderRepository.GetAsync(id); + //order.Lines is empty on this stage + + var lines = order.Lines; + //order.Lines is filled (lazy loaded) +} +```` + +Whenever you access to a property/collection, EF Core automatically performs an additional query to load the property/collection from the database. + +> Lazy loading should be carefully used since it may cause performance problems in some specific cases. + +See also [lazy loading document](https://docs.microsoft.com/en-us/ef/core/querying/related-data/lazy) of the EF Core. + ## Access to the EF Core API In most cases, you want to hide EF Core APIs behind a repository (this is the main purpose of the repository pattern). However, if you want to access the `DbContext` instance over the repository, you can use `GetDbContext()` or `GetDbSet()` extension methods. Example: @@ -296,7 +569,7 @@ public class BookService * `GetDbContext` returns a `DbContext` reference instead of `BookStoreDbContext`. You can cast it, however in most cases you don't need it. -> Important: You must reference to the `Volo.Abp.EntityFrameworkCore` package from the project you want to access to the DbContext. This breaks encapsulation, but this is what you want in that case. +> Important: You must reference to the `Volo.Abp.EntityFrameworkCore` package from the project you want to access to the `DbContext`. This breaks encapsulation, but this is what you want in that case. ## Extra Properties & Object Extension Manager @@ -365,7 +638,7 @@ public class MyRepositoryBase : EfCoreRepository where TEntity : class, IEntity { - public MyRepositoryBase(IDbContextProvider dbContextProvider) + public MyRepositoryBase(IDbContextProvider dbContextProvider) : base(dbContextProvider) { } @@ -395,7 +668,7 @@ context.Services.AddAbpDbContext(options => typeof(MyRepositoryBase<,>), typeof(MyRepositoryBase<>) ); - + //... }); ``` @@ -446,6 +719,22 @@ context.Services.AddAbpDbContext(options => In this example, `OtherDbContext` implements `IBookStoreDbContext`. This feature allows you to have multiple DbContext (one per module) on development, but single DbContext (implements all interfaces of all DbContexts) on runtime. +### Split Queries + +ABP enables [split queries](https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries) globally by default for better performance. You can change it as needed. + +**Example** + +````csharp +Configure(options => +{ + options.UseSqlServer(optionsBuilder => + { + optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery); + }); +}); +```` + ## See Also -* [Entities](Entities.md) \ No newline at end of file +* [Entities](Entities.md) diff --git a/docs/en/Exception-Handling.md b/docs/en/Exception-Handling.md index 59a2c6bd0e..04cc6fc695 100644 --- a/docs/en/Exception-Handling.md +++ b/docs/en/Exception-Handling.md @@ -85,7 +85,7 @@ Error **details** in an optional field of the JSON error message. Thrown `Except ### Logging -Caught exceptions are automatically logged. +Caught exceptions are automatically logged. #### Log Level @@ -300,7 +300,7 @@ In this case, create a class derived from the `ExceptionSubscriber` class in you ````csharp public class MyExceptionSubscriber : ExceptionSubscriber { - public override async Task HandleAsync(ExceptionNotificationContext context) + public async override Task HandleAsync(ExceptionNotificationContext context) { //TODO... } diff --git a/docs/en/Getting-Started-AspNetCore-Application.md b/docs/en/Getting-Started-AspNetCore-Application.md index 9698b1dfb0..9202ed29f1 100644 --- a/docs/en/Getting-Started-AspNetCore-Application.md +++ b/docs/en/Getting-Started-AspNetCore-Application.md @@ -4,7 +4,7 @@ This tutorial explains how to start ABP from scratch with minimal dependencies. ## Create A New Project -1. Create a new AspNet Core Web Application from Visual Studio 2019 (16.4.0+): +1. Create a new AspNet Core Web Application from Visual Studio 2019 (16.8.0+): ![](images/create-new-aspnet-core-application-v2.png) diff --git a/docs/en/Getting-Started-Create-Solution.md b/docs/en/Getting-Started-Create-Solution.md new file mode 100644 index 0000000000..75a50a737f --- /dev/null +++ b/docs/en/Getting-Started-Create-Solution.md @@ -0,0 +1,65 @@ +# Getting Started + +````json +//[doc-params] +{ + "UI": ["MVC", "Blazor", "NG"], + "DB": ["EF", "Mongo"], + "Tiered": ["Yes", "No"] +} +```` + +> This document assumes that you prefer to use **{{ UI_Value }}** as the UI framework and **{{ DB_Value }}** as the database provider. For other options, please change the preference on top of this document. + +## Create a New Project + +Use the `new` command of the ABP CLI to create a new project: + +````shell +abp new Acme.BookStore{{if UI == "NG"}} -u angular{{else if UI == "Blazor"}} -u blazor{{end}}{{if DB == "Mongo"}} -d mongodb{{end}}{{if Tiered == "Yes"}}{{if UI == "MVC"}} --tiered{{else}} --separate-identity-server{{end}}{{end}} +```` + +*You can use different level of namespaces; e.g. BookStore, Acme.BookStore or Acme.Retail.BookStore.* + +{{ if Tiered == "Yes" }} + +{{ if UI == "MVC" }} + +* `--tiered` argument is used to create N-tiered solution where authentication server, UI and API layers are physically separated. + +{{ else }} + +* `--separate-identity-server` argument is used to separate the identity server application from the API host application. If not specified, you will have a single endpoint on the server. + +{{ end }} + +{{ end }} + +> [ABP CLI document](./CLI.md) covers all of the available commands and options. + +> Alternatively, you can **create and download** projects from [ABP Framework website](https://abp.io/get-started) by easily selecting the all the options from the page. + +### The Solution Structure + +The solution has a layered structure (based on the [Domain Driven Design](Domain-Driven-Design.md)) and contains unit & integration test projects. See the [application template document](Startup-Templates/Application.md) to understand the solution structure in details. + +{{ if DB == "Mongo" }} + +#### MongoDB Transactions + +The [startup template](Startup-templates/Index.md) **disables** transactions in the `.MongoDB` project by default. If your MongoDB server supports transactions, you can enable the it in the *YourProjectMongoDbModule* class's `ConfigureServices` method: + + ```csharp +Configure(options => +{ + options.TransactionBehavior = UnitOfWorkTransactionBehavior.Auto; +}); + ``` + +> Or you can delete that code since `Auto` is already the default behavior. + +{{ end }} + +## Next Step + +* [Running the solution](Getting-Started-Running-Solution.md) \ No newline at end of file diff --git a/docs/en/Getting-Started-React-Native.md b/docs/en/Getting-Started-React-Native.md index a06257fec9..08faac3608 100644 --- a/docs/en/Getting-Started-React-Native.md +++ b/docs/en/Getting-Started-React-Native.md @@ -27,13 +27,13 @@ You have multiple options to initiate a new React Native project that works with ### 1. Using ABP CLI -ABP CLI is probably the most convenient and flexible way to initiate an ABP solution with a React Native application. Simply [install the ABP CLI](../../CLI.md) and run the following command in your terminal: +ABP CLI is probably the most convenient and flexible way to initiate an ABP solution with a React Native application. Simply [install the ABP CLI](CLI.md) and run the following command in your terminal: ```shell abp new MyCompanyName.MyProjectName -csf -u -m react-native ``` -> To see further options in the CLI, please visit the [CLI manual](../../CLI.md). +> To see further options in the CLI, please visit the [CLI manual](CLI.md). This command will prepare a solution with an **Angular** or an **MVC** (depends on your choice), a **.NET Core**, and a **React Native** project in it. diff --git a/docs/en/Getting-Started-Running-Solution.md b/docs/en/Getting-Started-Running-Solution.md new file mode 100644 index 0000000000..d1f02c887b --- /dev/null +++ b/docs/en/Getting-Started-Running-Solution.md @@ -0,0 +1,217 @@ +# Getting Started + +````json +//[doc-params] +{ + "UI": ["MVC", "Blazor", "NG"], + "DB": ["EF", "Mongo"], + "Tiered": ["Yes", "No"] +} +```` + +> This document assumes that you prefer to use **{{ UI_Value }}** as the UI framework and **{{ DB_Value }}** as the database provider. For other options, please change the preference on top of this document. + +## Create the Database + +### Connection String + +Check the **connection string** in the `appsettings.json` file under the {{if Tiered == "Yes"}}`.IdentityServer` and `.HttpApi.Host` projects{{else}}{{if UI=="MVC"}}`.Web` project{{else}}`.HttpApi.Host` project{{end}}{{end}} + +{{ if DB == "EF" }} + +````json +"ConnectionStrings": { + "Default": "Server=localhost;Database=BookStore;Trusted_Connection=True" +} +```` + +The solution is configured to use **Entity Framework Core** with **MS SQL Server** by default. EF Core supports [various](https://docs.microsoft.com/en-us/ef/core/providers/) database providers, so you can use any supported DBMS. See [the Entity Framework integration document](Entity-Framework-Core.md) to learn how to [switch to another DBMS](Entity-Framework-Core-Other-DBMS.md). + +### Apply the Migrations + +The solution uses the [Entity Framework Core Code First Migrations](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli). So, you need to apply migrations to create the database. There are two ways of applying the database migrations. + +#### Apply Migrations Using the DbMigrator + +The solution comes with a `.DbMigrator` console application which applies migrations and also **seeds the initial data**. It is useful on **development** as well as on **production** environment. + +> `.DbMigrator` project has its own `appsettings.json`. So, if you have changed the connection string above, you should also change this one. + +Right click to the `.DbMigrator` project and select **Set as StartUp Project** + +![set-as-startup-project](images/set-as-startup-project.png) + + Hit F5 (or Ctrl+F5) to run the application. It will have an output like shown below: + + ![db-migrator-output](images/db-migrator-output.png) + +> Initial [seed data](Data-Seeding.md) creates the `admin` user in the database (with the password is `1q2w3E*`) which is then used to login to the application. So, you need to use `.DbMigrator` at least once for a new database. + +#### Using EF Core Update-Database Command + +Ef Core has `Update-Database` command which creates database if necessary and applies pending migrations. + +{{ if UI == "MVC" }} + +Right click to the {{if Tiered == "Yes"}}`.IdentityServer`{{else}}`.Web`{{end}} project and select **Set as StartUp project**: + +{{ else if UI != "MVC" }} + +Right click to the `.HttpApi.Host` project and select **Set as StartUp Project**: + +{{ end }} + +![set-as-startup-project](images/set-as-startup-project.png) + +Open the **Package Manager Console**, select `.EntityFrameworkCore.DbMigrations` project as the **Default Project** and run the `Update-Database` command: + +![package-manager-console-update-database](images/package-manager-console-update-database.png) + +This will create a new database based on the configured connection string. + +> **Using the `.DbMigrator` tool is the suggested way**, because it also seeds the initial data to be able to properly run the web application. +> +> If you just use the `Update-Database` command, you will have an empty database, so you can not login to the application since there is no initial admin user in the database. You can use the `Update-Database` command in development time when you don't need to seed the database. However, using the `.DbMigrator` application is easier and you can always use it to migrate the schema and seed the database. + +{{ else if DB == "Mongo" }} + +````json +"ConnectionStrings": { + "Default": "mongodb://localhost:27017/BookStore" +} +```` + +The solution is configured to use **MongoDB** in your local computer, so you need to have a MongoDB server instance up and running or change the connection string to another MongoDB server. + +### Seed Initial Data + +The solution comes with a `.DbMigrator` console application which **seeds the initial data**. It is useful on **development** as well as on **production** environment. + +> `.DbMigrator` project has its own `appsettings.json`. So, if you have changed the connection string above, you should also change this one. + +Right click to the `.DbMigrator` project and select **Set as StartUp Project** + +![set-as-startup-project](images/set-as-startup-project.png) + + Hit F5 (or Ctrl+F5) to run the application. It will have an output like shown below: + + ![db-migrator-output](images/db-migrator-output.png) + +> Initial [seed data](Data-Seeding.md) creates the `admin` user in the database (with the password is `1q2w3E*`) which is then used to login to the application. So, you need to use `.DbMigrator` at least once for a new database. + +{{ end }} + +## Run the Application + +{{ if UI == "MVC" }} + +{{ if Tiered == "Yes" }} + +> Tiered solutions use **Redis** as the distributed cache. Ensure that it is installed and running in your local computer. If you are using a remote Redis Server, set the configuration in the `appsettings.json` files of the projects below. + +1. Ensure that the `.IdentityServer` project is the startup project. Run this application that will open a **login** page in your browser. + +> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. + +You can login, but you cannot enter to the main application here. This is **just the authentication server**. + +2. Ensure that the `.HttpApi.Host` project is the startup project and run the application which will open a **Swagger UI** in your browser. + +![swagger-ui](images/swagger-ui.png) + +This is the HTTP API that is used by the web application. + +3. Lastly, ensure that the `.Web` project is the startup project and run the application which will open a **welcome** page in your browser + +![mvc-tiered-app-home](images/bookstore-home.png) + +Click to the **login** button which will redirect you to the *authentication server* to login to the application: + +![bookstore-login](images/bookstore-login.png) + +{{ else # Tiered != "Yes" }} + +Ensure that the `.Web` project is the startup project. Run the application which will open the **login** page in your browser: + +> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. + +![bookstore-login](images/bookstore-login.png) + +{{ end # Tiered }} + +{{ else # UI != "MVC" }} + +### Running the HTTP API Host (Server Side) + +{{ if Tiered == "Yes" }} + +> Tiered solutions use Redis as the distributed cache. Ensure that it is installed and running in your local computer. If you are using a remote Redis Server, set the configuration in the `appsettings.json` files of the projects below. + +Ensure that the `.IdentityServer` project is the startup project. Run the application which will open a **login** page in your browser. + +> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. + +You can login, but you cannot enter to the main application here. This is just the authentication server. + +Ensure that the `.HttpApi.Host` project is the startup project and run the application which will open a Swagger UI: + +{{ else # Tiered == "No" }} + +Ensure that the `.HttpApi.Host` project is the startup project and run the application which will open a Swagger UI: + +> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. + +{{ end # Tiered }} + +![swagger-ui](images/swagger-ui.png) + +You can see the application APIs and test them here. Get [more info](https://swagger.io/tools/swagger-ui/) about the Swagger UI. + +{{ end # UI }} + +{{ if UI == "Blazor" }} + +### Running the Blazor Application (Client Side) + +Ensure that the `.Blazor` project is the startup project and run the application. + +> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. + +Once the application starts, click to the **Login** link on to header, which redirects you to the authentication server to enter a username and password: + +![bookstore-login](images/bookstore-login.png) + +{{ else if UI == "NG" }} + +### Running the Angular Application (Client Side) + +Go to the `angular` folder, open a command line terminal, type the `yarn` command (we suggest to the [yarn](https://yarnpkg.com/) package manager while `npm install` will also work) + +```bash +yarn +``` + +Once all node modules are loaded, execute `yarn start` (or `npm start`) command: + +```bash +yarn start +``` + +It may take a longer time for the first build. Once it finishes, it opens the Angular UI in your default browser with the [localhost:4200](http://localhost:4200/) address. + +![bookstore-login](images/bookstore-login.png) + +{{ end }} + +Enter **admin** as the username and **1q2w3E*** as the password to login to the application. The application is up and running. You can start developing your application based on this startup template. + +## Mobile Development + +If you want to include a [React Native](https://reactnative.dev/) project in your solution, add `-m react-native` (or `--mobile react-native`) argument to project creation command. This is a basic React Native startup template to develop mobile applications integrated to your ABP based backends. + +See the [Getting Started with the React Native](Getting-Started-React-Native.md) document to learn how to configure and run the React Native application. + +## See Also + +* [Web Application Development Tutorial](Tutorials/Part-1.md) +* [Application Startup Template](Startup-Templates/Application.md) diff --git a/docs/en/Getting-Started-Setup-Environment.md b/docs/en/Getting-Started-Setup-Environment.md new file mode 100644 index 0000000000..39a82076eb --- /dev/null +++ b/docs/en/Getting-Started-Setup-Environment.md @@ -0,0 +1,56 @@ +# Getting Started + +````json +//[doc-params] +{ + "UI": ["MVC", "Blazor", "NG"], + "DB": ["EF", "Mongo"], + "Tiered": ["Yes", "No"] +} +```` + +> This document assumes that you prefer to use **{{ UI_Value }}** as the UI framework and **{{ DB_Value }}** as the database provider. For other options, please change the preference on top of this document. + +## Setup Your Development Environment + +First things first! Let's setup your development environment before creating the project. + +### Pre-Requirements + +The following tools should be installed on your development machine: + +* [Visual Studio 2019](https://visualstudio.microsoft.com/vs/) (v16.8+) for Windows / [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/). [1](#f-editor) +* [.NET Core 5.0+](https://www.microsoft.com/net/download/dotnet-core/) +{{ if UI != "Blazor" }} +* [Node v12 or v14](https://nodejs.org/) +* [Yarn v1.20+ (not v2)](https://classic.yarnpkg.com/en/docs/install) [2](#f-yarn) or npm v6+ (already installed with Node) +{{ end }} +{{ if Tiered == "Yes" }} +* [Redis](https://redis.io/) (the startup solution uses the Redis as the [distributed cache](Caching.md)). +{{ end }} + +1 _You can use another editor instead of Visual Studio as long as it supports .NET Core and ASP.NET Core._ [↩](#a-editor) + +{{ if UI != "Blazor" }} + +2 _Yarn v2 works differently and is not supported._ [↩](#a-yarn) + +{{ end }} + +### Install the ABP CLI + +[ABP CLI](./CLI.md) is a command line interface that is used to automate some common tasks for ABP based solutions. First, you need to install the ABP CLI using the following command: + +````shell +dotnet tool install -g Volo.Abp.Cli +```` + +If you've already installed, you can update it using the following command: + +````shell +dotnet tool update -g Volo.Abp.Cli +```` + +## Next Step + +* [Creating a new solution](Getting-Started-Create-Solution.md) \ No newline at end of file diff --git a/docs/en/Getting-Started.md b/docs/en/Getting-Started.md index 1e473b266f..ddafff38e4 100644 --- a/docs/en/Getting-Started.md +++ b/docs/en/Getting-Started.md @@ -9,303 +9,12 @@ } ```` -This tutorial explains how to create a new web application using the [application startup template](Startup-Templates/Application.md). - > This document assumes that you prefer to use **{{ UI_Value }}** as the UI framework and **{{ DB_Value }}** as the database provider. For other options, please change the preference on top of this document. +## Contents -## Setup Your Development Environment - -First things first! Let's setup your development environment before creating the first project. - -### Pre-Requirements - -The following tools should be installed on your development machine: - -* [Visual Studio 2019](https://visualstudio.microsoft.com/vs/) for Windows / [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/). [1](#f-editor) -* [.NET Core 3.1+](https://www.microsoft.com/net/download/dotnet-core/) - -* [Node v12 or v14](https://nodejs.org/) -* [Yarn v1.20+ (not v2)](https://classic.yarnpkg.com/en/docs/install) [2](#f-yarn) or npm v6+ (already installed with Node) -{{ if Tiered == "Yes" }} - -* [Redis](https://redis.io/) (the startup solution uses the Redis as the [distributed cache](Caching.md)). - -{{ end }} - -1 _You can use another editor instead of Visual Studio as long as it supports .NET Core and ASP.NET Core._ [↩](#a-editor) - -2 _Yarn v2 works differently and is not supported._ [↩](#a-yarn) - -### Install the ABP CLI - -[ABP CLI](./CLI.md) is a command line interface that is used to automate some common tasks for ABP based solutions. - -> ABP CLI is a free & open source tool for the ABP framework. - -First, you need to install the ABP CLI using the following command: - -````shell -dotnet tool install -g Volo.Abp.Cli -```` - -If you've already installed, you can update it using the following command: - -````shell -dotnet tool update -g Volo.Abp.Cli -```` - -## Create a New Project - -Use the `new` command of the ABP CLI to create a new project: - -````shell -abp new Acme.BookStore{{if UI == "NG"}} -u angular{{else if UI == "Blazor"}} -u blazor{{end}}{{if DB == "Mongo"}} -d mongodb{{end}}{{if Tiered == "Yes"}}{{if UI == "MVC"}} --tiered{{else}} --separate-identity-server{{end}}{{end}} -```` - -> You can use different level of namespaces; e.g. BookStore, Acme.BookStore or Acme.Retail.BookStore. - -> Alternatively, you can select the "Direct Download" tab from the [ABP Framework web site](https://abp.io/get-started) to create a new solution. - -{{ if Tiered == "Yes" }} - -{{ if UI == "MVC" }} - -* `--tiered` argument is used to create N-tiered solution where authentication server, UI and API layers are physically separated. - -{{ else }} - -* `--separate-identity-server` argument is used to separate the identity server application from the API host application. If not specified, you will have a single endpoint on the server. - -{{ end }} - -{{ end }} - -### ABP CLI Commands & Options - -[ABP CLI document](./CLI.md) covers all of the available commands and options for the ABP CLI. This document uses the [application startup template](Startup-Templates/Application.md) to create a new web application. See the [ABP Startup Templates](Startup-Templates/Index.md) document for other templates. - -### The Solution Structure - -The solution has a layered structure (based on the [Domain Driven Design](Domain-Driven-Design.md)) and contains unit & integration test projects. See the [application template document](Startup-Templates/Application.md) to understand the solution structure in details. - -{{ if DB == "Mongo" }} - -#### MongoDB Transactions - -The [startup template](Startup-templates/Index.md) **disables** transactions in the `.MongoDB` project by default. If your MongoDB server supports transactions, you can enable the it in the *YourProjectMongoDbModule* class: - - ```csharp - Configure(options => - { - options.TransactionBehavior = UnitOfWorkTransactionBehavior.Auto; - }); - ``` - -> Or you can delete this code since this is already the default behavior. - -{{ end }} - -## Create the Database - -### Connection String - -Check the **connection string** in the `appsettings.json` file under the {{if Tiered == "Yes"}}`.IdentityServer` and `.HttpApi.Host` projects{{else}}{{if UI=="MVC"}}`.Web` project{{else}}`.HttpApi.Host` project{{end}}{{end}} - -{{ if DB == "EF" }} - -````json -"ConnectionStrings": { - "Default": "Server=localhost;Database=BookStore;Trusted_Connection=True" -} -```` - -The solution is configured to use **Entity Framework Core** with **MS SQL Server** by default. EF Core supports [various](https://docs.microsoft.com/en-us/ef/core/providers/) database providers, so you can use any supported DBMS. See [the Entity Framework integration document](Entity-Framework-Core.md) to learn how to [switch to another DBMS](Entity-Framework-Core-Other-DBMS.md). - -### Apply the Migrations - -The solution uses the [Entity Framework Core Code First Migrations](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli). So, you need to apply migrations to create the database. There are two ways of applying the database migrations. - -#### Apply Migrations Using the DbMigrator - -The solution comes with a `.DbMigrator` console application which applies migrations and also **seeds the initial data**. It is useful on **development** as well as on **production** environment. - -> `.DbMigrator` project has its own `appsettings.json`. So, if you have changed the connection string above, you should also change this one. - -Right click to the `.DbMigrator` project and select **Set as StartUp Project** - -![set-as-startup-project](images/set-as-startup-project.png) - - Hit F5 (or Ctrl+F5) to run the application. It will have an output like shown below: - - ![db-migrator-output](images/db-migrator-output.png) - -> Initial [seed data](Data-Seeding.md) creates the `admin` user in the database (with the password is `1q2w3E*`) which is then used to login to the application. So, you need to use `.DbMigrator` at least once for a new database. - -#### Using EF Core Update-Database Command - -Ef Core has `Update-Database` command which creates database if necessary and applies pending migrations. - -{{ if UI == "MVC" }} - -Right click to the {{if Tiered == "Yes"}}`.IdentityServer`{{else}}`.Web`{{end}} project and select **Set as StartUp project**: - -{{ else if UI != "MVC" }} - -Right click to the `.HttpApi.Host` project and select **Set as StartUp Project**: - -{{ end }} - -![set-as-startup-project](images/set-as-startup-project.png) - -Open the **Package Manager Console**, select `.EntityFrameworkCore.DbMigrations` project as the **Default Project** and run the `Update-Database` command: - -![package-manager-console-update-database](images/package-manager-console-update-database.png) - -This will create a new database based on the configured connection string. - -> **Using the `.DbMigrator` tool is the suggested way**, because it also seeds the initial data to be able to properly run the web application. -> -> If you just use the `Update-Database` command, you will have an empty database, so you can not login to the application since there is no initial admin user in the database. You can use the `Update-Database` command in development time when you don't need to seed the database. However, using the `.DbMigrator` application is easier and you can always use it to migrate the schema and seed the database. - -{{ else if DB == "Mongo" }} - -````json -"ConnectionStrings": { - "Default": "mongodb://localhost:27017/BookStore" -} -```` - -The solution is configured to use **MongoDB** in your local computer, so you need to have a MongoDB server instance up and running or change the connection string to another MongoDB server. - -### Seed Initial Data - -The solution comes with a `.DbMigrator` console application which **seeds the initial data**. It is useful on **development** as well as on **production** environment. - -> `.DbMigrator` project has its own `appsettings.json`. So, if you have changed the connection string above, you should also change this one. - -Right click to the `.DbMigrator` project and select **Set as StartUp Project** - -![set-as-startup-project](images/set-as-startup-project.png) - - Hit F5 (or Ctrl+F5) to run the application. It will have an output like shown below: - - ![db-migrator-output](images/db-migrator-output.png) - -> Initial [seed data](Data-Seeding.md) creates the `admin` user in the database (with the password is `1q2w3E*`) which is then used to login to the application. So, you need to use `.DbMigrator` at least once for a new database. - -{{ end }} - -## Run the Application - -{{ if UI == "MVC" }} - -{{ if Tiered == "Yes" }} - -1. Ensure that the `.IdentityServer` project is the startup project. Run this application that will open a **login** page in your browser. - -> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. - -You can login, but you cannot enter to the main application here. This is **just the authentication server**. - -2. Ensure that the `.HttpApi.Host` project is the startup project and run the application which will open a **Swagger UI** in your browser. - -![swagger-ui](images/swagger-ui.png) - -This is the HTTP API that is used by the web application. - -3. Lastly, ensure that the `.Web` project is the startup project and run the application which will open a **welcome** page in your browser - -![mvc-tiered-app-home](images/bookstore-home.png) - -Click to the **login** button which will redirect you to the *authentication server* to login to the application: - -![bookstore-login](images/bookstore-login.png) - -{{ else # Tiered != "Yes" }} - -Ensure that the `.Web` project is the startup project. Run the application which will open the **login** page in your browser: - -> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. - -![bookstore-login](images/bookstore-login.png) - -{{ end # Tiered }} - -{{ else # UI != "MVC" }} - -### Running the HTTP API Host (Server Side) - -{{ if Tiered == "Yes" }} - -Ensure that the `.IdentityServer` project is the startup project. Run the application which will open a **login** page in your browser. - -> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. - -You can login, but you cannot enter to the main application here. This is just the authentication server. - -Ensure that the `.HttpApi.Host` project is the startup project and run the application which will open a Swagger UI: - -{{ else # Tiered == "No" }} - -Ensure that the `.HttpApi.Host` project is the startup project and run the application which will open a Swagger UI: - -> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. - -{{ end # Tiered }} - -![swagger-ui](images/swagger-ui.png) - -You can see the application APIs and test them here. Get [more info](https://swagger.io/tools/swagger-ui/) about the Swagger UI. - -> ##### Authorization for the Swagger UI -> -> Most of the HTTP APIs require authentication & authorization. If you want to test authorized APIs, manually go to the `/Account/Login` page, enter `admin` as the username and `1q2w3E*` as the password to login to the application. Then you will be able to execute authorized APIs too. - -{{ end # UI }} - -{{ if UI == "Blazor" }} - -### Running the Blazor Application (Client Side) - -Ensure that the `.Blazor` project is the startup project and run the application. - -> Use Ctrl+F5 in Visual Studio (instead of F5) to run the application without debugging. If you don't have a debug purpose, this will be faster. - -Once the application starts, click to the **Login** link on to header, which redirects you to the authentication server to enter a username and password: - -![bookstore-login](images/bookstore-login.png) - -{{ else if UI == "NG" }} - -### Running the Angular Application (Client Side) - -Go to the `angular` folder, open a command line terminal, type the `yarn` command (we suggest to the [yarn](https://yarnpkg.com/) package manager while `npm install` will also work) - -```bash -yarn -``` - -Once all node modules are loaded, execute `yarn start` (or `npm start`) command: - -```bash -yarn start -``` - -It may take a longer time for the first build. Once it finishes, it opens the Angular UI in your default browser with the [localhost:4200](http://localhost:4200/) address. - -![bookstore-login](images/bookstore-login.png) - -{{ end }} - -Enter **admin** as the username and **1q2w3E*** as the password to login to the application. The application is up and running. You can start developing your application based on this startup template. - -## Mobile Development - -If you want to include a [React Native](https://reactnative.dev/) project in your solution, add `-m react-native` (or `--mobile react-native`) argument to project creation command. This is a basic React Native startup template to develop mobile applications integrated to your ABP based backends. - -See the [Getting Started with the React Native](Getting-Started-React-Native.md) document to learn how to configure and run the React Native application. - -## Next +This tutorial explains how to **create and run** a new web application using the ABP Framework. Follow the steps below; -* [Web Application Development Tutorial](Tutorials/Part-1.md) +1. [Setup your development environment](Getting-Started-Setup-Environment) +2. [Creating a new solution](Getting-Started-Create-Solution.md) +3. [Running the solution](Getting-Started-Running-Solution.md) \ No newline at end of file diff --git a/docs/en/Index.md b/docs/en/Index.md index 949c04eb24..95052add38 100644 --- a/docs/en/Index.md +++ b/docs/en/Index.md @@ -1,31 +1,73 @@ # ABP Documentation -ABP is an **open source application framework** focused on **ASP.NET Core** based **web application development**. It also supports developing other type of applications. - -Explore the navigation menu to deep dive in the documentation. +ABP Framework is a complete **infrastructure** based on the **ASP.NET Core** to create **modern web applications** and **APIs** by following the software development **best practices** and the **latest technologies**. ## Getting Started -The easiest way to start a new web application with the ABP Framework is to use the [getting started](Getting-Started.md) guide. +* [Getting Started Guide](Getting-Started.md) is the easiest way to start a new web application with the ABP Framework. +* [Web Application Development Tutorial](Tutorials/Part-1.md) is a complete tutorial to develop a full stack web application. -## Tutorials / Articles +### UI Framework Options -### Web Application Development + -[Web application development tutorial](Tutorials/Part-1.md) is a complete tutorial to develop a full stack application using the ABP Framework. +### Database Provider Options -### ABP Community Articles + -See also the [ABP Community](https://community.abp.io/) articles. +## Exploring the Documentation -## Samples +ABP has a **comprehensive documentation** that not only explains the ABP Framework, but also includes **guides** and **samples** to help you on creating a **maintainable solution** by introducing and discussing common **software development principle and best practices**. -See the [sample projects](Samples/Index.md) built with the ABP Framework. +### Architecture + +ABP offers a complete, modular and layered software architecture based on [Domain Driven Design](Domain-Driven-Design.md) principles and patterns. It also provides the necessary infrastructure to implement this architecture. + +* See the [Modularity](Module-Development-Basics.md) document to understand the module system. +* [Implementing Domain Driven Design](Domain-Driven-Design-Implementation-Guide.md) document is an ultimate guide for who want to understand and implement the DDD. +* [Microservice Architecture](Microservice-Architecture.md) document explains how ABP helps to create a microservice solution. + +### Infrastructure + +There are a lot of features provided by the ABP Framework to achieve real world scenarios easier, like [Event Bus](Event-Bus.md), [Background Job System](Background-Jobs.md), [Audit Logging](Audit-Logging.md), [BLOB Storing](Blob-Storing.md), [Data Seeding](Data-Seeding.md), [Data Filtering](Data-Filtering.md). + +### Cross Cutting Concerns + +ABP also simplifies (and even automates wherever possible) cross cutting concerns and common non-functional requirements like [Exception Handling](Exception-Handling.md), [Validation](Validation.md), [Authorization](Authorization.md), [Localization](Localization.md), [Caching](Caching.md), [Dependency Injection](Dependency-Injection.md), [Setting Management](Settings.md), etc. + +### Application Modules + +Application Modules provides pre-built application functionalities; + +* [**Account**](Modules/Account.md): Provides UI for the account management and allows user to login/register to the application. +* **[Identity](Modules/Identity.md)**: Manages organization units, roles, users and their permissions, based on the Microsoft Identity library. +* [**IdentityServer**](Modules/IdentityServer.md): Integrates to IdentityServer4. +* [**Tenant Management**](Modules/Tenant-Management.md): Manages tenants for a [multi-tenant](Multi-Tenancy.md) (SaaS) application. -## Source Code +See the [Application Modules](Modules/Index.md) document for all pre-built modules. + +### Startup Templates + +The [Startup templates](Startup-Templates/Index.md) are pre-built Visual Studio solution templates. You can create your own solution based on these templates to **immediately start your development**. + +## ABP Community + +### The Source Code ABP is hosted on GitHub. See [the source code](https://github.com/abpframework). -## Want to Contribute? +### ABP Community Web Site + +The [ABP Community](https://community.abp.io/) is a website to publish articles and share knowledge about the ABP Framework. You can also create content for the community! + +### Blog + +Follow the [ABP Blog](https://blog.abp.io/) to learn the latest happenings in the ABP Framework. + +### Samples + +See the [sample projects](Samples/Index.md) built with the ABP Framework. + +### Want to Contribute? ABP is a community-driven open source project. See [the contribution guide](Contribution/Index.md) if you want to be a part of this project. diff --git a/docs/en/Integration-Tests.md b/docs/en/Integration-Tests.md index f9f6830956..35d66171a6 100644 --- a/docs/en/Integration-Tests.md +++ b/docs/en/Integration-Tests.md @@ -1,3 +1 @@ -# Integration Tests - -TODO! \ No newline at end of file +This document has been [moved to here](Testing.md). \ No newline at end of file diff --git a/docs/en/JavaScript/Dynamic-JavaScript-API-Clients.md b/docs/en/JavaScript/Dynamic-JavaScript-API-Clients.md deleted file mode 100644 index 539d3ac15a..0000000000 --- a/docs/en/JavaScript/Dynamic-JavaScript-API-Clients.md +++ /dev/null @@ -1,3 +0,0 @@ -## Dynamic JavaScript API Clients - -TODO \ No newline at end of file diff --git a/docs/en/Localization.md b/docs/en/Localization.md index 37104a4878..089567422c 100644 --- a/docs/en/Localization.md +++ b/docs/en/Localization.md @@ -100,8 +100,6 @@ Configure(options => > The [application startup template](Startup-Templates/Application.md) sets `DefaultResourceType` to the localization resource of the application. -See the *Client Side* section below for a use case. - ### Short Localization Resource Name Localization resources are also available in the client (JavaScript) side. So, setting a short name for the localization resource makes it easy to use localization texts. Example: @@ -156,16 +154,16 @@ services.Configure(options => * If an extension file defines the same localized string, it overrides the string. -## Getting Localized Texts +## Getting the Localized Texts -### Server Side +Getting the localized text is pretty standard. -Getting the localized text on the server side is pretty standard. +### Simplest Usage In A Class -#### Simplest Usage In A Class +Just inject the `IStringLocalizer` service and use it like shown below: -````C# -public class MyService +````csharp +public class MyService : ITransientDependency { private readonly IStringLocalizer _localizer; @@ -183,9 +181,13 @@ public class MyService ##### Format Arguments -Format arguments can be passed after the localization key. If your message is `Hello {0}, welcome!`, then you can pass the `{0}` argument to the localizer like `_localizer["HelloMessage", "John"]` +Format arguments can be passed after the localization key. If your message is `Hello {0}, welcome!`, then you can pass the `{0}` argument to the localizer like `_localizer["HelloMessage", "John"]`. + +> Refer to the [Microsoft's localization documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization) for details about using the localization. -#### Simplest Usage In A Razor View/Page +### Using In A Razor View/Page + +Use `IHtmlLocalizer` in razor views/pages; ````c# @inject IHtmlLocalizer Localizer @@ -193,54 +195,59 @@ Format arguments can be passed after the localization key. If your message is `H

@Localizer["HelloWorld"]

```` -Refer to the [Microsoft's localization documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization) for details about using localization on the server side. - -### Client Side +### Special Base Classes -ABP provides JavaScript services to use the same localized texts in the client side. +Some ABP Framework base classes provide a `L` property to use the localizer even easier. -#### getResource +**Example: Localize a text in an application service method** -`abp.localization.getResource` function is used to get a localization resource: - -````js -var testResource = abp.localization.getResource('Test'); -```` +```csharp +using System.Threading.Tasks; +using MyProject.Localization; +using Volo.Abp.Application.Services; -Then you can localize a string based on this resource: - -````js -var str = testResource('HelloWorld'); -```` - -#### localize - -`abp.localization.localize` function is a shortcut where you can both specify the text name and the resource name: - -````js -var str = abp.localization.localize('HelloWorld', 'Test'); -```` +namespace MyProject +{ + public class TestAppService : ApplicationService + { + public TestAppService() + { + LocalizationResource = typeof(MyProjectResource); + } -`HelloWorld` is the text to localize, where `Test` is the localization resource name here. + public async Task DoIt() + { + var str = L["HelloWorld"]; + } + } +} +``` -If you don't specify the localization resource name, it uses the default localization resource defined on the `AbpLocalizationOptions` (see the *Default Resource* section above). Example: +When you set the `LocalizationResource` in the constructor, the `ApplicationService` class uses that resource type when you use the `L` property, just like in the `DoIt()` method. -````js -var str = abp.localization.localize('HelloWorld'); //uses the default resource -```` +Setting `LocalizationResource` in every application service can be tedious. You can create an abstract base application service class, set it there and derive your application services from that base class. This is already implemented when you create a new project with the [startup templates](Startup-Templates/Application.md). So, you can simply inherit from the base class directly use the `L` property: -##### Format Arguments +```csharp +using System.Threading.Tasks; -If your localized string contains arguments, like `Hello {0}, welcome!`, you can pass arguments to the localization methods. Examples: +namespace MyProject +{ + public class TestAppService : MyProjectAppService + { + public async Task DoIt() + { + var str = L["HelloWorld"]; + } + } +} +``` -````js -var str1 = abp.localization.getResource('Test')('HelloWelcomeMessage', 'John'); -var str2 = abp.localization.localize('HelloWorld', 'Test', 'John'); -```` +The `L` property is also available for some other base classes like `AbpController` and `AbpPageModel`. -Both of the samples above produce the output `Hello John, welcome!`. +## The Client Side -## See Also +See the following documents to learn how to reuse the same localization texts in the JavaScript side; -* [Localization in Angular UI](UI/Angular/Localization.md) -* [Forms & Validation](UI/AspNetCore/Forms-Validation.md) for the ASP.NET Core MVC / Razor Pages UI \ No newline at end of file +* [Localization for the MVC / Razor Pages UI](UI/AspNetCore/JavaScript-API/Localization.md) +* [Localization for the Blazor UI](UI/Blazor/Localization.md) +* [Localization for the Angular UI](UI/Angular/Localization.md) \ No newline at end of file diff --git a/docs/en/Migration-Guides/Abp-4_0-Angular.md b/docs/en/Migration-Guides/Abp-4_0-Angular.md new file mode 100644 index 0000000000..6095a0f447 --- /dev/null +++ b/docs/en/Migration-Guides/Abp-4_0-Angular.md @@ -0,0 +1,121 @@ +# Angular UI 3.3 to 4.0 Migration Guide + +## Angular v11 + +The new ABP Angular UI is based on Angular v11 and TypeScript v4. The difference between v10 and v11 is non-breaking so you do not have to update right away but it is recommended. Nevertheless, ABP modules will keep working with Angular v10. Therefore, if your project is Angular v10, you do not need to update to Angular 11. The update is usually very easy though. + +You can read more about Angular v11 [here](https://blog.angular.io/version-11-of-angular-now-available-74721b7952f7) + +## **Breaking Changes** + +### **Localization** + +Prior to ABP 4.x, we'd handled what locale files of Angular should be created to load them lazily. However, this made it impossible to add new locale files (to be lazily loaded) for our users. With ABP 4.x, we enabled an option to pass a function to `CoreModule`. + +The quickest solution is as follows: + +```typescript +// app.module.ts + +import { registerLocale } from '@abp/ng.core/locale'; +// or +// import { registerLocale } from '@volo/abp.ng.language-management/locale'; +// if you have commercial license + + +@NgModule({ +imports: [ + // ... + CoreModule.forRoot({ + // ...other options, + registerLocaleFn: registerLocale() + }), + //... +] +export class AppModule {} +``` + +You can find the related issue [here](https://github.com/abpframework/abp/issues/6066) +Also, please refer to [the docs](https://docs.abp.io/en/abp/latest/UI/Angular/Localization#registering-a-new-locale) for more information. + +### **Removed the Angular Account Module Public UI** + +With ABP 4.x, we have retired `@abp/ng.account`, it is no longer a part of our framework. There won't be any newer versions of this package as well. Therefore, you can delete anything related to this package. +There should be a config in `app-routing.module` for path `account` and `AccountConfigModule` import in `app.module` + +However, if you are using the commercial version of this package, a.k.a `@volo/abp.ng.account`, this package will continue to exist because it contains `AccountAdminModule` which is still being maintained and developed. You only need to delete the route config from `app-routing.module` + +You can find the related issue [here](https://github.com/abpframework/abp/issues/5652) + +Angular UI is using the Authorization Code Flow to authenticate since version 3.1.0 by default. Starting from version 4.0, this is becoming the only option, because it is the recommended way of authenticating SPAs. + +If you haven't done it yet, see [this post](https://blog.abp.io/abp/ABP-Framework-v3.1-RC-Has-Been-Released) to change the authentication of your application. + +### State Management + +In the ABP Angular UI, we've been using `NGXS` for state management. However, we've decided that the Angular UI should be agnostic with regard to state management. Our users should be able to handle the state in any way they prefer. They should be able to use any library other than `NGXS` or no library at all. That's why we have created our internal store in version 3.2. It is a simple utility class that employs `BehaviorSubject` internally. + +You can examine it [here](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/utils/internal-store-utils.ts) + +With version 4.0, we will keep utilizing our `InternalStore` instead of `@ngxs/store` in our services and move away from `@ngxs/store`. We plan to remove any dependency of `NGXS` by version 5.0. + +With this in mind, we've already deprecated some services and implemented some breaking changes. + +#### Removed the `SessionState` + +Use `SessionStateService` instead of the `SessionState`. See [this issue](https://github.com/abpframework/abp/issues/5606) for details. + +#### Deprecated the `ConfigState` + +`ConfigState` is now deprecated and should not be used. + +`ConfigState` reference removed from `CoreModule`. If you want to use the `ConfigState` (not recommended), you should pass the state to `NgxsModule` as shown below: + +```typescript +//app.module.ts + +import { ConfigState } from '@abp/ng.core'; + +// ... + +imports: [ + NgxsModule.forRoot([ConfigState]), +// ... +``` + +Moving away from the global store, we create small services with a single responsibility. There are two new services available in version 4.0 which are `EnvironmentService` and `PermissionService`. + +See [the related issue](https://github.com/abpframework/abp/issues/6154) + +Please refer to the following docs for detail information and examples +- [`ConfigStateService`](../UI/Angular/Config-State-Service) +- [`EnvironmentService`](../UI/Angular/Environment#EnvironmentService) +- [`PermissionService`](../UI/Angular/Permission-Management#) + +### Deprecated Interfaces + + Some interfaces have long been marked as deprecated and now they are removed. + +- Removed replaceable components state. +- Removed legacy identity types and service. +- Removed legacy tenant management types and service. +- Removed legacy feature management types and services. +- Removed legacy permission management types and service. + +### Deprecated commercial interfaces +- Removed legacy audit logging types and services. +- Removed legacy identity types and services. +- Removed legacy language management types and services. +- Removed legacy saas types and services. + +### Identity Server [COMMERCIAL] + +With the new version of Identity Server, there happened some breaking changes in the backend (also in the database). We've implemented those in the Angular UI. +If you are just using the package `@volo/abp.ng.identity-server` as is, you will not need to do anything. +However, there are a couple of breaking changes we need to mention. + +- As we have stated above, we want to remove the dependency of `NGXS`. Thus, we have deleted all of the actions defined in `identity-server.actions`. Those actions are not needed anymore and the state is managed locally. With the actions gone, `IdentityServerStateService` became unused and got deleted as well. + +- `ApiScope` is also available as a new entity (It was part of `ApiResource` before). It provides tokens for entity prop, entity actions, toolbar, edit and create form contributors like the existing ones which are `Client`, `IdentityResource` and `ApiResource` + +- There were some deprecated interfaces within the `IdentityServer` namespace. Those are no longer being used, instead, their replacements were generated by `ABP Cli` using the `generate-proxy` command. diff --git a/docs/en/Migration-Guides/Abp-4_0-Blazor.md b/docs/en/Migration-Guides/Abp-4_0-Blazor.md new file mode 100644 index 0000000000..90a9bc2e53 --- /dev/null +++ b/docs/en/Migration-Guides/Abp-4_0-Blazor.md @@ -0,0 +1,88 @@ +# Blazor UI 3.3 to 4.0 Migration Guide + +## Startup Template Changes + +These changes are required to manually applied in your own solution. It would be easier if you create a new solution based on 4.0 with the same name of your current solution then compare the files. + +### Csproj File / Dependencies + +* Add `true` to the `PropertyGroup` section of your project (`.csproj`) file. +* Update the `Blazorise.*` packages to the latest version (to the latest RC for the ABP 4.0 preview). + +### wwwroot/index.html + +There are some changes made in the index.html file; + +* Removed JQuery & Bootstrap JavaScript dependencies +* Replaced Bootstrap and FontAwesome imports with local files instead of CDN usages. +* Re-arranged some ABP CSS file locations. +* Introduced the `abp bundle` CLI command to manage global Style/Script file imports. + +Follow the steps below to apply the changes; + +1. Add the bundle contributor class into your project (it will be slightly different based on your solution namespaces): + +````csharp +using Volo.Abp.Bundling; + +namespace MyCompanyName.MyProjectName.Blazor +{ + public class MyProjectNameBundleContributor : IBundleContributor + { + public void AddScripts(BundleContext context) + { + } + + public void AddStyles(BundleContext context) + { + context.Add("main.css"); + } + } +} +```` + +If you are using another global style/script files, add them here. + +2. Remove all the `` elements and replace with the following comment tags: + +````html + + +```` + +3. Remove all the `` elements and replace with the following comment tags: + +````html + + +```` + +4. Execute the following command in a terminal in the root folder of the Blazor project (`.csproj`) file (ensure that you're using the ABP CLI version 4.0): + +````bash +abp bundle +```` + +This will fill in the `Styles` and `Scripts` tags based on the dependencies. + +5. You can clean the `blazor-error-ui` related sections from your `main.css` file since they are not needed anymore. + +### The Root Element + +This change is optional but recommended. + +* Change `...` to `
...
` in the `wwwroot/index.html`. +* Change `builder.RootComponents.Add("app");` to `builder.RootComponents.Add("#ApplicationContainer");` in the *YourProjectBlazorModule.cs*. + +## AbpCrudPageBase Changes + +If you've derived your pages from the `AbpCrudPageBase` class, then you may need to apply the following changes; + +- `OpenEditModalAsync` method gets `EntityDto` instead of id (`Guid`) parameter. Pass `context` instead of `context.Id`. +- `DeleteEntityAsync` method doesn't display confirmation dialog anymore. You can use the new `EntityActions` component in Data Grids to show confirmation messages. You can also inject `IUiMessageService` to your page or component and call the `ConfirmAsync` explicitly. +- Added `GetListInput` as a base property that is used to filter while getting the entities from the server. + +## Others + +- Refactored namespaces for some Blazor components ([#6015](https://github.com/abpframework/abp/issues/6015)). +- Removed Async Suffix from IUiMessageService methods ([#6123](https://github.com/abpframework/abp/pull/6123)). \ No newline at end of file diff --git a/docs/en/Migration-Guides/Abp-4_0-MVC-Razor-Pages.md b/docs/en/Migration-Guides/Abp-4_0-MVC-Razor-Pages.md new file mode 100644 index 0000000000..d2fa97ec5e --- /dev/null +++ b/docs/en/Migration-Guides/Abp-4_0-MVC-Razor-Pages.md @@ -0,0 +1,6 @@ +# MVC / Razor Pages UI 3.3 to 4.0 Migration Guide + +## Use IBrandingProvider in the Volo.Abp.UI Package + +This will be a breaking change for MVC UI, but very easy to fix. `IBrandingProvider` is being moved from `Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Components` to `Volo.Abp.Ui.Branding` namespace. So, just update the namespace imports. + diff --git a/docs/en/Migration-Guides/Abp-4_0.md b/docs/en/Migration-Guides/Abp-4_0.md new file mode 100644 index 0000000000..9e1bd4e816 --- /dev/null +++ b/docs/en/Migration-Guides/Abp-4_0.md @@ -0,0 +1,280 @@ +# ABP Framework 3.3 to 4.0 Migration Guide + +This document introduces the breaking changes done in the ABP Framework 4.0 and explains how to fix your 3.x based solutions while upgrading to the ABP Framework 4.0. + +> See [the blog post](https://blog.abp.io/abp/ABP.IO-Platform-v4.0-RC-Has-Been-Released-based-on-.NET-5.0) to learn what's new with the ABP Framework 4.0. This document only focuses on the breaking changes. + +## Overall + +Here, the overall list of the changes; + +* Upgraded to the .NET 5.0 [(#6118](https://github.com/abpframework/abp/issues/6118)). +* Moved from Newtonsoft.Json to System.Text.Json [(#1198](https://github.com/abpframework/abp/issues/1198)). +* Upgraded to the Identity Server 4.1.1 ([#4461](https://github.com/abpframework/abp/issues/4461)). +* Switched to `kebab-case` for conventional URLs for the auto API controller routes ([#5325](https://github.com/abpframework/abp/issues/5325)). +* Removed Retry for the Dynamic HTTP Client Proxies ([#6090](https://github.com/abpframework/abp/issues/6090)). +* Creation audit properties of the entities made read-only ([#6020](https://github.com/abpframework/abp/issues/6020)). +* Changed type of the IHasExtraProperties.ExtraProperties ([#3751](https://github.com/abpframework/abp/issues/3751)). +* Use IBrandingProvider in the Volo.Abp.UI package and remove the one in the Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared ([#5375](https://github.com/abpframework/abp/issues/5375)). +* Removed the Angular Account Module Public UI (login, register... pages) since they are not being used in the default (authorization code) flow ([#5652](https://github.com/abpframework/abp/issues/5652)). +* Removed the SessionState in the @abp/ng.core package ([#5606](https://github.com/abpframework/abp/issues/5606)). +* Made some API revisions & startup template changes for the Blazor UI. + +## Upgraded to .NET 5.0 + +ABP Framework has been moved to .NET 5.0. So, if you want to upgrade to the ABP Framework 4.0, you also need to upgrade to .NET 5.0. + +See the [Migrate from ASP.NET Core 3.1 to 5.0](https://docs.microsoft.com/en-us/aspnet/core/migration/31-to-50) document to learn how to upgrade your solution to .NET 5.0. + +## Moved to System.Text.Json + +ABP Framework 4.0 uses the System.Text.Json by default as the JSON serialization library. It, actually, using a hybrid approach: Continues to use the Newtonsoft.Json when it needs to use features not supported by the System.Text.Json. + +### Unsupported Types + +If you want to use the Newtonsoft.Json to serialize/deserialize for some specific types, you can configure the `AbpSystemTextJsonSerializerOptions` in your module's `ConfigureServices` method. + +**Example: Use Newtonsoft.Json for `MySpecialClass`** + +````csharp +Configure(options => +{ + options.UnsupportedTypes.AddIfNotContains(typeof(MySpecialClass)); +}); +```` + +### Always Use the Newtonsoft.Json + +If you want to continue to use the Newtonsoft.Json library for all the types, you can set `UseHybridSerializer` to false in the `PreConfigureServices` method of your module class: + +````csharp +PreConfigure(options => +{ + options.UseHybridSerializer = false; +}); +```` + +## Upgraded to Identity Server 4.1.1 + +ABP Framework upgrades the [IdentityServer4](https://www.nuget.org/packages/IdentityServer4) library from 3.x to 4.1.1 with the ABP Framework version 4.0. IdentityServer 4.x has a lot of changes. Some of them are **breaking changes in the data structure**. + +### Entity Changes + +Entity changes don't directly affect your application; however, it is good to know. + +#### ApiScope + +As the **most critical breaking change**; Identity Server 4.x defines the `ApiScope` as an independent aggregate root. Previously, it was the child entity of the `ApiResource`. This change requires manual operation. See the _Database Changes_ section. + +Also, added `Enabled(string)` and `Description(bool,true)` properties. + +#### ApiResource + +- Added `AllowedAccessTokenSigningAlgorithms (string)` and `ShowInDiscoveryDocument(bool, default: true)` properties + +#### Client + +- Added `RequireRequestObject ` and `AllowedIdentityTokenSigningAlgorithms ` properties. +- Changed the default value of `RequireConsent` from `true` to `false`. +- Changed the default value of `RequirePkce` from `false` to `true`. + +#### DeviceFlowCodes + +- Added `SessionId ` and `Description ` properties. + +#### PersistedGrant + +- Added `SessionId `, `Description ` and `ConsumedTime ` properties + +### Database Changes + +> Attention: **Please backup your database** before the migration! + +**If you are upgrading from 3.x, then there are some steps should be done in your database.** + +#### Database Schema Migration + +If you are using **Entity Framework Core**, you need to add a new database migration, using the `Add-Migration` command, and apply changes to the database. Please **review the migration** script and read the sections below to understand if it affects your existing data. Otherwise, you may **lose some of your configuration**, which may not be easy to remember and re-configure. + +#### Seed Code + +If you haven't customized the `IdentityServerDataSeedContributor` and haven't customized the initial data inside the `IdentityServer*` tables; + +1. Update `IdentityServerDataSeedContributor` class by comparing to [the latest code](https://github.com/abpframework/abp/blob/dev/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain/IdentityServer/IdentityServerDataSeedContributor.cs). You probably only need to add the `CreateApiScopesAsync` method and the code related to it. +2. Then you can simply clear all the **data** in these tables then execute the `DbMigrator` application to fill it with the new configuration. + +#### Migrating the Configuration Data + +If you've customized your IdentityServer configuration in the database or in the seed data, you should understand the changes and upgrade your code/data accordingly. Especially, the following changes will affect your application: + +- `IdentityServerApiScopes` table's `Enabled` field is dropped and re-created. So, you need to enable the API scopes again manually. +- `IdentityServerApiResourceScopes` table is dropped and recreated. So, you need to backup and move your current data to the new table. +- `IdentityServerIdentityResourceClaims` table is dropped and recreated. So, you need to backup and move your current data to the new table. + +You may need to perform additional steps based on how much you made custom configurations. + +### Other IdentityServer Changes + +IdentityServer has removed the [public origin option](https://github.com/IdentityServer/IdentityServer4/pull/4335). It was resolving HTTP/HTTPS conversion issues, but they decided to leave this to the developer. This is especially needed if you use a reverse proxy where your external protocol is HTTPS but internal protocol is HTTP. + +One simple solution is to add such a middleware at the begingning of your ASP.NET Core pipeline. + +```csharp +app.Use((httpContext, next) => +{ + httpContext.Request.Scheme = "https"; + return next(); +}); +``` + +> This sample is obtained from the [ASP.NET Core documentation](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer#scenarios-and-use-cases). You can use it if you always use HTTPS in all environments. + +### Related Resources + +- https://leastprivilege.com/2020/06/19/announcing-identityserver4-v4-0/ +- https://github.com/IdentityServer/IdentityServer4/issues/4592 + +## Auto API Controller Route Changes + +The route calculation for the [Auto API Controllers](https://docs.abp.io/en/abp/latest/API/Auto-API-Controllers) is changing with the ABP Framework version 4.0 ([#5325](https://github.com/abpframework/abp/issues/5325)). Before v4.0 the route paths were **camelCase**. After version 4.0, it's changed to **kebab-case** route paths where it is possible. + +**A typical auto API before v4.0** + +![route-before-4](images/route-before-4.png) + +**camelCase route parts become kebab-case with 4.0** + +![route-4](images/route-4.png) + +### How to Fix? + +You may not take any action for the MVC & Blazor UI projects. + +For the Angular UI, this change may effect your client UI. If you have used the [ABP CLI Service Proxy Generation](../UI/Angular/Service-Proxies.md), you can run the server side and re-generate the service proxies. If you haven't used this tool, you should manually update the related URLs in your application. + +If there are other type of clients (e.g. 3rd-party companies) using your APIs, they also need to update the URLs. + +### Use the v3.x style URLs + +If it is hard to change it in your application, you can still to use the version 3.x route strategy, by following one of the approaches; + +- Set `UseV3UrlStyle` to `true` in the options of the `options.ConventionalControllers.Create(...)` method. Example: + +```csharp +options.ConventionalControllers + .Create(typeof(BookStoreApplicationModule).Assembly, opts => + { + opts.UseV3UrlStyle = true; + }); +``` + +This approach affects only the controllers for the `BookStoreApplicationModule`. + +- Set `UseV3UrlStyle` to `true` for the `AbpConventionalControllerOptions` to set it globally. Example: + +```csharp +Configure(options => +{ + options.UseV3UrlStyle = true; +}); +``` + +Setting it globally affects all the modules in a modular application. + +## Removed Retry for the Dynamic HTTP Client Proxies + +[Dynamic C# HTTP Client Proxies](../API/Dynamic-CSharp-API-Clients.md) were trying up to 3 times if a request fails using the [Polly](https://github.com/App-vNext/Polly) library. Starting from the version 4.0, this logic has been removed. If you need it, you should configure it in your own application, by configuring the `AbpHttpClientBuilderOptions` in the `PreConfigureServices` method of your module. + +**Example: Retry 3 times on failure by incremental waiting between tries** + +````csharp +public override void PreConfigureServices(ServiceConfigurationContext context) +{ + PreConfigure(options => + { + options.ProxyClientBuildActions.Add((remoteServiceName, clientBuilder) => + { + clientBuilder.AddTransientHttpErrorPolicy( + policyBuilder => policyBuilder + .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(Math.Pow(2, i))) + ); + }); + }); +} +```` + +This example uses the Microsoft.Extensions.Http.Polly NuGet package. + +If you create a new solution, you can find the same configuration in the `.HttpApi.Client.ConsoleTestApp` project's module class, as an example. + +## Creation Audit Properties Made Read-Only + +Removed setters from the `IHasCreationTime.CreationTime`, ` IMustHaveCreator.CreatorId` and `IMayHaveCreator.CreatorId` properties to accidently set the creation properties while updating an existing entity. + +Since the ABP Framework automatically sets these properties, you normally don't need to directly set them. If you want to set them, as a best practice, it is suggested to make it in the constructor to not provide a way to change it later. + +These properties implemented with `protected set` in the `Entity` and `AggregateRoot` base classes. That means you can still set in a derived class, if you need it. Alternatively, you can use reflection to set them (Or use `ObjectHelper.TrySetProperty` which internally uses reflection) out of the class if you have to do. + +## Changed type of the IHasExtraProperties.ExtraProperties + +`IHasExtraProperties.ExtraProperties` was a regular `Dictionary`. With the version 4.0, it is replaced with `ExtraPropertyDictionary` class which inherits the `Dictionary`. + +Most of the applications don't be affected by this change. If you've directly implemented this interface, replace the standard dictionary to the `ExtraPropertyDictionary`. + +## Other Changes + +### IdentityOptions Usage + +Previously, when you inject `IOptions`, you get a dynamically overridden options value. For example, when you get `IdentityOptions.Password.RequiredLength`, the value is being changed based on the setting (`IdentitySettingNames.Password.RequiredLength`) of the current tenant. That means `IdentityOptions` changes per tenant. However, this caused an [issue](https://github.com/abpframework/abp/issues/6318) and we [had to change](https://github.com/abpframework/abp/pull/6333) the usage. + +With the version 4.0, you need to inject `IOptions` and call the new `SetAsync` method before using it, to be able to override the options by the settings. Otherwise, you get the default (statically configured) values of the options. + +Example usage: + +````csharp +public class MyService : ITransientDependency +{ + private readonly IOptions _options; + + public MyService(IOptions options) + { + _options = options; + } + + public async Task DoItAsync() + { + await _options.SetAsync(); + + var requiredLength = _options.Value.Password.RequiredLength; + } +} +```` + +Pre-built modules already handles this. However, if you have used `IdentityOptions` directly in your code, you also need to follow this new pattern. +Please make sure that the injected `IOptions` service and the service consuming it are in the same scope of dependency injection container. + +### LDAP module full async + +In order to solve the problem of async over sync, `ILdapManager` uses async method instead of sync. And use [`ldap4net`](https://github.com/flamencist/ldap4net) to replace [`Novell.Directory.Ldap.NETStandard`](https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard) package. + +### Dynamic external login provider system + +You need to change the `WithDynamicOptions` method and pass the `Handler` class of the external login provider. +Use the `goto definition` function in Visual Studio or Rider to check `Handler` in the extension method like `AddGoogle`. + +```csharp +- WithDynamicOptions() ++ WithDynamicOptions() +```` + +## ASP.NET Core MVC / Razor Pages UI + +See the [ASP.NET Core MVC / Razor Pages UI Migration Guide](Abp-4_0-MVC-Razor-Pages.md). + +## Angular UI + +See the [Angular UI Migration Guide](Abp-4_0-Angular.md). + +## Blazor UI + +See the [Blazor UI Migration Guide](Abp-4_0-Blazor.md). diff --git a/docs/en/Migration-Guides/BlazorUI-3_3.md b/docs/en/Migration-Guides/BlazorUI-3_3.md new file mode 100644 index 0000000000..bb3d07f615 --- /dev/null +++ b/docs/en/Migration-Guides/BlazorUI-3_3.md @@ -0,0 +1,14 @@ +# Migration Guide for the Blazor UI from the v3.2 to the v3.3 + +## Startup Template Changes + +* Remove `Volo.Abp.Account.Blazor` NuGet package from your `.Blazor.csproj` and add `Volo.Abp.TenantManagement.Blazor` NuGet package. +* Remove the ``typeof(AbpAccountBlazorModule)`` from the dependency list of *YourProjectBlazorModule* class and add the `typeof(AbpTenantManagementBlazorModule)`. +* Add `@using Volo.Abp.BlazoriseUI` and `@using Volo.Abp.BlazoriseUI.Components` into the `_Imports.razor` file. +* Remove the `div` with `id="blazor-error-ui"` (with its contents) from the `wwwroot/index.html ` file, since the ABP Framework now shows error messages as a better message box. +* Update the`AddOidcAuthentication` options in your *YourProjectBlazorModule* class as described in the issue [#5913](https://github.com/abpframework/abp/issues/5913). + +## BlazoriseCrudPageBase to AbpCrudPageBase + +Renamed `BlazoriseCrudPageBase` to `AbpCrudPageBase`. Just update the usages. It also has some changes, you may need to update method calls/usages manually. + diff --git a/docs/en/Migration-Guides/Index.md b/docs/en/Migration-Guides/Index.md new file mode 100644 index 0000000000..5973ee0a0d --- /dev/null +++ b/docs/en/Migration-Guides/Index.md @@ -0,0 +1,5 @@ +# ABP Framework Migration Guides + +* [3.3.x to 4.0 Migration Guide](Abp-4_0.md) +* [2.9.x to 3.0 Migration Guide](../UI/Angular/Migration-Guide-v3.md) + diff --git a/docs/en/Migration-Guides/images/route-4.png b/docs/en/Migration-Guides/images/route-4.png new file mode 100644 index 0000000000..0d57a57f3e Binary files /dev/null and b/docs/en/Migration-Guides/images/route-4.png differ diff --git a/docs/en/Migration-Guides/images/route-before-4.png b/docs/en/Migration-Guides/images/route-before-4.png new file mode 100644 index 0000000000..48d87c60c0 Binary files /dev/null and b/docs/en/Migration-Guides/images/route-before-4.png differ diff --git a/docs/en/Module-Development-Basics.md b/docs/en/Module-Development-Basics.md index e6f80233e4..4b76465a3e 100644 --- a/docs/en/Module-Development-Basics.md +++ b/docs/en/Module-Development-Basics.md @@ -57,7 +57,7 @@ public class BlogModule : AbpModule } ```` -See Configuration (TODO: link) document for more about the configuration system. +See the [Configuration](Configuration.md) document for more about the configuration system. #### Pre & Post Configure Services @@ -139,4 +139,4 @@ A depended module may depend on another module, but you only need to define your There are **two types of modules.** They don't have any structural difference but categorized by functionality and purpose: - **Framework modules**: These are **core modules of the framework** like caching, emailing, theming, security, serialization, validation, EF Core integration, MongoDB integration... etc. They do not have application/business functionalities but makes your daily development easier by providing common infrastructure, integration and abstractions. -- **Application modules**: These modules implement **specific application/business functionalities** like blogging, document management, identity management, tenant management... etc. They generally have their own entities, services, APIs and UI components. See [pre-built application modules](Modules/Index.md). \ No newline at end of file +- **Application modules**: These modules implement **specific application/business functionalities** like blogging, document management, identity management, tenant management... etc. They generally have their own entities, services, APIs and UI components. See [pre-built application modules](Modules/Index.md). diff --git a/docs/en/Modules/Account.md b/docs/en/Modules/Account.md index 6901b38f59..94cdb7af95 100644 --- a/docs/en/Modules/Account.md +++ b/docs/en/Modules/Account.md @@ -1,3 +1,38 @@ # Account Module -TODO \ No newline at end of file +This module provides necessary UI pages/components to make the user login and register to the application. + +> This document is incomplete. + +## Social/External Logins + +The [Account Module](../Modules/Account.md) has already configured to handle social or external logins out of the box. You can follow the ASP.NET Core documentation to add a social/external login provider to your application. + +### Example: Facebook Authentication + +Follow the [ASP.NET Core Facebook integration document](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins) to support the Facebook login for your application. + +#### Add the NuGet Package + +Add the [Microsoft.AspNetCore.Authentication.Facebook](https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.Facebook) package to your project. Based on your architecture, this can be `.Web`, `.IdentityServer` (for tiered setup) or `.Host` project. + +#### Configure the Provider + +Use the `.AddFacebook(...)` extension method in the `ConfigureServices` method of your [module](../Module-Development-Basics.md), to configure the client: + +````csharp +context.Services.AddAuthentication() + .AddFacebook(facebook => + { + facebook.AppId = "..."; + facebook.AppSecret = "..."; + facebook.Scope.Add("email"); + facebook.Scope.Add("public_profile"); + }); +```` + +> It would be a better practice to use the `appsettings.json` or the ASP.NET Core User Secrets system to store your credentials, instead of a hard-coded value like that. Follow the [Microsoft's document](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins) to learn the user secrets usage. + +### Other UI Types + +Beginning from the v3.1, the [Angular UI](../UI/Angular/Quick-Start.md) uses authorization code flow (as a best practice) to authenticate the user by redirecting to the MVC UI login page. So, even if you are using the Angular UI, social/external login integration is same as explained above and it will work out of the box. As similar, The [Blazor UI](../UI/Blazor/Overall.md) also uses the MVC UI to logic. \ No newline at end of file diff --git a/docs/en/Modules/Client-Simulation.md b/docs/en/Modules/Client-Simulation.md new file mode 100644 index 0000000000..bc5d38e814 --- /dev/null +++ b/docs/en/Modules/Client-Simulation.md @@ -0,0 +1,3 @@ +# Client Simulation Module + +TODO \ No newline at end of file diff --git a/docs/en/Modules/Cms-Kit.md b/docs/en/Modules/Cms-Kit.md new file mode 100644 index 0000000000..e13f1e585b --- /dev/null +++ b/docs/en/Modules/Cms-Kit.md @@ -0,0 +1,3 @@ +# CMS Kit Module + +TODO \ No newline at end of file diff --git a/docs/en/Modules/Docs.md b/docs/en/Modules/Docs.md index e788a4c0f8..5780b4b827 100644 --- a/docs/en/Modules/Docs.md +++ b/docs/en/Modules/Docs.md @@ -446,7 +446,7 @@ As an example you can see ABP Framework documentation: #### Conditional sections feature (Using Scriban) -Docs module uses [Scriban]( ) for conditionally show or hide some parts of a document. In order to use that feature, you have to create a JSON file as **Parameter document** per every language. It will contain all the key-values, as well as their display names. +Docs module uses [Scriban](https://github.com/lunet-io/scriban/tree/master/doc) for conditionally show or hide some parts of a document. In order to use that feature, you have to create a JSON file as **Parameter document** per every language. It will contain all the key-values, as well as their display names. For example, [en/docs-params.json](https://github.com/abpio/abp-commercial-docs/blob/master/en/docs-params.json): @@ -537,7 +537,7 @@ Also, **Document_Language_Code** and **Document_Version** keys are pre-defined i ------ -**IMPORTANT NOTICE**: Scriban uses "{{" and "}}" for syntax. Therefore, you must use escape blocks if you are going to use those in your document (an Angular document, for example). See [Scriban docs]( ) for more information. +**IMPORTANT NOTICE**: Scriban uses "{{" and "}}" for syntax. Therefore, you must use escape blocks if you are going to use those in your document (an Angular document, for example). See [Scriban docs](https://github.com/lunet-io/scriban/blob/master/doc/language.md#13-escape-block) for more information. ### 8- Creating the Navigation Document diff --git a/docs/en/Modules/Identity.md b/docs/en/Modules/Identity.md index b38f59c03b..a88087eaa8 100644 --- a/docs/en/Modules/Identity.md +++ b/docs/en/Modules/Identity.md @@ -2,7 +2,7 @@ Identity module is used to manage [organization units](Organization-Units.md), roles, users and their permissions, based on the Microsoft Identity library. -**See [the source code](https://github.com/abpframework/abp/tree/dev/modules/identity). Documentation will come soon...** +> **See [the source code](https://github.com/abpframework/abp/tree/dev/modules/identity). Documentation will come soon...** ## Identity Security Log @@ -27,3 +27,51 @@ Configure(options => options.ApplicationName = "AbpSecurityTest"; }); ``` + +## Organization Unit Management + +Organization units (OU) is a part of **Identity Module** and can be used to **hierarchically group users and entities**. + +### OrganizationUnit Entity + +An OU is represented by the **OrganizationUnit** entity. The fundamental properties of this entity are: + +- **TenantId**: Tenant's Id of this OU. Can be null for host OUs. +- **ParentId**: Parent OU's Id. Can be null if this is a root OU. +- **Code**: A hierarchical string code that is unique for a tenant. +- **DisplayName**: Shown name of the OU. + +The OrganizationUnit entity's primary key (Id) is a **Guid** type and it derives from the [**FullAuditedAggregateRoot**](../Entities.md) class. + +#### Organization Tree + +Since an OU can have a parent, all OUs of a tenant are in a **tree** structure. There are some rules for this tree; + +- There can be more than one root (where the `ParentId` is `null`). +- There is a limit for the first-level children count of an OU (because of the fixed OU Code unit length explained below). + +#### OU Code + +OU code is automatically generated and maintained by the OrganizationUnit Manager. It's a string that looks something like this: + +"**00001.00042.00005**" + +This code can be used to easily query the database for all the children of an OU (recursively). There are some rules for this code: + +- It must be **unique** for a [tenant](../Multi-Tenancy.md). +- All the children of the same OU have codes that **start with the parent OU's code**. +- It's **fixed length** and based on the level of the OU in the tree, as shown in the sample. +- While the OU code is unique, it can be **changeable** if you move an OU. +- You must reference an OU by Id, not Code. + +### OrganizationUnit Manager + +The **OrganizationUnitManager** class can be [injected](../Dependency-Injection.md) and used to manage OUs. Common use cases are: + +- Create, Update or Delete an OU +- Move an OU in the OU tree. +- Getting information about the OU tree and its items. + +#### Multi-Tenancy + +The `OrganizationUnitManager` is designed to work for a **single tenant** at a time. It works for the **current tenant** by default. \ No newline at end of file diff --git a/docs/en/Modules/Index.md b/docs/en/Modules/Index.md index ae17c15c8a..9d0199f4c3 100644 --- a/docs/en/Modules/Index.md +++ b/docs/en/Modules/Index.md @@ -1,6 +1,6 @@ # Application Modules -ABP is a **modular application framework** which consists of dozens of **nuget packages**. It also provides a complete infrastructure to build your own application modules which may have entities, services, database integration, APIs, UI components and so on. +ABP is a **modular application framework** which consists of dozens of **NuGet & NPM packages**. It also provides a complete infrastructure to build your own application modules which may have entities, services, database integration, APIs, UI components and so on. There are **two types of modules.** They don't have any structural difference but categorized by functionality and purpose: @@ -9,24 +9,26 @@ There are **two types of modules.** They don't have any structural difference bu ## Open Source Application Modules -There are some **free and open source** application modules developed and maintained by the ABP community: +There are some **free and open source** application modules developed and maintained as a part of the ABP Framework. -* **Account**: Provides UI for the account management and allows user to login/register to the application. +* [**Account**](Account.md): Provides UI for the account management and allows user to login/register to the application. * [**Audit Logging**](Audit-Logging.md): Persists audit logs to a database. -* **Background Jobs**: Persist background jobs when using the default background job manager. -* **Blogging**: Used to create fancy blogs. ABP's [own blog](https://blog.abp.io/) already using this module. -* [**Docs**](Docs.md): Used to create technical documentation pages. ABP's [own documentation](https://docs.abp.io) already using this module. -* **Feature Management**: Used to persist and manage the [features](../Features.md). +* [**Background Jobs**](Background-Jobs.md): Persist background jobs when using the default background job manager. +* [**Blogging**](Blogging.md): Used to create fancy blogs. ABP's [own blog](https://blog.abp.io/) already using this module. +* [**Client Simulation**](Client-Simulation.md): A simple web UI to stress test HTTP APIs by simulating concurrent clients. +* [**CMS Kit**](Cms-Kit.md): A set of reusable *Content Management System* features. +* [**Docs**](Docs.md): Used to create technical documentation website. ABP's [own documentation](https://docs.abp.io) already using this module. +* [**Feature Management**](Feature-Management.md): Used to persist and manage the [features](../Features.md). * **[Identity](Identity.md)**: Manages organization units, roles, users and their permissions, based on the Microsoft Identity library. -* **IdentityServer**: Integrates to IdentityServer4. -* **Permission Management**: Used to persist permissions. +* [**IdentityServer**](IdentityServer.md): Integrates to IdentityServer4. +* [**Permission Management**](Permission-Management.md): Used to persist permissions. * **[Setting Management](Setting-Management.md)**: Used to persist and manage the [settings](../Settings.md). -* **Tenant Management**: Manages tenants for a [multi-tenant](../Multi-Tenancy.md) application. -* **Users**: Abstract users, so other modules can depend on this module instead of the Identity module. +* [**Tenant Management**](Tenant-Management.md): Manages tenants for a [multi-tenant](../Multi-Tenancy.md) application. +* [**Users**](Users.md): Abstract users, so other modules can depend on this module instead of the Identity module. * [**Virtual File Explorer**](Virtual-File-Explorer.md): Provided a simple UI to view files in [virtual file system](../Virtual-File-System.md). See [the GitHub repository](https://github.com/abpframework/abp/tree/master/modules) for source code of all modules. ## Commercial Application Modules -[ABP Commercial](https://commercial.abp.io/) license provides additional pre-built application modules on top of the ABP framework. See the [module list](https://commercial.abp.io/modules) provided by the ABP Commercial. \ No newline at end of file +[ABP Commercial](https://commercial.abp.io/) license provides **additional pre-built application modules** on top of the ABP framework. See the [module list](https://commercial.abp.io/modules) provided by the ABP Commercial. \ No newline at end of file diff --git a/docs/en/Modules/Organization-Units.md b/docs/en/Modules/Organization-Units.md deleted file mode 100644 index b27e038528..0000000000 --- a/docs/en/Modules/Organization-Units.md +++ /dev/null @@ -1,47 +0,0 @@ -# Organization Unit Management - -Organization units (OU) is a part of **Identity Module** and can be used to **hierarchically group users and entities**. - -### OrganizationUnit Entity - -An OU is represented by the **OrganizationUnit** entity. The fundamental properties of this entity are: - -- **TenantId**: Tenant's Id of this OU. Can be null for host OUs. -- **ParentId**: Parent OU's Id. Can be null if this is a root OU. -- **Code**: A hierarchical string code that is unique for a tenant. -- **DisplayName**: Shown name of the OU. - -The OrganizationUnit entity's primary key (Id) is a **Guid** type and it derives from the [**FullAuditedAggregateRoot**](../Entities.md) class. - -#### Organization Tree - -Since an OU can have a parent, all OUs of a tenant are in a **tree** structure. There are some rules for this tree; - -- There can be more than one root (where the `ParentId` is `null`). -- There is a limit for the first-level children count of an OU (because of the fixed OU Code unit length explained below). - -#### OU Code - -OU code is automatically generated and maintained by the OrganizationUnit Manager. It's a string that looks something like this: - -"**00001.00042.00005**" - -This code can be used to easily query the database for all the children of an OU (recursively). There are some rules for this code: - -- It must be **unique** for a [tenant](../Multi-Tenancy.md). -- All the children of the same OU have codes that **start with the parent OU's code**. -- It's **fixed length** and based on the level of the OU in the tree, as shown in the sample. -- While the OU code is unique, it can be **changeable** if you move an OU. -- You must reference an OU by Id, not Code. - -### OrganizationUnit Manager - -The **OrganizationUnitManager** class can be [injected](../Dependency-Injection.md) and used to manage OUs. Common use cases are: - -- Create, Update or Delete an OU -- Move an OU in the OU tree. -- Getting information about the OU tree and its items. - -#### Multi-Tenancy - -The `OrganizationUnitManager` is designed to work for a **single tenant** at a time. It works for the **current tenant** by default. diff --git a/docs/en/Modules/Users.md b/docs/en/Modules/Users.md new file mode 100644 index 0000000000..1cb0f4b701 --- /dev/null +++ b/docs/en/Modules/Users.md @@ -0,0 +1,3 @@ +# Users Module + +TODO \ No newline at end of file diff --git a/docs/en/MongoDB.md b/docs/en/MongoDB.md index 475eb94f1b..98769c13b8 100644 --- a/docs/en/MongoDB.md +++ b/docs/en/MongoDB.md @@ -40,7 +40,7 @@ public class MyDbContext : AbpMongoDbContext protected override void CreateModel(IMongoModelBuilder modelBuilder) { base.CreateModel(modelBuilder); - + //Customize the configuration for your collections. } } @@ -62,7 +62,7 @@ So, most of times you don't need to explicitly configure registration for your e protected override void CreateModel(IMongoModelBuilder modelBuilder) { base.CreateModel(modelBuilder); - + modelBuilder.Entity(b => { b.CollectionName = "MyQuestions"; //Sets the collection name @@ -88,7 +88,7 @@ If you have multiple databases in your application, you can configure the connec [ConnectionStringName("MySecondConnString")] public class MyDbContext : AbpMongoDbContext { - + } ```` @@ -202,7 +202,7 @@ You generally want to derive from the `IRepository` to inherit standard reposito Example implementation of the `IBookRepository` interface: ```csharp -public class BookRepository : +public class BookRepository : MongoDbRepository, IBookRepository { @@ -242,9 +242,9 @@ context.Services.AddMongoDbContext(options => This is especially important when you want to **override a base repository method** to customize it. For instance, you may want to override `DeleteAsync` method to delete an entity in a more efficient way: ```csharp -public override async Task DeleteAsync( - Guid id, - bool autoSave = false, +public async override Task DeleteAsync( + Guid id, + bool autoSave = false, CancellationToken cancellationToken = default) { //TODO: Custom implementation of the delete method @@ -381,4 +381,4 @@ context.Services.AddMongoDbContext(options => }); ``` -In this example, `OtherMongoDbContext` implements `IBookStoreMongoDbContext`. This feature allows you to have multiple MongoDbContext (one per module) on development, but single MongoDbContext (implements all interfaces of all MongoDbContexts) on runtime. \ No newline at end of file +In this example, `OtherMongoDbContext` implements `IBookStoreMongoDbContext`. This feature allows you to have multiple MongoDbContext (one per module) on development, but single MongoDbContext (implements all interfaces of all MongoDbContexts) on runtime. diff --git a/docs/en/Multi-Tenancy.md b/docs/en/Multi-Tenancy.md index 03b3420ada..8cdda55af2 100644 --- a/docs/en/Multi-Tenancy.md +++ b/docs/en/Multi-Tenancy.md @@ -329,6 +329,7 @@ Configure(options => `MyCustomTenantResolveContributor` must inherit from the `TenantResolveContributorBase` (or implement the `ITenantResolveContributor`) as shown below: ````csharp +using System.Threading.Tasks; using Volo.Abp.MultiTenancy; namespace MultiTenancyDemo.Web @@ -337,7 +338,7 @@ namespace MultiTenancyDemo.Web { public override string Name => "Custom"; - public override void Resolve(ITenantResolveContext context) + public override Task ResolveAsync(ITenantResolveContext context) { //TODO... } diff --git a/docs/en/PlugIn-Modules.md b/docs/en/PlugIn-Modules.md new file mode 100644 index 0000000000..19aa72734d --- /dev/null +++ b/docs/en/PlugIn-Modules.md @@ -0,0 +1,3 @@ +# Plug-In Modules + +TODO \ No newline at end of file diff --git a/docs/en/Redis-Cache.md b/docs/en/Redis-Cache.md index 42679679c6..3e11584bce 100644 --- a/docs/en/Redis-Cache.md +++ b/docs/en/Redis-Cache.md @@ -25,9 +25,11 @@ Volo.Abp.Caching.StackExchangeRedis package automatically gets the redis [config ````js "Redis": { + "IsEnabled": "true", "Configuration": "127.0.0.1" } ```` +The setting `IsEnabled` is optional and will be considered `true` if it is not set. Alternatively you can configure the standard [RedisCacheOptions](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.stackexchangeredis.rediscacheoptions) [options](Options.md) class in the `ConfigureServices` method of your [module](Module-Development-Basics.md): diff --git a/docs/en/Repositories.md b/docs/en/Repositories.md index a222b9d803..5ff8372af8 100644 --- a/docs/en/Repositories.md +++ b/docs/en/Repositories.md @@ -79,6 +79,14 @@ If your entity does not have an Id primary key (it may have a composite primary > `IRepository` has a few missing methods those normally works with the `Id` property of an entity. Because of the entity has no `Id` property in that case, these methods are not available. One example is the `Get` method that gets an id and returns the entity with given id. However, you can still use `IQueryable` features to query entities by standard LINQ methods. +### Soft / Hard Delete + +`DeleteAsync` method of the repository doesn't delete the entity if the entity is a **soft-delete** entity (that implements `ISoftDelete`). Soft-delete entities are marked as "deleted" in the database. Data Filter system ensures that the soft deleted entities are not retrieved from database normally. + +If your entity is a soft-delete entity, you can use the `HardDeleteAsync` method to really delete the entity from database in case of you need it. + +See the [Data Filtering](Data-Filtering.md) documentation for more about soft-delete. + ## Custom Repositories Default generic repositories will be sufficient for most cases. However, you may need to create a custom repository class for your entity. @@ -142,7 +150,7 @@ var people = _personRepository You normally want to use `.ToListAsync()`, `.CountAsync()`... instead, to be able to write a **truly async code**. -However, you see that you can't use these async extension methods in your application or domain layer when you create a new project using the standard [application startup template](Startup-Templates/Application.md), because; +However, you see that you can't use all the async extension methods in your application or domain layer when you create a new project using the standard [application startup template](Startup-Templates/Application.md), because; * These async methods **are not standard LINQ methods** and they are defined in the [Microsoft.EntityFrameworkCore](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore) NuGet package. * The standard template **doesn't have a reference** to the EF Core package from the domain and application layers, to be independent from the database provider. @@ -151,9 +159,9 @@ Based on your requirements and development model, you have the following options > Using async methods is strongly suggested! Don't use sync LINQ methods while executing database queries to be able to develop a scalable application. -### Option-1: Reference to the EF Core +### Option-1: Reference to the Database Provider Package -The easiest solution is to directly add the EF Core package from the project you want to use these async methods. +**The easiest solution** is to directly add the EF Core package from the project you want to use these async methods. > Add the [Volo.Abp.EntityFrameworkCore](https://www.nuget.org/packages/Volo.Abp.EntityFrameworkCore) NuGet package to your project, which indirectly reference to the EF Core package. This ensures that you use the correct version of the EF Core compatible to the rest of your application. @@ -183,14 +191,34 @@ var people = ((IMongoQueryable)_personRepository .ToListAsync(); ```` -### Option-2: Custom Repository Methods +### Option-2: Use the IRepository Async Extension Methods -You can always create custom repository methods and use the database provider specific APIs, like async extension methods here. See [EF Core](Entity-Framework-Core.md) or [MongoDb](MongoDB.md) document for more info about the custom repositories. +ABP Framework provides async extension methods for the repositories, just similar to async LINQ extension methods. -This method is suggested; +**Example: Use `CountAsync` and `FirstOrDefaultAsync` methods on the repositories** -* If you want to **completely isolate** your domain & application layers from the database provider. -* If you develop a **reusable [application module](Modules/Index.md)** and don't want to force to a specific database provider, which should be done as a [best practice](Best-Practices/Index.md). +````csharp +var countAll = await _personRepository + .CountAsync(); + +var count = await _personRepository + .CountAsync(x => x.Name.StartsWith("A")); + +var book1984 = await _bookRepository + .FirstOrDefaultAsync(x => x.Name == "John"); +```` + +The standard LINQ extension methods are supported: *AllAsync, AnyAsync, AverageAsync, ContainsAsync, CountAsync, FirstAsync, FirstOrDefaultAsync, LastAsync, LastOrDefaultAsync, LongCountAsync, MaxAsync, MinAsync, SingleAsync, SingleOrDefaultAsync, SumAsync, ToArrayAsync, ToListAsync*. + +This approach still **has a limitation**. You need to call the extension method directly on the repository object. For example, the below usage is **not supported**: + +```csharp +var count = await _bookRepository.Where(x => x.Name.Contains("A")).CountAsync(); +``` + +This is because the object returned from the `Where` method is not a repository object, it is a standard `IQueryable` interface. See the other options for such cases. + +This method is suggested **wherever possible**. ### Option-3: IAsyncQueryableExecuter @@ -245,6 +273,17 @@ ABP Framework executes the query asynchronously using the actual database provid This method is suggested; +* If you want to develop your application code **without depending** on the database provider. * If you are building a **reusable library** that doesn't have a database provider integration package, but needs to execute an `IQueryable` object in some case. -For example, ABP Framework uses the `IAsyncQueryableExecuter` in the `CrudAppService` base class (see the [application services](Application-Services.md) document). \ No newline at end of file +For example, ABP Framework uses the `IAsyncQueryableExecuter` in the `CrudAppService` base class (see the [application services](Application-Services.md) document). + +### Option-4: Custom Repository Methods + +You can always create custom repository methods and use the database provider specific APIs, like async extension methods here. See [EF Core](Entity-Framework-Core.md) or [MongoDb](MongoDB.md) document for more info about the custom repositories. + +This method is suggested; + +* If you want to **completely isolate** your domain & application layers from the database provider. +* If you develop a **reusable [application module](Modules/Index.md)** and don't want to force to a specific database provider, which should be done as a [best practice](Best-Practices/Index.md). + diff --git a/docs/en/Road-Map.md b/docs/en/Road-Map.md index 8670ba080b..3a45ca1767 100644 --- a/docs/en/Road-Map.md +++ b/docs/en/Road-Map.md @@ -1,17 +1,12 @@ # ABP Framework Road Map -You can always check the milestone planning and the prioritized backlog issues on [the GitHub repository](https://github.com/abpframework/abp/milestones) for a detailed road map. - -While we will **continue to add other exciting features**, we will work on the following major items in the **middle term**: - -* **Blazor UI** for the framework and all the pre-built modules (in progress). -* **.NET 5.0**! As Microsoft has announced that the .NET 5.0 will be released in November 2020, we will prepare for this change before and move to the .NET 5.0 just after Microsoft releases it. We hope a smooth transition. - -Beside this middle term goals, there are many features in the [backlog](https://github.com/abpframework/abp/milestone/2). Here, a list of some major items in the backlog; +You can always check the milestone planning and the prioritized backlog issues on [the GitHub repository](https://github.com/abpframework/abp/milestones) for a detailed road map. Here, a list of some major items in the backlog; * [#2882](https://github.com/abpframework/abp/issues/2882) / Providing a gRPC integration infrastructure (while it is [already possible](https://github.com/abpframework/abp-samples/tree/master/GrpcDemo) to create or consume gRPC endpoints for your application, we plan to create endpoints for the [standard application modules](https://docs.abp.io/en/abp/latest/Modules/Index)) * [#236](https://github.com/abpframework/abp/issues/236) Resource based authorization system +* [#6132](https://github.com/abpframework/abp/issues/6132) A New Theme alternative to the Basic Theme * [#1754](https://github.com/abpframework/abp/issues/1754) / Multi-lingual entities +* [#497](https://github.com/abpframework/abp/issues/497) API Versioning system finalize & document * [#633](https://github.com/abpframework/abp/issues/633) / Realtime notification system * [#57](https://github.com/abpframework/abp/issues/57) / Built-in CQRS infrastructure * [#336](https://github.com/abpframework/abp/issues/336) / Health Check abstraction diff --git a/docs/en/Settings.md b/docs/en/Settings.md index 32761ff201..567cb02c4c 100644 --- a/docs/en/Settings.md +++ b/docs/en/Settings.md @@ -2,7 +2,7 @@ [Configuration system](Configuration.md) is a good way to configure the application on startup. In addition to the configurations, ABP provides another way to set and get some application settings. -A setting is a name-value pair stored in a dynamic data source, generally in a database. Setting system is extensible and there are pre-built provides for a user, a tenant, global and default. +A setting is a name-value pair stored in a dynamic data source, generally in a database. Setting system is extensible and there are pre-built providers for a user, a tenant, global and default. ## Defining Settings @@ -67,7 +67,7 @@ public class MySettingDefinitionProvider : SettingDefinitionProvider > Using constants for the setting names is a good practice and ABP packages do it. `Abp.Mailing.Smtp.Host` setting name is a constant defined by the `EmailSettingNames` class (in the `Volo.Abp.Emailing` namespace). -## Reading Setting Values +## Reading the Setting Values ### ISettingProvider @@ -108,24 +108,15 @@ public class MyService } ```` -> `ISettingProvider` is a very common service and some base classes (like `IApplicationService`) already property-inject it. You can directly use the `SettingProvider` in such cases. +> `ISettingProvider` is a very common service and some base classes (like `IApplicationService`) already property-inject it. You can directly use the `SettingProvider` property in such cases. ### Reading Setting Values on the Client Side -If a setting is allowed to be visible on the client side, current value of the setting can also be read from the JavaScript code. Examples: +If a setting is allowed to be visible on the client side, current value of the setting can also be read from the client code. See the following documents to understand how to get the setting values in different UI types; -````js -//Gets a value as string. -var language = abp.setting.get('Abp.Localization.DefaultLanguage'); - -//Gets an integer value. -var requiredLength = abp.setting.getInt('Abp.Identity.Password.RequiredLength'); - -//Gets a boolean value. -var requireDigit = abp.setting.getBoolean('Abp.Identity.Password.RequireDigit'); -```` - -In addition, use `abp.setting.values` to get a dictionary of all the setting values. +* [MVC / Razor Pages](UI/AspNetCore/JavaScript-API/Settings.md) +* [Angular](UI/Angular/Settings.md) +* [Blazor](UI/Blazor/Settings.md) ## Setting Value Providers diff --git a/docs/en/Specifications.md b/docs/en/Specifications.md index ea4f140e95..036baa749e 100644 --- a/docs/en/Specifications.md +++ b/docs/en/Specifications.md @@ -1,3 +1,255 @@ # Specifications -TODO! \ No newline at end of file +Specification Pattern is used to define **named, reusable, combinable and testable filters** for entities and other business objects. + +> A Specification is a part of the Domain Layer. + +## Installation + +> This package is **already installed** when you use the startup templates. So, most of the times you don't need to manually install it. + +Install the [Volo.Abp.Specifications](https://abp.io/package-detail/Volo.Abp.Specifications) package to your project. You can use the [ABP CLI](CLI.md) *add-package* command in a command line terminal when the current folder is the root folder of your project (`.csproj`): + +````bash +abp add-package Volo.Abp.Specifications +```` + +## Defining the Specifications + +Assume that you've a Customer entity as defined below: + +````csharp +using System; +using Volo.Abp.Domain.Entities; + +namespace MyProject +{ + public class Customer : AggregateRoot + { + public string Name { get; set; } + + public byte Age { get; set; } + + public long Balance { get; set; } + + public string Location { get; set; } + } +} +```` + +You can create a new Specification class derived from the `Specification`. + +**Example: A specification to select the customers with 18+ age:** + +````csharp +using System; +using System.Linq.Expressions; +using Volo.Abp.Specifications; + +namespace MyProject +{ + public class Age18PlusCustomerSpecification : Specification + { + public override Expression> ToExpression() + { + return c => c.Age >= 18; + } + } +} +```` + +You simply define a lambda [Expression](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions) to define a specification. + +> Instead, you can directly implement the `ISpecification` interface, but the `Specification` base class much simplifies it. + +## Using the Specifications + +There are two common use cases of the specifications. + +### IsSatisfiedBy + +`IsSatisfiedBy` method can be used to check if a single object satisfies the specification. + +**Example: Throw exception if the customer doesn't satisfy the age specification** + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; + +namespace MyProject +{ + public class CustomerService : ITransientDependency + { + public async Task BuyAlcohol(Customer customer) + { + if (!new Age18PlusCustomerSpecification().IsSatisfiedBy(customer)) + { + throw new Exception( + "This customer doesn't satisfy the Age specification!" + ); + } + + //TODO... + } + } +} +```` + +### ToExpression & Repositories + +`ToExpression()` method can be used to use the specification as Expression. In this way, you can use a specification to **filter entities while querying from the database**. + +````csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Domain.Services; + +namespace MyProject +{ + public class CustomerManager : DomainService, ITransientDependency + { + private readonly IRepository _customerRepository; + + public CustomerManager(IRepository customerRepository) + { + _customerRepository = customerRepository; + } + + public async Task> GetCustomersCanBuyAlcohol() + { + var query = _customerRepository.Where( + new Age18PlusCustomerSpecification().ToExpression() + ); + + return await AsyncExecuter.ToListAsync(query); + } + } +} +```` + +> Specifications are correctly translated to SQL/Database queries and executed efficiently in the DBMS side. While it is not related to the Specifications, see the [Repositories](Repositories.md) document if you want to know more about the `AsyncExecuter`. + +Actually, using the `ToExpression()` method is not necessary since the specifications are automatically casted to Expressions. This would also work: + +````csharp +var query = _customerRepository.Where( + new Age18PlusCustomerSpecification() +); +```` + +## Composing the Specifications + +One powerful feature of the specifications is that they are composable with `And`, `Or`, `Not` and `AndNot` extension methods. + +Assume that you have another specification as defined below: + +```csharp +using System; +using System.Linq.Expressions; +using Volo.Abp.Specifications; + +namespace MyProject +{ + public class PremiumCustomerSpecification : Specification + { + public override Expression> ToExpression() + { + return (customer) => (customer.Balance >= 100000); + } + } +} +``` + +You can combine the `PremiumCustomerSpecification` with the `Age18PlusCustomerSpecification` to query the count of premium adult customers as shown below: + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Domain.Services; +using Volo.Abp.Specifications; + +namespace MyProject +{ + public class CustomerManager : DomainService, ITransientDependency + { + private readonly IRepository _customerRepository; + + public CustomerManager(IRepository customerRepository) + { + _customerRepository = customerRepository; + } + + public async Task GetAdultPremiumCustomerCountAsync() + { + return await _customerRepository.CountAsync( + new Age18PlusCustomerSpecification() + .And(new PremiumCustomerSpecification()).ToExpression() + ); + } + } +} +```` + +If you want to make this combination another reusable specification, you can create such a combination specification class deriving from the `AndSpecification`: + +````csharp +using Volo.Abp.Specifications; + +namespace MyProject +{ + public class AdultPremiumCustomerSpecification : AndSpecification + { + public AdultPremiumCustomerSpecification() + : base(new Age18PlusCustomerSpecification(), + new PremiumCustomerSpecification()) + { + } + } +} +```` + +Now, you can re-write the `GetAdultPremiumCustomerCountAsync` method as shown below: + +````csharp +public async Task GetAdultPremiumCustomerCountAsync() +{ + return await _customerRepository.CountAsync( + new AdultPremiumCustomerSpecification() + ); +} +```` + +> You see the power of the specifications with these samples. If you change the `PremiumCustomerSpecification` later, say change the balance from `100.000` to `200.000`, all the queries and combined specifications will be effected by the change. This is a good way to reduce code duplication! + +## Discussions + +While the specification pattern is older than C# lambda expressions, it's generally compared to expressions. Some developers may think it's not needed anymore and we can directly pass expressions to a repository or to a domain service as shown below: + +````csharp +var count = await _customerRepository.CountAsync(c => c.Balance > 100000 && c.Age => 18); +```` + +Since ABP's [Repository](Repositories.md) supports Expressions, this is a completely valid use. You don't have to define or use any specification in your application and you can go with expressions. + +So, what's the point of a specification? Why and when should we consider to use them? + +### When To Use? + +Some benefits of using specifications: + +- **Reusabe**: Imagine that you need the Premium Customer filter in many places in your code base. If you go with expressions and do not create a specification, what happens if you later change the "Premium Customer" definition? Say you want to change the minimum balance from $100,000 to $250,000 and add another condition to be a customer older than 3 years. If you'd used a specification, you just change a single class. If you repeated (copy/pasted) the same expression everywhere, you need to change all of them. +- **Composable**: You can combine multiple specifications to create new specifications. This is another type of reusability. +- **Named**: `PremiumCustomerSpecification` better explains the intent rather than a complex expression. So, if you have an expression that is meaningful in your business, consider using specifications. +- **Testable**: A specification is a separately (and easily) testable object. + +### When To Not Use? + +- **Non business expressions**: Do not use specifications for non business-related expressions and operations. +- **Reporting**: If you are just creating a report, do not create specifications, but directly use `IQueryable` & LINQ expressions. You can even use plain SQL, views or another tool for reporting. DDD does not necessarily care about reporting, so the way you query the underlying data store can be important from a performance perspective. \ No newline at end of file diff --git a/docs/en/Startup-Templates/Application.md b/docs/en/Startup-Templates/Application.md index 8cccf32382..81f0170e59 100644 --- a/docs/en/Startup-Templates/Application.md +++ b/docs/en/Startup-Templates/Application.md @@ -97,7 +97,7 @@ A `BookType` enum and a `BookConsts` class (which may have some constant fields #### .Domain Project -This is the domain layer of the solution. It mainly contains [entities, aggregate roots](../Entities.md), [domain services](../Domain-Services.md), [value types](../Value-Types.md), [repository interfaces](../Repositories.md) and other domain objects. +This is the domain layer of the solution. It mainly contains [entities, aggregate roots](../Entities.md), [domain services](../Domain-Services.md), [value objects](../Value-Objects.md), [repository interfaces](../Repositories.md) and other domain objects. A `Book` entity, a `BookManager` domain service and an `IBookRepository` interface are good candidates for this project. diff --git a/docs/en/Startup-Templates/Index.md b/docs/en/Startup-Templates/Index.md index 0c788a6a9c..b73779ecb8 100644 --- a/docs/en/Startup-Templates/Index.md +++ b/docs/en/Startup-Templates/Index.md @@ -5,3 +5,4 @@ While you can start with an empty project and add needed packages manually, star * [**app**](Application.md): Application template. * [**module**](Module.md): Module/service template. * [**console**](Console.md): Console template. +* [**WPF**](WPF.md): WPF template. diff --git a/docs/en/Startup-Templates/WPF.md b/docs/en/Startup-Templates/WPF.md new file mode 100644 index 0000000000..7eb6a5c73e --- /dev/null +++ b/docs/en/Startup-Templates/WPF.md @@ -0,0 +1,27 @@ +# WPF Application Startup Template + +This template is used to create a minimalist WPF application project. + +## How to Start With? + +First, install the [ABP CLI](../CLI.md) if you haven't installed before: + +````bash +dotnet tool install -g Volo.Abp.Cli +```` + +Then use the `abp new` command in an empty folder to create a new solution: + +````bash +abp new Acme.MyWpfApp -t wpf +```` + +`Acme.MyWpfApp` is the solution name, like *YourCompany.YourProduct*. You can use single level, two-levels or three-levels naming. + +## Solution Structure + +After you use the above command to create a solution, you will have a solution like shown below: + +![basic-wpf-application-solution](../images/basic-wpf-application-solution.png) + +* `HelloWorldService` is a sample service that implements the `ITransientDependency` interface to register this service to the [dependency injection](../Dependency-Injection.md) system. \ No newline at end of file diff --git a/docs/en/Swagger.md b/docs/en/Swagger.md new file mode 100644 index 0000000000..1fda8a0cd7 --- /dev/null +++ b/docs/en/Swagger.md @@ -0,0 +1,3 @@ +# Swagger UI Integration + +TODO \ No newline at end of file diff --git a/docs/en/Testing.md b/docs/en/Testing.md index 5dafef3daf..0a617174ed 100644 --- a/docs/en/Testing.md +++ b/docs/en/Testing.md @@ -1,3 +1,673 @@ -# Testing +# Automated Testing -TODO! \ No newline at end of file +## Introduction + +ABP Framework has been designed with testability in mind. There are some different levels of automated testing; + +* **Unit Tests**: You typically test a single class (or a very few classes together). These tests will be fast. However, you generally need to deal with mocking for the dependencies of your service(s). +* **Integration Tests**: You typically test a service, but this time you don't mock the fundamental infrastructure and services to see if they properly working together. +* **UI Tests**: You test the UI of the application, just like the users interact with your application. + +### Unit Tests vs Integration Tests + +Integration tests have some significant **advantages** compared to unit tests; + +* **Easier to write** since you don't work to establish mocking and dealing with the dependencies. +* Your test code runs with all the real services and infrastructure (including database mapping and queries), so it is much closer to the **real application test**. + +While they have some drawbacks; + +* They are **slower** compared to unit tests since all the infrastructure is prepared for each test case. +* A bug in a service may make multiple test cases broken, so it may be **harder to find the real problem** in some cases. + +We suggest to go mixed: Write unit or integration test where it is necessary and you find effective to write and maintain it. + +## The Application Startup Template + +The [Application Startup Template](Startup-Templates/Application.md) comes with the test infrastructure properly installed and configured for you. + +### The Test Projects + +See the following solution structure in the Visual Studio: + +![solution-test-projects](images/solution-test-projects.png) + +There are more than one test project, organized by the layers; + +* `Domain.Tests` is used to test your Domain Layer objects (like [Domain Services](Domain-Services.md) and [Entities](Entities.md)). +* `Application.Tests` is used to test your Application Layer (like [Application Services](Application-Services.md)). +* `EntityFrameworkCore.Tests` is used to test your custom repository implementations or EF Core mappings (this project will be different if you use another [Database Provider](Data-Access.md)). +* `Web.Tests` is used to test the UI Layer (like Pages, Controllers and View Components). This project does exists only for MVC / Razor Page applications. +* `TestBase` contains some classes those are shared/used by the other projects. + +> `HttpApi.Client.ConsoleTestApp` is not an automated test application. It is an example Console Application that shows how to consume your HTTP APIs from a .NET Console Application. + +The following sections will introduce the base classes and other infrastructure included in these projects. + +### The Test Infrastructure + +The startup solution has the following libraries already installed; + +* [xUnit](https://xunit.net/) as the test framework. +* [NSubstitute](https://nsubstitute.github.io/) as the mocking library. +* [Shouldly](https://github.com/shouldly/shouldly) as the assertion library. + +While you are free to replace them with your favorite tools, this document and examples will be base on these tooling. + +## The Test Explorer + +You can use the Test Explorer to view and run the tests in Visual Studio. For other IDEs, see their own documentation. + +### Open the Test Explorer + +Open the *Test Explorer*, under the *Tests* menu, if it is not already open: + +![vs-test-explorer](images/vs-test-explorer.png) + +### Run the Tests + +Then you can click to the Run All or Run buttons to run the tests. The initial startup template has some sample tests for you: + +![vs-startup-template-tests](images/vs-startup-template-tests.png) + +### Run Tests In Parallel + +The test infrastructure is compatible to run the tests in parallel. It is **strongly suggested** to run all the tests in parallel, which is pretty faster then running them one by one. + +To enable it, click to the caret icon near to the settings (gear) button and select the *Run Tests In Parallel*. + +![vs-run-tests-in-parallel](images/vs-run-tests-in-parallel.png) + +## Unit Tests + +For Unit Tests, you don't need to much infrastructure. You typically instantiate your class and provide some pre-configured mocked objects to prepare your object to test. + +### Classes Without Dependencies + +In this simplest case, the class you want to test has no dependencies. In this case, you can directly instantiate your class, call its methods and make your assertions. + +#### Example: Testing an Entity + +Assume that you've an `Issue` [entity](Entities.md) as shown below: + +````csharp +using System; +using Volo.Abp.Domain.Entities; + +namespace MyProject.Issues +{ + public class Issue : AggregateRoot + { + public string Title { get; set; } + public string Description { get; set; } + public bool IsLocked { get; set; } + public bool IsClosed { get; private set; } + public DateTime? CloseDate { get; private set; } + + public void Close() + { + IsClosed = true; + CloseDate = DateTime.UtcNow; + } + + public void Open() + { + if (!IsClosed) + { + return; + } + + if (IsLocked) + { + throw new IssueStateException("You can not open a locked issue!"); + } + + IsClosed = true; + CloseDate = null; + } + } +} + +```` + +Notice that the `IsClosed` and `CloseDate` properties have private setters to force some business rules by using the `Open()` and `Close()` methods; + +* Whenever you close an issue, the `CloseDate` should be set to the [current time](Timing.md). +* An issue can not be re-opened if it is locked. And if it is re-opened, the `CloseDate` should be set to `null`. + +Since the `Issue` entity is a part of the Domain Layer, we should test it in the `Domain.Tests` project. Create an `Issue_Tests` class inside the `Domain.Tests` project: + +````csharp +using Shouldly; +using Xunit; + +namespace MyProject.Issues +{ + public class Issue_Tests + { + [Fact] + public void Should_Set_The_CloseDate_Whenever_Close_An_Issue() + { + // Arrange + + var issue = new Issue(); + issue.CloseDate.ShouldBeNull(); // null at the beginning + + // Act + + issue.Close(); + + // Assert + + issue.IsClosed.ShouldBeTrue(); + issue.CloseDate.ShouldNotBeNull(); + } + } +} +```` + +This test follows the AAA (Arrange-Act-Assert) pattern; + +* **Arrange** part creates an `Issue` entity and ensures the `CloseDate` is `null` at the beginning. +* **Act** part executes the method we want to test for this case. +* **Assert** part checks if the `Issue` properties are same as we expect to be. + +`[Fact]` attribute is defined by the [xUnit](https://xunit.net/) library and marks a method as a test method. `Should...` extension methods are provided by the [Shouldly](https://github.com/shouldly/shouldly) library. You can directly use the `Assert` class of the xUnit, but Shouldly makes it much comfortable and straightforward. + +When you execute the tests, you will see that is passes successfully: + +![issue-first-test](images/issue-first-test.png) + +Let's add two more test methods: + +````csharp +[Fact] +public void Should_Allow_To_ReOpen_An_Issue() +{ + // Arrange + + var issue = new Issue(); + issue.Close(); + + // Act + + issue.Open(); + + // Assert + + issue.IsClosed.ShouldBeFalse(); + issue.CloseDate.ShouldBeNull(); +} + +[Fact] +public void Should_Not_Allow_To_ReOpen_A_Locked_Issue() +{ + // Arrange + + var issue = new Issue(); + issue.Close(); + issue.IsLocked = true; + + // Act & Assert + + Assert.Throws(() => + { + issue.Open(); + }); +} +```` + +`Assert.Throws` checks if the executed code throws a matching exception. + +> See the xUnit & Shoudly documentations to learn more about these libraries. + +### Classes With Dependencies + +If your service has dependencies and you want to unit test this service, you need to mock the dependencies. + +#### Example: Testing a Domain Service + +Assume that you've an `IssueManager` [Domain Service](Domain-Services.md) that is defined as below: + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp; +using Volo.Abp.Domain.Services; + +namespace MyProject.Issues +{ + public class IssueManager : DomainService + { + public const int MaxAllowedOpenIssueCountForAUser = 3; + + private readonly IIssueRepository _issueRepository; + + public IssueManager(IIssueRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task AssignToUserAsync(Issue issue, Guid userId) + { + var issueCount = await _issueRepository.GetIssueCountOfUserAsync(userId); + + if (issueCount >= MaxAllowedOpenIssueCountForAUser) + { + throw new BusinessException( + code: "IM:00392", + message: $"You can not assign more" + + $"than {MaxAllowedOpenIssueCountForAUser} issues to a user!" + ); + } + + issue.AssignedUserId = userId; + } + } +} +```` + +`IssueManager` depends on the `IssueRepository` service, that will be mocked in this example. + +**Business Rule**: The example `AssignToUserAsync` doesn't allow to assign more than 3 (`MaxAllowedOpenIssueCountForAUser` constant) issues to a user. If you want to assign an issue in this case, you first need to unassign an existing issue. + +The test case below tries to make a valid assignment: + +````csharp +using System; +using System.Threading.Tasks; +using NSubstitute; +using Shouldly; +using Volo.Abp; +using Xunit; + +namespace MyProject.Issues +{ + public class IssueManager_Tests + { + [Fact] + public async Task Should_Assign_An_Issue_To_A_User() + { + // Arrange + + var userId = Guid.NewGuid(); + + var fakeRepo = Substitute.For(); + fakeRepo.GetIssueCountOfUserAsync(userId).Returns(1); + + var issueManager = new IssueManager(fakeRepo); + + var issue = new Issue(); + + // Act + + await issueManager.AssignToUserAsync(issue, userId); + + //Assert + + issue.AssignedUserId.ShouldBe(userId); + await fakeRepo.Received(1).GetIssueCountOfUserAsync(userId); + } + } +} +```` + +* `Substitute.For` creates a mock (fake) object that is passed into the `IssueManager` constructor. +* `fakeRepo.GetIssueCountOfUserAsync(userId).Returns(1)` ensures that the `GetIssueCountOfUserAsync` method of the repository returns `1`. +* `issueManager.AssignToUserAsync` doesn't throw any exception since the repository returns `1` for the currently assigned issue count. +* `issue.AssignedUserId.ShouldBe(userId);` line checks if the `AssignedUserId` has the correct value. +* `await fakeRepo.Received(1).GetIssueCountOfUserAsync(userId);` checks if the `IssueManager` called the `GetIssueCountOfUserAsync` method exactly one time. + +Let's add a second test to see if it prevents to assign issues to a user more than the allowed count: + +````csharp +[Fact] +public async Task Should_Not_Allow_To_Assign_Issues_Over_The_Limit() +{ + // Arrange + + var userId = Guid.NewGuid(); + + var fakeRepo = Substitute.For(); + fakeRepo + .GetIssueCountOfUserAsync(userId) + .Returns(IssueManager.MaxAllowedOpenIssueCountForAUser); + + var issueManager = new IssueManager(fakeRepo); + + // Act & Assert + + var issue = new Issue(); + + await Assert.ThrowsAsync(async () => + { + await issueManager.AssignToUserAsync(issue, userId); + }); + + issue.AssignedUserId.ShouldBeNull(); + await fakeRepo.Received(1).GetIssueCountOfUserAsync(userId); +} +```` + +> For more information on the mocking, see the [NSubstitute](https://nsubstitute.github.io/) documentation. + +It is relatively easy to mock a single dependency. But, when your dependencies grow, it gets harder to setup the test objects and mock all the dependencies. See the *Integration Tests* section that doesn't require mocking the dependencies. + +### Tip: Share the Test Class Constructor + +[xUnit](https://xunit.net/) creates a **new test class instance** (`IssueManager_Tests` for this example) for each test method. So, you can move some *Arrange* code into the constructor to reduce the code duplication. The constructor will be executed for each test case and doesn't affect each other, even if they work in parallel. + +**Example: Refactor the `IssueManager_Tests` to reduce the code duplication** + +````csharp +using System; +using System.Threading.Tasks; +using NSubstitute; +using Shouldly; +using Volo.Abp; +using Xunit; + +namespace MyProject.Issues +{ + public class IssueManager_Tests + { + private readonly Guid _userId; + private readonly IIssueRepository _fakeRepo; + private readonly IssueManager _issueManager; + private readonly Issue _issue; + + public IssueManager_Tests() + { + _userId = Guid.NewGuid(); + _fakeRepo = Substitute.For(); + _issueManager = new IssueManager(_fakeRepo); + _issue = new Issue(); + } + + [Fact] + public async Task Should_Assign_An_Issue_To_A_User() + { + // Arrange + _fakeRepo.GetIssueCountOfUserAsync(_userId).Returns(1); + + // Act + await _issueManager.AssignToUserAsync(_issue, _userId); + + //Assert + _issue.AssignedUserId.ShouldBe(_userId); + await _fakeRepo.Received(1).GetIssueCountOfUserAsync(_userId); + } + + [Fact] + public async Task Should_Not_Allow_To_Assign_Issues_Over_The_Limit() + { + // Arrange + _fakeRepo + .GetIssueCountOfUserAsync(_userId) + .Returns(IssueManager.MaxAllowedOpenIssueCountForAUser); + + // Act & Assert + await Assert.ThrowsAsync(async () => + { + await _issueManager.AssignToUserAsync(_issue, _userId); + }); + + _issue.AssignedUserId.ShouldBeNull(); + await _fakeRepo.Received(1).GetIssueCountOfUserAsync(_userId); + } + } +} +```` + +> Keep your test code clean to create a maintainable test suite. + +## Integration Tests + +> You can follow the [web application development tutorial](Tutorials/Part-1.md) to learn developing a full stack application, including the integration tests. + +### The Integration Test Infrastructure + +ABP Provides a complete infrastructure to write integration tests. All the ABP infrastructure and services will perform in your tests. The application startup template comes with the necessary infrastructure pre-configured for you; + +#### The Database + +The startup template is configured to use **in-memory SQLite** database for the EF Core (for MongoDB, it uses [Mongo2Go](https://github.com/Mongo2Go/Mongo2Go) library). So, all the configuration and queries are performed against a real database and you can even test database transactions. + +Using in-memory SQLite database has two main advantages; + +* It is faster compared to an external DBMS. +* It create a **new fresh database** for each test case, so tests doesn't affect each other. + +> **Tip**: Do not use EF Core's In-Memory database for advanced integration tests. It is not a real DBMS and has many differences in details. For example, it doesn't support transaction and rollback scenarios, so you can't truly test the failing scenarios. On the other hand, In-Memory SQLite is a real DBMS and supports the fundamental SQL database features. + +### The Seed Data + +Writing tests against an empty database is not practical. In most cases, you need to some initial data in the database. For example, if you write a test class that query, update and delete the Products, it would be helpful to have a few products in the database before executing the test case. + +ABP's [Data Seeding](Data-Seeding.md) system is a powerful way to seed the initial data. The application startup template has a *YourProject*TestDataSeedContributor class in the `.TestBase` project. You can fill it to have an initial data that you can use for each test method. + +**Example: Create some Issues as the seed data** + +````csharp +using System.Threading.Tasks; +using MyProject.Issues; +using Volo.Abp.Data; +using Volo.Abp.DependencyInjection; + +namespace MyProject +{ + public class MyProjectTestDataSeedContributor + : IDataSeedContributor, ITransientDependency + { + private readonly IIssueRepository _issueRepository; + + public MyProjectTestDataSeedContributor(IIssueRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task SeedAsync(DataSeedContext context) + { + await _issueRepository.InsertAsync( + new Issue + { + Title = "Test issue one", + Description = "Test issue one description", + AssignedUserId = TestData.User1Id + }); + + await _issueRepository.InsertAsync( + new Issue + { + Title = "Test issue two", + Description = "Test issue two description", + AssignedUserId = TestData.User1Id + }); + + await _issueRepository.InsertAsync( + new Issue + { + Title = "Test issue three", + Description = "Test issue three description", + AssignedUserId = TestData.User1Id + }); + + await _issueRepository.InsertAsync( + new Issue + { + Title = "Test issue four", + Description = "Test issue four description", + AssignedUserId = TestData.User2Id + }); + } + } +} +```` + +Also created a static class to store the User `Ids`: + +````csharp +using System; + +namespace MyProject +{ + public static class TestData + { + public static Guid User1Id = Guid.Parse("41951813-5CF9-4204-8B18-CD765DBCBC9B"); + public static Guid User2Id = Guid.Parse("2DAB4460-C21B-4925-BF41-A52750A9B999"); + } +} +```` + +In this way, we can use these known Issues and the User `Id`s to perform the tests. + +### Example: Testing a Domain Service + +`AbpIntegratedTest` class (defined in the [Volo.Abp.TestBase](https://www.nuget.org/packages/Volo.Abp.TestBase) package) is used to write tests integrated to the ABP Framework. `T` is the Type of the root module to setup and initialize the application. + +The application startup template has base classes in each test project, so you can derive from these base classes to make it easier. + +See the `IssueManager` tests are re-written as integration tests + +````csharp +using System.Threading.Tasks; +using Shouldly; +using Volo.Abp; +using Xunit; + +namespace MyProject.Issues +{ + public class IssueManager_Integration_Tests : MyProjectDomainTestBase + { + private readonly IssueManager _issueManager; + private readonly Issue _issue; + + public IssueManager_Integration_Tests() + { + _issueManager = GetRequiredService(); + _issue = new Issue + { + Title = "Test title", + Description = "Test description" + }; + } + + [Fact] + public async Task Should_Not_Allow_To_Assign_Issues_Over_The_Limit() + { + // Act & Assert + await Assert.ThrowsAsync(async () => + { + await _issueManager.AssignToUserAsync(_issue, TestData.User1Id); + }); + + _issue.AssignedUserId.ShouldBeNull(); + } + + [Fact] + public async Task Should_Assign_An_Issue_To_A_User() + { + // Act + await _issueManager.AssignToUserAsync(_issue, TestData.User2Id); + + //Assert + _issue.AssignedUserId.ShouldBe(TestData.User2Id); + } + } +} +```` + +* First test method assigns the issue to the User 1, which has already assigned to 3 issues in the Data Seed code. So, it throws a `BusinessException`. +* Second test method assigns the issue to User 2, which has only 1 issue assigned. So, the method succeeds. + +This class typically locates in the `.Domain.Tests` project since it tests a class located in the `.Domain` project. It is derived from the `MyProjectDomainTestBase` which is already configured to properly run the tests. + +Writing such an integration test class is very straightforward. Another benefit is that you won't need to change the test class later when you add another dependency to the `IssueManager` class. + +### Example: Testing an Application Service + +Testing an [Application Service](Application-Services.md) is not so different. Assume that you've created an `IssueAppService` as defined below: + +````csharp +using System.Collections.Generic; +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace MyProject.Issues +{ + public class IssueAppService : ApplicationService, IIssueAppService + { + private readonly IIssueRepository _issueRepository; + + public IssueAppService(IIssueRepository issueRepository) + { + _issueRepository = issueRepository; + } + + public async Task> GetListAsync() + { + var issues = await _issueRepository.GetListAsync(); + + return ObjectMapper.Map, List>(issues); + } + } +} +```` + +*(assuming you've also defined the `IIssueAppService` and `IssueDto` and created the [object mapping](Object-To-Object-Mapping.md) between `Issue` and the `IssueDto`)* + +Now, you can write a test class inside the `.Application.Tests` project: + +````csharp +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +namespace MyProject.Issues +{ + public class IssueAppService_Tests : MyProjectApplicationTestBase + { + private readonly IIssueAppService _issueAppService; + + public IssueAppService_Tests() + { + _issueAppService = GetRequiredService(); + } + + [Fact] + public async Task Should_Get_All_Issues() + { + //Act + var issueDtos = await _issueAppService.GetListAsync(); + + //Assert + issueDtos.Count.ShouldBeGreaterThan(0); + } + } +} +```` + +It's that simple. This test method tests everything, including the application service, EF Core mapping, object to object mapping and the repository implementation. In this way, you can fully test the Application Later and the Domain Layer of your solution. + +## UI Tests + +In general, there are two types of UI Tests; + +### Non Visual Tests + +Such tests completely depends on your UI Framework choice; + +* For an MVC / Razor Pages UI, you typically make request to the server, get some HTML and test if some expected DOM elements exist in the returned result. +* Angular has its own infrastructure and practices to test the components, views and services. + +See the following documents to learn Non Visual UI Testing; + +* [Testing in ASP.NET Core MVC / Razor Pages](UI/AspNetCore/Testing.md) +* [Testing in Angular](UI/Angular/Testing.md) +* [Testing in Blazor](UI/Blazor/Testing.md) + +### Visual Tests + +Visual Tests are used to interact with the application UI just like a real user does. It fully tests the application, including the visual appearance of the pages and components. + +Visual UI Testing is out of the scope for the ABP Framework. There are a lot of tooling in the industry (like [Selenium](https://www.selenium.dev/)) that you can use to test your application's UI. \ No newline at end of file diff --git a/docs/en/Text-Templating.md b/docs/en/Text-Templating.md index 07f3b141ab..b080087ba8 100644 --- a/docs/en/Text-Templating.md +++ b/docs/en/Text-Templating.md @@ -187,9 +187,9 @@ var result = await _templateRenderer.RenderAsync( In this case, we haven't created a model class, but created an anonymous object as the model. -### PascalCase vs camelCase +### PascalCase vs snake_case -PascalCase property names (like `UserName`) is used as camelCase (like `userName`) in the templates. +PascalCase property names (like `UserName`) is used as snake_case (like `user_name`) in the templates. ## Localization diff --git a/docs/en/Themes/Basic.md b/docs/en/Themes/Basic.md index a0165c803a..819138de5f 100644 --- a/docs/en/Themes/Basic.md +++ b/docs/en/Themes/Basic.md @@ -1,3 +1,2 @@ -## Basic Theme +This document has been moved to [here](../UI/AspNetCore/Basic-Theme.md). -TODO \ No newline at end of file diff --git a/docs/en/Tutorials/Part-10.md b/docs/en/Tutorials/Part-10.md index 2e0b1c4939..a9de3a062e 100644 --- a/docs/en/Tutorials/Part-10.md +++ b/docs/en/Tutorials/Part-10.md @@ -10,7 +10,7 @@ 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_Value}}** as the ORM provider. +* **{{DB_Value}}** as the ORM provider. * **{{UI_Value}}** as the UI Framework. This tutorial is organized as the following parts; @@ -38,7 +38,7 @@ This tutorial has multiple versions based on your **UI** and **Database** prefer We have created `Book` and `Author` functionalities for the book store application. However, currently there is no relation between these entities. -In this tutorial, we will establish a **1 to N** relation between the `Book` and the `Author`. +In this tutorial, we will establish a **1 to N** relation between the `Author` and the `Book` entities. ## Add Relation to The Book Entity @@ -50,7 +50,7 @@ public Guid AuthorId { get; set; } {{if DB=="EF"}} -> In this tutorial, we preferred to not add a **navigation property** to the `Author` entity from the `Book` class (like `public Author Author { get; set; }`). This is due to follow the DDD best practices (rule: refer to other aggregates only by id). However, you can add such a navigation property and configure it for the EF Core. In this way, you don't need to write join queries while getting books with their authors (just like we will done below) which makes your application code simpler. +> In this tutorial, we preferred to not add a **navigation property** to the `Author` entity from the `Book` class (like `public Author Author { get; set; }`). This is due to follow the DDD best practices (rule: refer to other aggregates only by id). However, you can add such a navigation property and configure it for the EF Core. In this way, you don't need to write join queries while getting books with their authors (like we will done below) which makes your application code simpler. {{end}} @@ -78,7 +78,7 @@ builder.Entity(b => b.ToTable(BookStoreConsts.DbTablePrefix + "Books", BookStoreConsts.DbSchema); b.ConfigureByConvention(); //auto configure for the base class props b.Property(x => x.Name).IsRequired().HasMaxLength(128); - + // ADD THE MAPPING FOR THE RELATION b.HasOne().WithMany().HasForeignKey(x => x.AuthorId).IsRequired(); }); @@ -384,8 +384,8 @@ namespace Acme.BookStore.Books return bookDto; } - public override async Task> - GetListAsync(PagedAndSortedResultRequestDto input) + public override async Task> GetListAsync( + PagedAndSortedResultRequestDto input) { await CheckGetListPolicyAsync(); @@ -485,7 +485,7 @@ namespace Acme.BookStore.Books DeletePolicyName = BookStorePermissions.Books.Create; } - public override async Task GetAsync(Guid id) + public async override Task GetAsync(Guid id) { await CheckGetPolicyAsync(); @@ -498,7 +498,7 @@ namespace Acme.BookStore.Books return bookDto; } - public override async Task> + public async override Task> GetListAsync(PagedAndSortedResultRequestDto input) { await CheckGetListPolicyAsync(); @@ -524,7 +524,7 @@ namespace Acme.BookStore.Books var authorDictionary = await GetAuthorDictionaryAsync(books); //Set AuthorName for the DTOs - bookDtos.ForEach(bookDto => bookDto.AuthorName = + bookDtos.ForEach(bookDto => bookDto.AuthorName = authorDictionary[bookDto.AuthorId].Name); //Get the total count with another query (required for the paging) @@ -622,7 +622,7 @@ namespace Acme.BookStore.Books result.Items.ShouldContain(b => b.Name == "1984" && b.AuthorName == "George Orwell"); } - + [Fact] public async Task Should_Create_A_Valid_Book() { @@ -645,7 +645,7 @@ namespace Acme.BookStore.Books result.Id.ShouldNotBe(Guid.Empty); result.Name.ShouldBe("New test book 42"); } - + [Fact] public async Task Should_Not_Create_A_Book_Without_Name() { @@ -911,6 +911,17 @@ You can run the application and try to create a new book or update an existing b {{else if UI=="NG"}} +### Service Proxy Generation + +Since the HTTP APIs have been changed, you need to update Angular client side [service proxies](../UI/Angular/Service-Proxies.md). Before running `generate-proxy` command, your host must be up and running. + +Run the following command in the `angular` folder (you may need to stop the angular application): + +```bash +abp generate-proxy +``` +This command will update the service proxy files under the `/src/app/proxy/` folder. + ### The Book List Book list page change is trivial. Open the `/src/app/book/book.component.html` and add the following column definition between the `Name` and `Type` columns: @@ -1082,36 +1093,37 @@ Add the following field to the `@code` section of the `Books.razor` file: IReadOnlyList authorList = Array.Empty(); ```` -And fill it in the `OnInitializedAsync` method, by adding the following code to the end of the method: +Override the `OnInitializedAsync` method and adding the following code: ````csharp -authorList = (await AppService.GetAuthorLookupAsync()).Items; +protected override async Task OnInitializedAsync() +{ + await base.OnInitializedAsync(); + authorList = (await AppService.GetAuthorLookupAsync()).Items; +} ```` +* It is essential to call the `base.OnInitializedAsync()` since `AbpCrudPageBase` has some initialization code to be executed. + The final `@code` block should be the following: ````csharp @code { - bool canCreateBook; - bool canEditBook; - bool canDeleteBook; - //ADDED A NEW FIELD IReadOnlyList authorList = Array.Empty(); + public Books() // Constructor + { + CreatePolicyName = BookStorePermissions.Books.Create; + UpdatePolicyName = BookStorePermissions.Books.Edit; + DeletePolicyName = BookStorePermissions.Books.Delete; + } + + //GET AUTHORS ON INITIALIZATION protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); - - canCreateBook = await - AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Create); - canEditBook = await - AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Edit); - canDeleteBook = await - AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Delete); - - //GET AUTHORS authorList = (await AppService.GetAuthorLookupAsync()).Items; } } @@ -1164,4 +1176,4 @@ Add the following `Field` definition into the `ModalBody` of the *Edit* modal, a That's all. We are reusing the `authorList` defined for the *Create* modal. -{{end}} \ No newline at end of file +{{end}} diff --git a/docs/en/Tutorials/Part-2.md b/docs/en/Tutorials/Part-2.md index e52fe7a46d..7bc42b1fc9 100644 --- a/docs/en/Tutorials/Part-2.md +++ b/docs/en/Tutorials/Part-2.md @@ -583,19 +583,18 @@ When you click to the Books menu item under the Book Store parent, you are being We will use the [Blazorise library](https://blazorise.com/) as the UI component kit. It is a very powerful library that supports major HTML/CSS frameworks, including the Bootstrap. -ABP Framework provides a generic base class, `BlazoriseCrudPageBase<...>`, to create CRUD style pages. This base class is compatible to the `ICrudAppService` that was used to build the `IBookAppService`. So, we can inherit from the `BlazoriseCrudPageBase` to automate the standard CRUD stuff. +ABP Framework provides a generic base class, `AbpCrudPageBase<...>`, to create CRUD style pages. This base class is compatible to the `ICrudAppService` that was used to build the `IBookAppService`. So, we can inherit from the `AbpCrudPageBase` to automate the code behind for the standard CRUD stuff. Open the `Books.razor` and replace the content as the following: ````xml @page "/books" @using Volo.Abp.Application.Dtos -@using Volo.Abp.BlazoriseUI @using Acme.BookStore.Books @using Acme.BookStore.Localization @using Microsoft.Extensions.Localization @inject IStringLocalizer L -@inherits BlazoriseCrudPageBase +@inherits AbpCrudPageBase @@ -620,14 +619,14 @@ Open the `Books.razor` and replace the content as the following: @context.PublishDate.ToShortDateString() If you see some syntax errors, you can ignore them if your application properly built and run. Visual Studio still has some bugs with Blazor. -* Inherited from the `BlazoriseCrudPageBase` which implements all the CRUD details for us. +* Inherited from the `AbpCrudPageBase` which implements all the CRUD details for us. * `Entities`, `TotalCount`, `PageSize`, `OnDataGridReadAsync` are defined in the base blass. * Injected `IStringLocalizer` (as `L` object) and used for localization. While the code above pretty easy to understand, you can check the Blazorise [Card](https://blazorise.com/docs/components/card/) and [DataGrid](https://blazorise.com/docs/extensions/datagrid/) documents to understand them better. -#### About the BlazoriseCrudPageBase +#### About the AbpCrudPageBase -We will continue to benefit from the `BlazoriseCrudPageBase` for the books page. You could just inject the `IBookAppService` and perform all the server side calls yourself (thanks to the [Dynamic C# HTTP API Client Proxy](../API/Dynamic-CSharp-API-Clients.md) system of the ABP Framework). We will do it manually for the authors page to demonstrate how to call server side HTTP APIs in your Blazor applications. +We will continue to benefit from the `AbpCrudPageBase` for the books page. You could just inject the `IBookAppService` and perform all the server side calls yourself (thanks to the [Dynamic C# HTTP API Client Proxy](../API/Dynamic-CSharp-API-Clients.md) system of the ABP Framework). We will do it manually for the authors page to demonstrate how to call server side HTTP APIs in your Blazor applications. ## Run the Final Application diff --git a/docs/en/Tutorials/Part-3.md b/docs/en/Tutorials/Part-3.md index 079b9e7cf8..2106e82069 100644 --- a/docs/en/Tutorials/Part-3.md +++ b/docs/en/Tutorials/Part-3.md @@ -1163,7 +1163,7 @@ Clicking the "Delete" action calls the `delete` method which then shows a confir ## Creating a New Book -In this section, you will learn how to create a new modal dialog form to create a new book. Since we've inherited from the `BlazoriseCrudPage`, we only need to develop the view part. +In this section, you will learn how to create a new modal dialog form to create a new book. Since we've inherited from the `AbpCrudPageBase`, we only need to develop the view part. ### Add "New Button" Button @@ -1171,15 +1171,13 @@ Open the `Books.razor` and replace the `` section with the following ````xml - - + +

@L["Books"]

- - - - + +
@@ -1196,48 +1194,67 @@ Now, we can add a modal that will be opened when we click to the button. Open the `Books.razor` and add the following code to the end of the page: ````xml - + - - @L["NewBook"] - - - - - @L["Name"] - - - - @L["Type"] - - - - @L["PublishDate"] - - - - @L["Price"] - - - - - - - +
+ + @L["NewBook"] + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
```` +This code requires a service; Inject the `AbpBlazorMessageLocalizerHelper` at the top of the file, just before the `@inherits...` line: + +````csharp +@inject AbpBlazorMessageLocalizerHelper LH +```` + +* The form implements validation and the `AbpBlazorMessageLocalizerHelper` is used to simply localize the validation messages. * `CreateModal` object, `CloseCreateModalAsync` and `CreateEntityAsync` method are defined by the base class. See the [Blazorise documentation](https://blazorise.com/docs/) if you want to understand the `Modal` and the other components. That's all. Run the application and try to add a new book: @@ -1250,85 +1267,88 @@ Editing a books is similar to the creating a new book. ### Actions Dropdown -Open the `Books.razor` and add the following `DataGridColumn` section inside the `DataGridColumns` as the first item: +Open the `Books.razor` and add the following `DataGridEntityActionsColumn` section inside the `DataGridColumns` as the first item: ````xml - + - - - @L["Actions"] - - - - @L["Edit"] - - - + + + - + ```` -* `OpenEditModalAsync` is defined in the base class which takes the `Id` of the entity (book) to edit. +* `OpenEditModalAsync` is defined in the base class which takes the entity (book) to edit. -This adds an "Actions" dropdown to all the books inside the `DataGrid` with an `Edit` action: +`DataGridEntityActionsColumn` component is used to show an "Actions" dropdown for each row in the `DataGrid`. `DataGridEntityActionsColumn` shows a **single button** instead of a dropdown if there is only one available action inside it: -![blazor-edit-book-action](images/blazor-edit-book-action.png) +![blazor-edit-book-action](images/blazor-edit-book-action-2.png) ### Edit Modal We can now define a modal to edit the book. Add the following code to the end of the `Books.razor` page: ````xml - + - - @EditingEntity.Name - - - - - @L["Name"] - - - - @L["Type"] - - - - @L["PublishDate"] - - - - @L["Price"] - - - - - - - +
+ + @EditingEntity.Name + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
```` ### AutoMapper Configuration -The base `BlazoriseCrudPage` uses the [object to object mapping](../Object-To-Object-Mapping.md) system to convert an incoming `BookDto` object to a `CreateUpdateBookDto` object. So, we need to define the mapping. +The base `AbpCrudPageBase` uses the [object to object mapping](../Object-To-Object-Mapping.md) system to convert an incoming `BookDto` object to a `CreateUpdateBookDto` object. So, we need to define the mapping. Open the `BookStoreBlazorAutoMapperProfile` inside the `Acme.BookStore.Blazor` project and change the content as the following: @@ -1356,17 +1376,26 @@ You can now run the application and try to edit a book. ![blazor-edit-book-modal](images/blazor-edit-book-modal.png) +> Tip: Try to leave the *Name* field empty and submit the form to show the validation error message. + ## Deleting a Book -Open the `Books.razor` page and add the following `DropdownItem` under the "Edit" action inside the "Actions" `DropdownMenu`: +Open the `Books.razor` page and add the following `EntityAction` under the "Edit" action inside the `EntityActions`: ````xml - - @L["Delete"] - + ```` -* `DeleteEntityAsync` is defined in the base class. +* `DeleteEntityAsync` is defined in the base class that deletes the entity by performing a call to the server. +* `ConfirmationMessage` is a callback to show a confirmation message before executing the action. +* `GetDeleteConfirmationMessage` is defined in the base class. You can override this method (or pass another value to the `ConfirmationMessage` parameter) to customize the localization message. + +The "Actions" button becomes a dropdown since it has two actions now: + +![blazor-edit-book-action](images/blazor-delete-book-action.png) Run the application and try to delete a book. @@ -1377,24 +1406,22 @@ Here the complete code to create the book management CRUD page, that has been de ````xml @page "/books" @using Volo.Abp.Application.Dtos -@using Volo.Abp.BlazoriseUI @using Acme.BookStore.Books @using Acme.BookStore.Localization @using Microsoft.Extensions.Localization @inject IStringLocalizer L -@inherits BlazoriseCrudPageBase +@inject AbpBlazorMessageLocalizerHelper LH +@inherits AbpCrudPageBase - - + +

@L["Books"]

- - - - + +
@@ -1406,27 +1433,19 @@ Here the complete code to create the book management CRUD page, that has been de ShowPager="true" PageSize="PageSize"> - + - - - @L["Actions"] - - - - @L["Edit"] - - - @L["Delete"] - - - + + + + - + @@ -1460,85 +1479,109 @@ Here the complete code to create the book management CRUD page, that has been de
- + - - @L["NewBook"] - - - - - @L["Name"] - - - - @L["Type"] - - - - @L["PublishDate"] - - - - @L["Price"] - - - - - - - +
+ + @L["NewBook"] + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
- + - - @EditingEntity.Name - - - - - @L["Name"] - - - - @L["Type"] - - - - @L["PublishDate"] - - - - @L["Price"] - - - - - - - +
+ + @EditingEntity.Name + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
```` diff --git a/docs/en/Tutorials/Part-4.md b/docs/en/Tutorials/Part-4.md index 9c31f4fd3c..8dab28a8db 100644 --- a/docs/en/Tutorials/Part-4.md +++ b/docs/en/Tutorials/Part-4.md @@ -75,9 +75,12 @@ If you had created a data seed contributor as described in the [first part](Part Add a new test class, named `BookAppService_Tests` in the `Books` namespace (folder) of the `Acme.BookStore.Application.Tests` project: ````csharp +using System; +using System.Linq; using System.Threading.Tasks; using Shouldly; using Volo.Abp.Application.Dtos; +using Volo.Abp.Validation; using Xunit; namespace Acme.BookStore.Books @@ -123,7 +126,7 @@ public async Task Should_Create_A_Valid_Book() { Name = "New test book 42", Price = 10, - PublishDate = System.DateTime.Now, + PublishDate = DateTime.Now, Type = BookType.ScienceFiction } ); @@ -205,7 +208,7 @@ namespace Acme.BookStore.Books { Name = "New test book 42", Price = 10, - PublishDate = System.DateTime.Now, + PublishDate = DateTime.Now, Type = BookType.ScienceFiction } ); diff --git a/docs/en/Tutorials/Part-5.md b/docs/en/Tutorials/Part-5.md index 815addd224..29374419cb 100644 --- a/docs/en/Tutorials/Part-5.md +++ b/docs/en/Tutorials/Part-5.md @@ -70,7 +70,7 @@ namespace Acme.BookStore.Permissions } ```` -This is a hierarchical way of defining permission names. For example, "create book" permission name was defined as `BookStore.Books.Create`. +This is a hierarchical way of defining permission names. For example, "create book" permission name was defined as `BookStore.Books.Create`. ABP doesn't force you to a structure, but we find this way useful. ### Permission Definitions @@ -423,13 +423,13 @@ Open the `/src/app/book/book.component.html` file and replace the create button ````html - ```` -* Just added `abpPermission="BookStore.Books.Create"` that hides the button if the current user has no permission. +* Just added `*abpPermission="'BookStore.Books.Create'"` that hides the button if the current user has no permission. ### Hide the Edit and Delete Actions @@ -443,24 +443,24 @@ Open the `/src/app/book/book.component.html` file and replace the edit and delet ````html - - ```` -* Added `abpPermission="BookStore.Books.Edit"` that hides the edit action if the current user has no editing permission. -* Added `abpPermission="BookStore.Books.Delete"` that hides the delete action if the current user has no delete permission. +* Added `*abpPermission="'BookStore.Books.Edit'"` that hides the edit action if the current user has no editing permission. +* Added `*abpPermission="'BookStore.Books.Delete'"` that hides the delete action if the current user has no delete permission. {{else if UI == "Blazor"}} ### Authorize the Razor Component -Open the `/Pages/Books.razor` file in the `Acme.BookStore.Blazor` project and add an `Authorize` attribute just after the `@page` directive, as shown below: +Open the `/Pages/Books.razor` file in the `Acme.BookStore.Blazor` project and add an `Authorize` attribute just after the `@page` directive and the following namespace imports (`@using` lines), as shown below: ````html @page "/books" @@ -476,37 +476,29 @@ Adding this attribute prevents to enter this page if the current hasn't logged i The book management page has a *New Book* button and *Edit* and *Delete* actions for each book. We should hide these buttons/actions if the current user has not granted for the related permissions. -#### Inject the IAuthorizationService +The base `AbpCrudPageBase` class already has the necessary functionality for these kind of operations. -Inject the `IAuthorizationService` into the `Books.razor`: - -````csharp -@inject IAuthorizationService AuthorizationService -```` - -#### Get the Permissions On Initialization +#### Set the Policy (Permission) Names Add the following code block to the end of the `Books.razor` file: ````csharp @code { - bool canCreateBook; - bool canEditBook; - bool canDeleteBook; - - protected override async Task OnInitializedAsync() + public Books() // Constructor { - await base.OnInitializedAsync(); - - canCreateBook =await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Create); - canEditBook = await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Edit); - canDeleteBook = await AuthorizationService.IsGrantedAsync(BookStorePermissions.Books.Delete); + CreatePolicyName = BookStorePermissions.Books.Create; + UpdatePolicyName = BookStorePermissions.Books.Edit; + DeletePolicyName = BookStorePermissions.Books.Delete; } } ```` -We will use these `bool` fields to check the permissions. +The base `AbpCrudPageBase` class automatically checks these permissions on the related operations. It also defines the given properties for us if we need to check them manually: + +* `HasCreatePermission`: True, if the current user has permission to create the entity. +* `HasUpdatePermission`: True, if the current user has permission to edit/update the entity. +* `HasDeletePermission`: True, if the current user has permission to delete the entity. > **Blazor Tip**: While adding the C# code into a `@code` block is fine for small code parts, it is suggested to use the code behind approach to develop a more maintainable code base when the code block becomes longer. We will use this approach for the authors part. @@ -515,7 +507,7 @@ We will use these `bool` fields to check the permissions. Wrap the *New Book* button by an `if` block as shown below: ````xml -@if (canCreateBook) +@if (HasCreatePermission) { @@ -524,28 +516,29 @@ Wrap the *New Book* button by an `if` block as shown below: #### Hide the Edit/Delete Actions -As similar to the *New Book* button, we can use `if` blocks to conditionally show/hide the *Edit* and *Delete* actions: +`EntityAction` component defines `RequiredPolicy` attribute (parameter) to conditionally show the action based on the user permissions. + +Update the `EntityActions` section as shown below: ````xml -@if (canEditBook) -{ - - @L["Edit"] - -} -@if (canDeleteBook) -{ - - @L["Delete"] - -} + + + + ```` #### About the Permission Caching You can run and test the permissions. Remove a book related permission from the admin role to see the related button/action disappears from the UI. -However, ABP Framework caches the permissions of the current user in the client side. So, when you change a permission for yourself, you need to manually **refresh the page** to take the effect. If you don't refresh and try to use the prohibited action you get an HTTP 403 (forbidden) response from the server. +**ABP Framework caches the permissions** of the current user in the client side. So, when you change a permission for yourself, you need to manually **refresh the page** to take the effect. If you don't refresh and try to use the prohibited action you get an HTTP 403 (forbidden) response from the server. > Changing a permission for a role or user immediately available on the server side. So, this cache system doesn't cause any security problem. @@ -593,54 +586,39 @@ if (await context.IsGrantedAsync(BookStorePermissions.Books.Default)) } ```` -You also need to add `async` keyword to the `ConfigureMenuAsync` method and re-arrange the return values. The final `BookStoreMenuContributor` class should be the following: +You also need to add `async` keyword to the `ConfigureMenuAsync` method and re-arrange the return value. The final `ConfigureMainMenuAsync` method should be the following: ````csharp -using System.Threading.Tasks; -using Acme.BookStore.Localization; -using Acme.BookStore.Permissions; -using Volo.Abp.UI.Navigation; - -namespace Acme.BookStore.Blazor +private async Task ConfigureMainMenuAsync(MenuConfigurationContext context) { - public class BookStoreMenuContributor : IMenuContributor - { - public async Task ConfigureMenuAsync(MenuConfigurationContext context) - { - if(context.Menu.DisplayName != StandardMenus.Main) - { - return; - } + var l = context.GetLocalizer(); - var l = context.GetLocalizer(); - - context.Menu.Items.Insert( - 0, - new ApplicationMenuItem( - "BookStore.Home", - l["Menu:Home"], - "/", - icon: "fas fa-home" - ) - ); + context.Menu.Items.Insert( + 0, + new ApplicationMenuItem( + "BookStore.Home", + l["Menu:Home"], + "/", + icon: "fas fa-home" + ) + ); - var bookStoreMenu = new ApplicationMenuItem( - "BooksStore", - l["Menu:BookStore"], - icon: "fa fa-book" - ); + var bookStoreMenu = new ApplicationMenuItem( + "BooksStore", + l["Menu:BookStore"], + icon: "fa fa-book" + ); - context.Menu.AddItem(bookStoreMenu); + context.Menu.AddItem(bookStoreMenu); - if (await context.IsGrantedAsync(BookStorePermissions.Books.Default)) - { - bookStoreMenu.AddItem(new ApplicationMenuItem( - "BooksStore.Books", - l["Menu:Books"], - url: "/books" - )); - } - } + //CHECK the PERMISSION + if (await context.IsGrantedAsync(BookStorePermissions.Books.Default)) + { + bookStoreMenu.AddItem(new ApplicationMenuItem( + "BooksStore.Books", + l["Menu:Books"], + url: "/books" + )); } } ```` diff --git a/docs/en/Tutorials/Part-7.md b/docs/en/Tutorials/Part-7.md index 32c9f6b9a4..5cae52a4b1 100644 --- a/docs/en/Tutorials/Part-7.md +++ b/docs/en/Tutorials/Part-7.md @@ -74,6 +74,10 @@ Open the **Package Manager Console** on Visual Studio and ensure that the **Defa Run the following command to create a new database migration: +````bash +Add-Migration "Added_Authors" +```` + ![bookstore-add-migration-authors](images/bookstore-add-migration-authors.png) This will create a new migration class. Then run the `Update-Database` command to create the table on the database. diff --git a/docs/en/Tutorials/Part-9.md b/docs/en/Tutorials/Part-9.md index 841d2fb3cb..65a59f39e1 100644 --- a/docs/en/Tutorials/Part-9.md +++ b/docs/en/Tutorials/Part-9.md @@ -843,15 +843,8 @@ Create a new Razor Component Page, `/Pages/Authors.razor`, in the `Acme.BookStor ````xml @page "/authors" @using Acme.BookStore.Authors -@using Acme.BookStore.Localization -@using Microsoft.AspNetCore.Authorization -@using Microsoft.Extensions.Localization -@using Volo.Abp.ObjectMapping +@inherits BookStoreComponentBase @inject IAuthorAppService AuthorAppService -@inject IStringLocalizer L -@inject IAuthorizationService AuthorizationService -@inject IUiMessageService UiMessageService -@inject IObjectMapper ObjectMapper @@ -1048,10 +1041,10 @@ namespace Acme.BookStore.Blazor.Pages { CanCreateAuthor = await AuthorizationService .IsGrantedAsync(BookStorePermissions.Authors.Create); - + CanEditAuthor = await AuthorizationService .IsGrantedAsync(BookStorePermissions.Authors.Edit); - + CanDeleteAuthor = await AuthorizationService .IsGrantedAsync(BookStorePermissions.Authors.Delete); } @@ -1105,7 +1098,7 @@ namespace Acme.BookStore.Blazor.Pages private async Task DeleteAuthorAsync(AuthorDto author) { var confirmMessage = L["AuthorDeletionConfirmationMessage", author.Name]; - if (!await UiMessageService.ConfirmAsync(confirmMessage)) + if (!await Message.Confirm(confirmMessage)) { return; } @@ -1177,6 +1170,20 @@ We should complete the localizations we've used above. Open the `en.json` file u "NewAuthor": "New author" ```` +### Run the Application + +Run and login to the application. **If you don't see the Authors menu item under the Book Store menu, that means you don't have the permission yet.** Go to the `identity/roles` page, click to the *Actions* button and select the *Permissions* action for the **admin role**: + +![bookstore-author-permissions](images/bookstore-author-permissions.png) + +As you see, the admin role has no *Author Management* permissions yet. Click to the checkboxes and save the modal to grant the necessary permissions. You will see the *Authors* menu item under the *Book Store* in the main menu, after **refreshing the page**: + +![bookstore-authors-page](images/bookstore-authors-blazor-ui.png) + +That's all! This is a fully working CRUD page, you can create, edit and delete the authors. + +> **Tip**: If you run the `.DbMigrator` console application after defining a new permission, it automatically grants these new permissions to the admin role and you don't need to manually grant the permissions yourself. + {{end}} ## The Next Part diff --git a/docs/en/Tutorials/images/blazor-bookstore-book-list.png b/docs/en/Tutorials/images/blazor-bookstore-book-list.png index 91450f47c2..18bb26ccb1 100644 Binary files a/docs/en/Tutorials/images/blazor-bookstore-book-list.png and b/docs/en/Tutorials/images/blazor-bookstore-book-list.png differ diff --git a/docs/en/Tutorials/images/blazor-delete-book-action.png b/docs/en/Tutorials/images/blazor-delete-book-action.png new file mode 100644 index 0000000000..f2b0b83f30 Binary files /dev/null and b/docs/en/Tutorials/images/blazor-delete-book-action.png differ diff --git a/docs/en/Tutorials/images/blazor-edit-book-action-2.png b/docs/en/Tutorials/images/blazor-edit-book-action-2.png new file mode 100644 index 0000000000..70856ab325 Binary files /dev/null and b/docs/en/Tutorials/images/blazor-edit-book-action-2.png differ diff --git a/docs/en/Tutorials/images/bookstore-authors-blazor-ui.png b/docs/en/Tutorials/images/bookstore-authors-blazor-ui.png new file mode 100644 index 0000000000..5b9480957d Binary files /dev/null and b/docs/en/Tutorials/images/bookstore-authors-blazor-ui.png differ diff --git a/docs/en/UI/Angular/Component-Replacement.md b/docs/en/UI/Angular/Component-Replacement.md index 577129e139..6df847d6d0 100644 --- a/docs/en/UI/Angular/Component-Replacement.md +++ b/docs/en/UI/Angular/Component-Replacement.md @@ -45,7 +45,7 @@ Run the following command to generate a layout in `angular` folder: yarn ng generate component my-application-layout ``` -Add the following code in your layout template (`my-layout.component.html`) where you want the page to be loaded. +Add the following code in your layout template (`my-application-layout.component.html`) where you want the page to be loaded. ```html @@ -547,7 +547,3 @@ The final UI looks like below: ## See Also - [How to Replace PermissionManagementComponent](./Permission-Management-Component-Replacement.md) - -## What's Next? - -- [Custom Setting Page](./Custom-Setting-Page.md) diff --git a/docs/en/UI/Angular/Config-State-Service.md b/docs/en/UI/Angular/Config-State-Service.md new file mode 100644 index 0000000000..c810562623 --- /dev/null +++ b/docs/en/UI/Angular/Config-State-Service.md @@ -0,0 +1,135 @@ +# Config State Service + +`ConfigStateService` is a singleton service, i.e. provided in root level of your application, and keeps the application configuration response in the internal store. + +## Before Use + +In order to use the `ConfigStateService` you must inject it in your class as a dependency. + +```js +import { ConfigStateService } from '@abp/ng.core'; + +@Component({ + /* class metadata here */ +}) +class DemoComponent { + constructor(private config: ConfigStateService) {} +} +``` + +You do not have to provide the `ConfigStateService` at module or component/directive level, because it is already **provided in root**. + +## Get Methods + +`ConfigStateService` has numerous get methods which allow you to get a specific configuration or all configurations. + +Get methods with "$" at the end of the method name (e.g. `getAll$`) return an RxJs stream. The streams are triggered when set or patched the state. + +### How to Get All Configurations + +You can use the `getAll` or `getAll$` method of `ConfigStateService` to get all of the applcation configuration response object. It is used as follows: + +```js +// this.config is instance of ConfigStateService + +const config = this.config.getAll(); + +// or +this.config.getAll$().subscribe(config => { + // use config here +}) +``` + +### How to Get a Specific Configuration + +You can use the `getOne` or `getOne$` method of `ConfigStateService` to get a specific configuration property. For that, the property name should be passed to the method as parameter. + +```js +// this.config is instance of ConfigStateService + +const currentUser = this.config.getOne("currentUser"); + +// or +this.config.getOne$("currentUser").subscribe(currentUser => { + // use currentUser here +}) +``` + +On occasion, you will probably want to be more specific than getting just the current user. For example, here is how you can get the `tenantId`: + +```js +const tenantId = this.config.getDeep("currentUser.tenantId"); + +// or +this.config.getDeep$("currentUser.tenantId").subscribe(tenantId => { + // use tenantId here +}) +``` + +or by giving an array of keys as parameter: + +```js +const tenantId = this.config.getDeep(["currentUser", "tenantId"]); +``` + +FYI, `getDeep` is able to do everything `getOne` does. Just keep in mind that `getOne` is slightly faster. + +### How to Get a Feature + +You can use the `getFeature` or `getFeature$` method of `ConfigStateService` to get a feature value. For that, the feature name should be passed to the method as parameter. + +```js +// this.config is instance of ConfigStateService + +const enableLdapLogin = this.configStateService.getFeature("Account.EnableLdapLogin"); + +// or +this.config.getFeature$("Account.EnableLdapLogin").subscribe(enableLdapLogin => { + // use enableLdapLogin here +}) +``` + +> For more information, see the [features document](./Features). + +### How to Get a Setting + +You can use the `getSetting` or `getSetting$` method of `ConfigStateService` to get a setting. For that, the setting name should be passed to the method as parameter. + +```js +// this.config is instance of ConfigStateService + +const twoFactorBehaviour = this.configStateService.getSetting("Abp.Identity.TwoFactor.Behaviour"); + +// or +this.config.getSetting$("Abp.Identity.TwoFactor.Behaviour").subscribe(twoFactorBehaviour => { + // use twoFactorBehaviour here +}) +``` + +> For more information, see the [settings document](./Settings). + +#### State Properties + +Please refer to `ApplicationConfiguration.Response` type for all the properties you can get with `getOne` and `getDeep`. It can be found in the [application-configuration.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/application-configuration.ts#L4). + + +## Set State + +`ConfigStateService` has a method named `setState` which allow you to set the state value. + +You can get the application configuration response and set the `ConfigStateService` state value as shown below: + +```js +import {ApplicationConfigurationService, ConfigStateService} from '@abp/ng.core'; + +constructor(private applicationConfigurationService: ApplicationConfigurationService, private config: ConfigStateService) { + this.applicationConfigurationService.getConfiguration().subscribe(config => { + this.config.setState(config); + }) +} +``` + +## See Also + +- [Settings](./Settings.md) +- [Features](./Features.md) diff --git a/docs/en/UI/Angular/Config-State.md b/docs/en/UI/Angular/Config-State.md index 0c1070f54d..d6774bb0cb 100644 --- a/docs/en/UI/Angular/Config-State.md +++ b/docs/en/UI/Angular/Config-State.md @@ -1,236 +1 @@ -# Config State - -`ConfigStateService` is a singleton service, i.e. provided in root level of your application, and is actually a façade for interacting with application configuration state in the `Store`. - -## Before Use - -In order to use the `ConfigStateService` you must inject it in your class as a dependency. - -```js -import { ConfigStateService } from '@abp/ng.core'; - -@Component({ - /* class metadata here */ -}) -class DemoComponent { - constructor(private config: ConfigStateService) {} -} -``` - -You do not have to provide the `ConfigStateService` at module or component/directive level, because it is already **provided in root**. - -## Selector Methods - -`ConfigStateService` has numerous selector methods which allow you to get a specific configuration or all configurations from the `Store`. - -### How to Get All Configurations From the Store - -You can use the `getAll` method of `ConfigStateService` to get all of the configuration object from the store. It is used as follows: - -```js -// this.config is instance of ConfigStateService - -const config = this.config.getAll(); -``` - -### How to Get a Specific Configuration From the Store - -You can use the `getOne` method of `ConfigStateService` to get a specific configuration property from the store. For that, the property name should be passed to the method as parameter. - -```js -// this.config is instance of ConfigStateService - -const currentUser = this.config.getOne("currentUser"); -``` - -On occasion, you will probably want to be more specific than getting just the current user. For example, here is how you can get the `tenantId`: - -```js -const tenantId = this.config.getDeep("currentUser.tenantId"); -``` - -or by giving an array of keys as parameter: - -```js -const tenantId = this.config.getDeep(["currentUser", "tenantId"]); -``` - -FYI, `getDeep` is able to do everything `getOne` does. Just keep in mind that `getOne` is slightly faster. - -#### Config State Properties - -Please refer to `Config.State` type for all the properties you can get with `getOne` and `getDeep`. It can be found in the [config.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L7). - -### How to Get the Application Information From the Store - -The `getApplicationInfo` method is used to get the application information from the environment variables stored as the config state. This is how you can use it: - -```js -// this.config is instance of ConfigStateService - -const appInfo = this.config.getApplicationInfo(); -``` - -This method never returns `undefined` or `null` and returns an empty object literal (`{}`) instead. In other words, you will never get an error when referring to the properties of `appInfo` above. - -#### Application Information Properties - -Please refer to `Config.Application` type for all the properties you can get with `getApplicationInfo`. It can be found in the [config.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L21). - -### How to Get API URL From the Store - -The `getApplicationInfo` method is used to get a specific API URL from the environment variables stored as the config state. This is how you can use it: - -```js -// this.config is instance of ConfigStateService - -const apiUrl = this.config.getApiUrl(); -// environment.apis.default.url - -const searchUrl = this.config.getApiUrl("search"); -// environment.apis.search.url -``` - -This method returns the `url` of a specific API based on the key given as its only parameter. If there is no key, `'default'` is used. - -### How to Get All Settings From the Store - -You can use the `getSettings` method of `ConfigStateService` to get all of the settings object from the configuration state. Here is how you get all settings: - -```js -// this.config is instance of ConfigStateService - -const settings = this.config.getSettings(); -``` - -In addition, the method lets you search settings by **passing a keyword** to it. - -```js -const localizationSettings = this.config.getSettings("Localization"); -/* -{ - 'Abp.Localization.DefaultLanguage': 'en' -} -*/ -``` - -Beware though, **settings search is case sensitive**. - -### How to Get a Specific Setting From the Store - -You can use the `getSetting` method of `ConfigStateService` to get a specific setting from the configuration state. Here is an example: - -```js -// this.config is instance of ConfigStateService - -const defaultLang = this.config.getSetting("Abp.Localization.DefaultLanguage"); -// 'en' -``` - -### How to Get a Specific Feature From the Store - -You can use the `getFeature` method of `ConfigStateService` to get a specific feature from the configuration state. Here is an example: - -```js -// this.config is instance of ConfigStateService - -const isChatEnabled = this.config.getFeature("Chat.Enable"); -// 'en' -``` - -### How to Get a Specific Permission From the Store - -You can use the `getGrantedPolicy` method of `ConfigStateService` to get a specific permission from the configuration state. For that, you should pass a policy key as parameter to the method. - -```js -// this.config is instance of ConfigStateService - -const hasIdentityPermission = this.config.getGrantedPolicy("Abp.Identity"); -// true -``` - -You may also **combine policy keys** to fine tune your selection: - -```js -// this.config is instance of ConfigStateService - -const hasIdentityAndAccountPermission = this.config.getGrantedPolicy( - "Abp.Identity && Abp.Account" -); -// false - -const hasIdentityOrAccountPermission = this.config.getGrantedPolicy( - "Abp.Identity || Abp.Account" -); -// true -``` - -Please consider the following **rules** when creating your permission selectors: - -- Maximum 2 keys can be combined. -- `&&` operator looks for both keys. -- `||` operator looks for either key. -- Empty string `''` as key will return `true` -- Using an operator without a second key will return `false` - -### How to Get Translations From the Store - -The `getLocalization` method of `ConfigStateService` is used for translations. Here are some examples: - -```js -// this.config is instance of ConfigStateService - -const identity = this.config.getLocalization("AbpIdentity::Identity"); -// 'identity' - -const notFound = this.config.getLocalization("AbpIdentity::IDENTITY"); -// 'AbpIdentity::IDENTITY' - -const defaultValue = this.config.getLocalization({ - key: "AbpIdentity::IDENTITY", - defaultValue: "IDENTITY" -}); -// 'IDENTITY' -``` - -Please check out the [localization documentation](./Localization.md) for details. - -## Dispatch Methods - -`ConfigStateService` has several dispatch methods which allow you to conveniently dispatch predefined actions to the `Store`. - -### How to Get Application Configuration From Server - -The `dispatchGetAppConfiguration` triggers a request to an endpoint that responds with the application state and then places this response to the `Store` as configuration state. - -```js -// this.config is instance of ConfigStateService - -this.config.dispatchGetAppConfiguration(); -// returns a state stream which emits after dispatch action is complete -``` - -Note that **you do not have to call this method at application initiation**, because the application configuration is already being received from the server at start. - -### How to Set the Environment - -The `dispatchSetEnvironment` places environment variables passed to it in the `Store` under the configuration state. Here is how it is used: - -```js -// this.config is instance of ConfigStateService - -this.config.dispatchSetEnvironment({ - /* environment properties here */ -}); -// returns a state stream which emits after dispatch action is complete -``` - -Note that **you do not have to call this method at application initiation**, because the environment variables are already being stored at start. - -#### Environment Properties - -Please refer to `Config.Environment` type for all the properties you can pass to `dispatchSetEnvironment` as parameter. It can be found in the [config.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L13). - -## What's Next? - -- [HTTP Requests](./Http-Requests) +**ConfigState has been deprecated.** Use the [ConfigStateService](./Config-State-Service) instead. \ No newline at end of file diff --git a/docs/en/UI/Angular/Confirmation-Service.md b/docs/en/UI/Angular/Confirmation-Service.md index 16dfa9fd94..ef48332580 100644 --- a/docs/en/UI/Angular/Confirmation-Service.md +++ b/docs/en/UI/Angular/Confirmation-Service.md @@ -180,8 +180,3 @@ clear( ``` - `status` parameter is the value of the confirmation closing event. - - -## What's Next? - -- [Toast Overlay](./Toaster-Service.md) diff --git a/docs/en/UI/Angular/Content-Projection-Service.md b/docs/en/UI/Angular/Content-Projection-Service.md index 7e03776835..ee64f57e20 100644 --- a/docs/en/UI/Angular/Content-Projection-Service.md +++ b/docs/en/UI/Angular/Content-Projection-Service.md @@ -71,8 +71,3 @@ projectContent | TemplateRef>( - `projectionStrategy` parameter is the primary focus here and is explained above. - `injector` parameter is the `Injector` instance you can pass to the projected content. It is not used in `TemplateProjectionStrategy`. - - -## What's Next? - -- [Confirmation Popup](./Confirmation-Service.md) diff --git a/docs/en/UI/Angular/Cross-Origin-Strategy.md b/docs/en/UI/Angular/Cross-Origin-Strategy.md index e626bf5011..5edcbed9e6 100644 --- a/docs/en/UI/Angular/Cross-Origin-Strategy.md +++ b/docs/en/UI/Angular/Cross-Origin-Strategy.md @@ -51,10 +51,3 @@ CROSS_ORIGIN_STRATEGY.UseCredentials(integrity?: string) ``` `crossorigin` will be set as `"use-credentials"` and `integrity` is optional. - - - - -## What's Next? - -- [LoadingStrategy](./Loading-Strategy.md) diff --git a/docs/en/UI/Angular/Dom-Insertion-Service.md b/docs/en/UI/Angular/Dom-Insertion-Service.md index d56e4f8b0e..78e01c59fb 100644 --- a/docs/en/UI/Angular/Dom-Insertion-Service.md +++ b/docs/en/UI/Angular/Dom-Insertion-Service.md @@ -134,7 +134,3 @@ has(content: string): boolean The `has` method returns a boolean value that indicates the given content has already been added to the DOM or not. - `content` parameter is the content of the inserted `HTMLScriptElement` or `HTMLStyleElement` element. - -## What's Next? - -- [Lazy Loading Scripts & Styles](./Lazy-Load-Service.md) diff --git a/docs/en/UI/Angular/Environment.md b/docs/en/UI/Angular/Environment.md index 1b78a11cc6..8c6fb28ce7 100644 --- a/docs/en/UI/Angular/Environment.md +++ b/docs/en/UI/Angular/Environment.md @@ -102,7 +102,80 @@ export interface RemoteEnv { * `method`: HTTP method to be used when retrieving environment config. Default: `GET` * `headers`: If extra headers are needed for the request, it can be set through this field. +## EnvironmentService -## What's Next? +` EnvironmentService` is a singleton service, i.e. provided in root level of your application, and keeps the environment in the internal store. -- [About Feature Libraries](./Feature-Libraries.md) + +### Before Use + +In order to use the `EnvironmentService` you must inject it in your class as a dependency. + +```js +import { EnvironmentService } from '@abp/ng.core'; + +@Component({ + /* class metadata here */ +}) +class DemoComponent { + constructor(private environment: EnvironmentService) {} +} +``` + +You do not have to provide the `EnvironmentService` at module or component/directive level, because it is already **provided in root**. + + +### Get Methods + +`EnvironmentService` has numerous get methods which allow you to get a specific value or all environment object. + +Get methods with "$" at the end of the method name (e.g. `getEnvironment$`) return an RxJs stream. The streams are triggered when set or patched the state. + +#### How to Get Environment Object + +You can use the `getEnvironment` or `getEnvironment$` method of `EnvironmentService` to get all of the environment object. It is used as follows: + +```js +// this.environment is instance of EnvironmentService + +const environment = this.environment.getAll(); + +// or +this.environment.getAll$().subscribe(environment => { + // use environment here +}) +``` + +#### How to Get API URL + +The `getApiUrl` or `getApiUrl$` method is used to get a specific API URL from the environment object. This is how you can use it: + +```js +// this.environment is instance of EnvironmentService + +const apiUrl = this.environment.getApiUrl(); +// environment.apis.default.url + +this.environment.getApiUrl$("search").subscribe(searchUrl => { +// environment.apis.search.url +}) +``` + +This method returns the `url` of a specific API based on the key given as its only parameter. If there is no key, `'default'` is used. + + +#### How to Set the Environment + +`EnvironmentService` has a method named `setState` which allow you to set the state value. + +```js +// this.environment is instance of EnvironmentService + +this.environment.setState(newEnvironmentObject); +``` + +Note that **you do not have to call this method at application initiation**, because the environment variables are already being stored at start. + +#### Environment Properties + +Please refer to `Environment` type for all the properties. It can be found in the [config.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L13). \ No newline at end of file diff --git a/docs/en/UI/Angular/Feature-Libraries.md b/docs/en/UI/Angular/Feature-Libraries.md index 937bae7245..bdfff93371 100644 --- a/docs/en/UI/Angular/Feature-Libraries.md +++ b/docs/en/UI/Angular/Feature-Libraries.md @@ -90,9 +90,3 @@ Depending on the library, the `.forLazy` static method may also receive some opt --- 1 _Libraries expect to work at a predefined path. Please check [how to patch a navigation element](./Modifying-the-Menu.md#how-to-patch-or-remove-a-navigation-element), if you want to use a different path from the default one (e.g. '/identity')._ [↩](#a-modify-route) - ---- - -## What's Next? - -- [Service Proxies](./Service-Proxies.md) diff --git a/docs/en/UI/Angular/Features.md b/docs/en/UI/Angular/Features.md index f749030a26..3278bfd988 100644 --- a/docs/en/UI/Angular/Features.md +++ b/docs/en/UI/Angular/Features.md @@ -1,3 +1,33 @@ -# Angular UI: Features +# Features -> This document explains how to get feature values in an Angular application. See the [Features document](../../Features.md) to learn the feature system. \ No newline at end of file +You can get the value of a feature on the client-side using the [config state service](./Config-State.md) if it is allowed by the feature definition on the server-side. + +> This document explains how to get feature values in an Angular application. See the [Features document](../../Features.md) to learn the feature system. + +## Before Use + +To use the `ConfigStateService`, you must inject it in your class as a dependency. You do not have to provide the service explicitly, because it is already **provided in root**. + +```js +import { ConfigStateService } from '@abp/ng.core'; + +@Component({ + /* class metadata here */ +}) +class DemoComponent { + constructor(private config: ConfigStateService) {} +} +``` + +## How to Get a Specific Feature + +You can use the `getFeature` method of `ConfigStateService` to get a specific feature from the configuration state. Here is an example: + +```js +// this.config is instance of ConfigStateService + +const defaultLang = this.config.getFeature("Identity.TwoFactor"); +// 'Optional' +``` + +You can then check the value of the feature to perform your logic. Please note that **feature keys are case-sensitive**. diff --git a/docs/en/UI/Angular/Form-Validation.md b/docs/en/UI/Angular/Form-Validation.md new file mode 100644 index 0000000000..38e7969eea --- /dev/null +++ b/docs/en/UI/Angular/Form-Validation.md @@ -0,0 +1,140 @@ +# Form Validation + +Reactive forms in ABP Angular UI are validated by [ngx-validate](https://www.npmjs.com/package/@ngx-validate/core) and helper texts are shown automatically based on validation rules and error blueprints. You do not have to add any elements or components to your templates. The library handles that for you. Here is how the experience is: + +The ngx-validate library validates an Angular reactive form and an error text appears under each wrong input based on the validation rule and the error blueprint. + +## How to Add New Error Messages + +You can add a new error message by providing the `VALIDATION_BLUEPRINTS` injection token from your root module. + +```js +import { VALIDATION_BLUEPRINTS } from "@ngx-validate/core"; + +@NgModule({ + // rest of the module metadata + + providers: [ + // other providers + { + provide: VALIDATION_BLUEPRINTS, + useValue: { + uniqueUsername: "::AlreadyExists[{%{{{ username }}}%}]", + }, + }, + ], +}) +export class AppModule {} +``` + +When a [validator](https://angular.io/guide/form-validation#defining-custom-validators) or an [async validator](https://angular.io/guide/form-validation#creating-asynchronous-validators) returns an error with the key given to the error blueprints (`uniqueUsername` here), the validation library will be able to display an error message after localizing according to the given key and interpolation params. The result will look like this: + +An already taken username is entered while creating new user and a custom error message appears under the input after validation. + +In this example; + +- Localization key is `::AlreadyExists`. +- The interpolation param is `username`. +- Localization resource is defined as `"AlreadyExists": "Sorry, “{0}” already exists."`. +- And the validator should return `{ uniqueUsername: { username: "admin" } }` as the error object. + +## How to Change Existing Error Messages + +You can overwrite an existing error message by providing `VALIDATION_BLUEPRINTS` injection token from your root module. Let's imagine you have a custom localization resource for required inputs. + +```json +"RequiredInput": "Oops! We need this input." +``` + +To use this instead of the built-in required input message, all you need to do is the following. + +```js +import { VALIDATION_BLUEPRINTS } from "@ngx-validate/core"; + +@NgModule({ + // rest of the module metadata + + providers: [ + // other providers + { + provide: VALIDATION_BLUEPRINTS, + useValue: { + required: "::RequiredInput", + }, + }, + ], +}) +export class AppModule {} +``` + +The error message will look like this: + +A required field is cleared and the custom error message appears under the input. + +## How to Disable Validation on a Form + +If you want to validate a form manually, you can always disable automatic validation on it. All you need to do is place `skipValidation` on the form element. + +```html +
+ +
+``` + +## How to Disable Validation on a Specific Field + +Validation works on any element or component with a `formControl` or `formControlName` directive. You can disable automatic validation on a specific field by placing `skipValidation` on the input element or component. + +```html + +``` + +## How to Use a Custom Error Component + +First, build a custom error component. Extending the existing `ValidationErrorComponent` would make it easier. + +```js +import { ValidationErrorComponent } from "@abp/ng.theme.basic"; +import { ChangeDetectionStrategy, Component } from "@angular/core"; + +@Component({ + selector: "app-validation-error", + template: ` +
+ {%{{{ error.message | abpLocalization: error.interpoliteParams }}}%} +
+ `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ErrorComponent extends ValidationErrorComponent {} +``` + +Then, declare and provide it in your root module. + +```js +import { VALIDATION_ERROR_TEMPLATE } from "@ngx-validate/core"; + +@NgModule({ + // rest of the module metadata + + declarations: [ + // other declarables + ErrorComponent, + ], + providers: [ + // other providers + { + provide: VALIDATION_ERROR_TEMPLATE, + useValue: ErrorComponent, + }, + ], +}) +export class AppModule {} +``` + +The error message will be bold and italic now: + +A required field is cleared and a bold and italic error message appears. diff --git a/docs/en/UI/Angular/HTTP-Requests.md b/docs/en/UI/Angular/HTTP-Requests.md index 2ac5aa1b49..ab1ac04097 100644 --- a/docs/en/UI/Angular/HTTP-Requests.md +++ b/docs/en/UI/Angular/HTTP-Requests.md @@ -203,7 +203,3 @@ getSomeCustomHeaderValue() { You may find `Rest.Observe` enum [here](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/rest.ts#L10). - -## What's Next? - -* [Localization](./Localization.md) diff --git a/docs/en/UI/Angular/Lazy-Load-Service.md b/docs/en/UI/Angular/Lazy-Load-Service.md index 344b446107..0e1f7928c7 100644 --- a/docs/en/UI/Angular/Lazy-Load-Service.md +++ b/docs/en/UI/Angular/Lazy-Load-Service.md @@ -204,10 +204,3 @@ load(strategy: LoadingStrategy, retryTimes?: number, retryDelay?: number): Obser - `strategy` parameter is the primary focus here and is explained above. - `retryTimes` defines how many times the loading will be tried again before fail (_default: 2_). - `retryDelay` defines how much delay there will be between retries (_default: 1000_). - - - - -## What's Next? - -- [Projecting Angular Content](./Content-Projection-Service.md) diff --git a/docs/en/UI/Angular/List-Service.md b/docs/en/UI/Angular/List-Service.md index d534558363..7cc31a46fd 100644 --- a/docs/en/UI/Angular/List-Service.md +++ b/docs/en/UI/Angular/List-Service.md @@ -177,8 +177,3 @@ As of v3.0, with ngx-datatable, the `page` property has to be set as `0` for ini ``` **Important Note:** The `abp-table` is not removed, but is deprecated and will be removed in the future. Please consider switching to ngx-datatable. - - -## What's Next? - -- [Easy *ngFor trackBy](./Track-By-Service.md) diff --git a/docs/en/UI/Angular/Localization.md b/docs/en/UI/Angular/Localization.md index eec4db0cb4..6c7e6084a6 100644 --- a/docs/en/UI/Angular/Localization.md +++ b/docs/en/UI/Angular/Localization.md @@ -100,36 +100,6 @@ this.localizationService.get('Resource::Key'); this.localizationService.get({ key: 'Resource::Key', defaultValue: 'Default Value' }); ``` -### Using the Config State - -In order to you `getLocalization` method you should import ConfigState. - -```js -import { ConfigState } from '@abp/ng.core'; -``` - -Then you can use it as followed: - -```js -this.store.selectSnapshot(ConfigState.getLocalization('ResourceName::Key')); -``` - -`getLocalization` method can be used with both `localization key` and [`LocalizationWithDefault`](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L34) interface. - -```js -this.store.selectSnapshot( - ConfigState.getLocalization( - { - key: 'AbpIdentity::UserDeletionConfirmation', - defaultValue: 'Default Value', - }, - 'John', - ), -); -``` - -Localization resources are stored in the `localization` property of `ConfigState`. - ## RTL Support As of v2.9 ABP has RTL support. If you are generating a new project with v2.9 and above, everything is set, you do not need to do any changes. If you are migrating your project from an earlier version, please follow the 2 steps below: @@ -193,37 +163,129 @@ import { Component } from '@angular/core'; export class AppComponent {} ``` -## Mapping of Culture Name to Angular Locale File Name +## Registering a New Locale + +Since ABP has more than one language, Angular locale files loads lazily using [Webpack's import function](https://webpack.js.org/api/module-methods/#import-1) to avoid increasing the bundle size and register to Angular core using the [`registerLocaleData`](https://angular.io/api/common/registerLocaleData) function. The chunks to be included in the bundle are specified by the [Webpack's magic comments](https://webpack.js.org/api/module-methods/#magic-comments) as hard-coded. Therefore a `registerLocale` function that returns Webpack `import` function must be passed to `CoreModule`. + +### registerLocaleFn + +`registerLocale` function that exported from `@abp/ng.core/locale` package is a higher order function that accepts `cultureNameLocaleFileMap` object and `errorHandlerFn` function as params and returns Webpack `import` function. A `registerLocale` function must be passed to the `forRoot` of the `CoreModule` as shown below: + +```js +// app.module.ts + +import { registerLocale } from '@abp/ng.core/locale'; +// if you have commercial license and the language management module, add the below import +// import { registerLocale } from '@volo/abp.ng.language-management/locale'; + + +@NgModule({ + imports: [ + // ... + CoreModule.forRoot({ + // ...other options, + registerLocaleFn: registerLocale( + // you can pass the cultureNameLocaleFileMap and errorHandlerFn as optionally + { + cultureNameLocaleFileMap: { 'pt-BR': 'pt' }, + errorHandlerFn: ({ resolve, reject, locale, error }) => { + // the error can be handled here + }, + }, + ) + }), + //... + ] +``` + + +### Mapping of Culture Name to Angular Locale File Name Some of the culture names defined in .NET do not match Angular locales. In such cases, the Angular app throws an error like below at runtime: ![locale-error](./images/locale-error.png) -If you see an error like this, you should pass the `cultureNameLocaleFileMap` property like below to CoreModule's forRoot static method. +If you see an error like this, you should pass the `cultureNameLocaleFileMap` property like below to the `registerLocale` function. ```js // app.module.ts +import { registerLocale } from '@abp/ng.core/locale'; +// if you have commercial license and the language management module, add the below import +// import { registerLocale } from '@volo/abp.ng.language-management/locale'; + + @NgModule({ imports: [ - // other imports - CoreModule.forRoot({ - // other options - cultureNameLocaleFileMap: { - "DotnetCultureName": "AngularLocaleFileName", - "pt-BR": "pt" // example - } - }) + // ... + CoreModule.forRoot({ + // ...other options, + registerLocaleFn: registerLocale( + { + cultureNameLocaleFileMap: { + "DotnetCultureName": "AngularLocaleFileName", + "pt-BR": "pt" // example + }, + }, + ) + }), //... ``` See [all locale files in Angular](https://github.com/angular/angular/tree/master/packages/common/locales). +### Adding a New Culture -## See Also +Add the below code to the `app.module.ts` by replacing `your-locale` placeholder with a correct locale name. -* [Localization in ASP.NET Core](../../Localization.md) +```js +//app.module.ts + +import { storeLocaleData } from '@abp/ng.core/locale'; +import( +/* webpackChunkName: "_locale-your-locale-js"*/ +/* webpackMode: "eager" */ +'@angular/common/locales/your-locale.js' +).then(m => storeLocaleData(m.default, 'your-locale')); +``` -## What's Next? +...or a custom `registerLocale` function can be passed to the `CoreModule`: + +```js +// register-locale.ts + +import { differentLocales } from '@abp/ng.core'; +export function registerLocale(locale: string) { + return import( + /* webpackChunkName: "_locale-[request]"*/ + /* webpackInclude: /[/\\](en|fr).js/ */ + /* webpackExclude: /[/\\]global|extra/ */ + `@angular/common/locales/${differentLocales[locale] || locale}.js` + ) +} + +// app.module.ts -* [Permission Management](./Permission-Management.md) +import { registerLocale } from './register-locale'; + +@NgModule({ + imports: [ + // ... + CoreModule.forRoot({ + // ...other options, + registerLocaleFn: registerLocale + }), + //... + ] +``` + +After this custom `registerLocale` function, since the en and fr added to the `webpackInclude`, only en and fr locale files will be created as chunks: + +![locale chunks](https://user-images.githubusercontent.com/34455572/98203212-acaa2100-1f44-11eb-85af-4eb66d296326.png) + +Which locale files you add to `webpackInclude` magic comment, they will be included in the bundle + + +## See Also + +* [Localization in ASP.NET Core](../../Localization.md) diff --git a/docs/en/UI/Angular/Migration-Guide-v3.md b/docs/en/UI/Angular/Migration-Guide-v3.md index 6a7b86efcb..f13b0c966f 100644 --- a/docs/en/UI/Angular/Migration-Guide-v3.md +++ b/docs/en/UI/Angular/Migration-Guide-v3.md @@ -470,8 +470,3 @@ Some interfaces have long been marked as deprecated and now they are removed. - Please check if you are still using [anything listed in this issue](https://github.com/abpframework/abp/issues/4281) - -## What's Next? - -* [Quick Start](./Quick-Start.md) - diff --git a/docs/en/UI/Angular/Modifying-the-Menu.md b/docs/en/UI/Angular/Modifying-the-Menu.md index a3c356891e..b0a3b760fa 100644 --- a/docs/en/UI/Angular/Modifying-the-Menu.md +++ b/docs/en/UI/Angular/Modifying-the-Menu.md @@ -271,8 +271,3 @@ export class AppComponent { * Patched the languages dropdown element with new `requiredPolicy` and new `order`. * Removed the current user dropdown element. - - -## What's Next - -* [Component Replacement](./Component-Replacement.md) diff --git a/docs/en/UI/Angular/Multi-Tenancy.md b/docs/en/UI/Angular/Multi-Tenancy.md index c3e54c5f83..e7e284bb0d 100644 --- a/docs/en/UI/Angular/Multi-Tenancy.md +++ b/docs/en/UI/Angular/Multi-Tenancy.md @@ -126,7 +126,3 @@ The app sends the `__tenant` header that contains the current tenant id on each ## See Also - [Multi Tenancy in ABP](../../Multi-Tenancy.md) - -## What's Next? - -- [Managing RxJS Subscriptions](./Subscription-Service.md) diff --git a/docs/en/UI/Angular/PWA-Configuration.md b/docs/en/UI/Angular/PWA-Configuration.md index a6aee244ba..918aa4970d 100644 --- a/docs/en/UI/Angular/PWA-Configuration.md +++ b/docs/en/UI/Angular/PWA-Configuration.md @@ -340,7 +340,3 @@ In case you want to cache other static files, please refer to the [service worke ### 3.2 Set Data Groups This part is unique to your project. We recommend being very careful about which endpoints to cache. Please refer to [service worker configuration document](https://angular.io/guide/service-worker-config#datagroups) on Angular.io for details. - -## What's Next? - -- [Config State](./Config-State.md) diff --git a/docs/en/UI/Angular/Permission-Management.md b/docs/en/UI/Angular/Permission-Management.md index b9c4649c03..b8125bb2a3 100644 --- a/docs/en/UI/Angular/Permission-Management.md +++ b/docs/en/UI/Angular/Permission-Management.md @@ -2,22 +2,46 @@ A permission is a simple policy that is granted or prohibited for a particular user, role or client. You can read more about [authorization in ABP](../../Authorization.md) document. -You can get permission of authenticated user using `getGrantedPolicy` selector of `ConfigState`. +You can get permission of authenticated user using `getGrantedPolicy` or `getGrantedPolicy$` method of `PermissionService`. + +> ConfigState's getGrantedPolicy selector and ConfigStateService's getGrantedPolicy method deprecated. Use permission service's `getGrantedPolicy$` or `getGrantedPolicy`methods instead You can get permission as boolean value: ```js -import { ConfigStateService } from '@abp/ng.core'; +import { PermissionService } from '@abp/ng.core'; export class YourComponent { - constructor(private config: ConfigStateService) {} + constructor(private permissionService: PermissionService) {} ngOnInit(): void { - const canCreate = this.config.getGrantedPolicy('AbpIdentity.Roles.Create'); + const canCreate = this.permissionService.getGrantedPolicy('AbpIdentity.Roles.Create'); } } ``` +You may also **combine policy keys** to fine tune your selection: + +```js +// this.permissionService is instance of PermissionService + +const hasIdentityAndAccountPermission = this.permissionService.getGrantedPolicy( + "Abp.Identity && Abp.Account" +); + +const hasIdentityOrAccountPermission = this.permissionService.getGrantedPolicy( + "Abp.Identity || Abp.Account" +); +``` + +Please consider the following **rules** when creating your permission selectors: + +- Maximum 2 keys can be combined. +- `&&` operator looks for both keys. +- `||` operator looks for either key. +- Empty string `''` as key will return `true` +- Using an operator without a second key will return `false` + ## Permission Directive You can use the `PermissionDirective` to manage visibility of a DOM Element accordingly to user's permission. @@ -30,8 +54,6 @@ You can use the `PermissionDirective` to manage visibility of a DOM Element acco As shown above you can remove elements from DOM with `abpPermission` structural directive. -The directive can also be used as an attribute directive but we recommend to you to use it as a structural directive. - ## Permission Guard You can use `PermissionGuard` if you want to control authenticated user's permission to access to the route during navigation. @@ -55,8 +77,4 @@ const routes: Routes = [ ]; ``` -Granted Policies are stored in the `auth` property of `ConfigState`. - -## What's Next? - -* [Multi Tenancy](./Multi-Tenancy.md) \ No newline at end of file +Granted Policies are stored in the `auth` property of `ConfigState`. \ No newline at end of file diff --git a/docs/en/UI/Angular/Quick-Start.md b/docs/en/UI/Angular/Quick-Start.md index a58671156c..c17f069c5f 100644 --- a/docs/en/UI/Angular/Quick-Start.md +++ b/docs/en/UI/Angular/Quick-Start.md @@ -204,9 +204,3 @@ In addition, you can [deploy your application to certain targets using the Angul --- 1 _The compiled output will be placed under `/dist` in a folder by the project name._ [↩](#a-dist-folder-name) - ---- - -## What's Next? - -- [Environment Variables](./Environment.md) diff --git a/docs/en/UI/Angular/Service-Proxies.md b/docs/en/UI/Angular/Service-Proxies.md index 92c4b01871..8f6b1c4d60 100644 --- a/docs/en/UI/Angular/Service-Proxies.md +++ b/docs/en/UI/Angular/Service-Proxies.md @@ -137,7 +137,3 @@ export class BookComponent implements OnInit { ``` > Please [see this article](https://github.com/abpframework/abp/blob/dev/docs/en/Blog-Posts/2020-09-07%20Angular-Service-Proxies/POST.md) to learn more about service proxies. - -## What's Next? - -- [PWA Configuration](./PWA-Configuration.md) diff --git a/docs/en/UI/Angular/Settings.md b/docs/en/UI/Angular/Settings.md new file mode 100644 index 0000000000..0dd29025e5 --- /dev/null +++ b/docs/en/UI/Angular/Settings.md @@ -0,0 +1,55 @@ +# Settings + +You can get settings on the client-side using the [config state service](./Config-State.md) if they are allowed by their setting definition on the server-side. + +> This document only explains how settings work in the Angular UI projects. See the [settings document](../../../Settings.md) to understand the ABP setting system. + +## Before Use + +To use the `ConfigStateService`, you must inject it in your class as a dependency. You do not have to provide the service explicitly, because it is already **provided in root**. + +```js +import { ConfigStateService } from '@abp/ng.core'; + +@Component({ + /* class metadata here */ +}) +class DemoComponent { + constructor(private config: ConfigStateService) {} +} +``` + +## How to Get a Specific Setting + +You can use the `getSetting` method of `ConfigStateService` to get a specific setting from the configuration state. Here is an example: + +```js +// this.config is instance of ConfigStateService + +const defaultLang = this.config.getSetting("Abp.Localization.DefaultLanguage"); +// 'en' +``` + +### How to Get All Settings From the Store + +You can use the `getSettings` method of `ConfigStateService` to obtain all settings as an object where the object properties are setting names and property values are setting values. + +```js +// this.config is instance of ConfigStateService + +const settings = this.config.getSettings(); +// all settings as a key value pair +``` + +Additionally, the method lets you search settings by **passing a keyword** to it. + +```js +const localizationSettings = this.config.getSettings("Localization"); +/* +{ + 'Abp.Localization.DefaultLanguage': 'en' +} +*/ +``` + +Beware though, **settings search is case-sensitive**. diff --git a/docs/en/UI/Angular/Subscription-Service.md b/docs/en/UI/Angular/Subscription-Service.md index dee77cbf1e..e080f8f3fa 100644 --- a/docs/en/UI/Angular/Subscription-Service.md +++ b/docs/en/UI/Angular/Subscription-Service.md @@ -197,7 +197,3 @@ class DemoComponent implements OnInit { } } ``` - -## What's Next? - -- [Working with Lists](./List-Service.md) diff --git a/docs/en/UI/Angular/Testing.md b/docs/en/UI/Angular/Testing.md new file mode 100644 index 0000000000..f24ae62982 --- /dev/null +++ b/docs/en/UI/Angular/Testing.md @@ -0,0 +1,3 @@ +# Angular UI: Testing + +TODO \ No newline at end of file diff --git a/docs/en/UI/Angular/Toaster-Service.md b/docs/en/UI/Angular/Toaster-Service.md index f6d5c71e99..059fd720a8 100644 --- a/docs/en/UI/Angular/Toaster-Service.md +++ b/docs/en/UI/Angular/Toaster-Service.md @@ -85,7 +85,103 @@ The all open toasts can be removed manually via the `clear` method: ```js this.toaster.clear(); ``` +## Replacing ToasterService with 3rd party toaster libraries +If you want the ABP Framework to utilize 3rd party libraries for the toasters instead of the built-in one, you can provide a service that implements `Toaster.Service` interface, and provide it as follows (ngx-toastr library used in example): + +> You can use *LocalizationService* for toaster messages translations. +```js +// your-custom-toaster.service.ts +import { Injectable } from '@angular/core'; +import { Config, LocalizationService } from '@abp/ng.core'; +import { Toaster } from '@abp/ng.theme.shared'; +import { ToastrService } from 'ngx-toastr'; + +@Injectable() +export class CustomToasterService implements Toaster.Service { + constructor(private toastr: ToastrService, private localizationService: LocalizationService) {} + + error( + message: Config.LocalizationParam, + title?: Config.LocalizationParam, + options?: Partial, + ) { + return this.show(message, title, 'error', options); + } + + clear(): void { + this.toastr.clear(); + } + + info( + message: Config.LocalizationParam, + title: Config.LocalizationParam | undefined, + options: Partial | undefined, + ): Toaster.ToasterId { + return this.show(message, title, 'info', options); + } + + remove(id: number): void { + this.toastr.remove(id); + } + + show( + message: Config.LocalizationParam, + title: Config.LocalizationParam, + severity: Toaster.Severity, + options: Partial, + ): Toaster.ToasterId { + const translatedMessage = this.localizationService.instant(message); + const translatedTitle = this.localizationService.instant(title); + const toasterOptions = { + positionClass: 'toast-bottom-right', + tapToDismiss: options.tapToDismiss, + ...(options.sticky && { + extendedTimeOut: 0, + timeOut: 0, + }), + }; + const activeToast = this.toastr.show( + translatedMessage, + translatedTitle, + toasterOptions, + `toast-${severity}`, + ); + return activeToast.toastId; + } + + success( + message: Config.LocalizationParam, + title: Config.LocalizationParam | undefined, + options: Partial | undefined, + ): Toaster.ToasterId { + return this.show(message, title, 'success', options); + } + + warn( + message: Config.LocalizationParam, + title: Config.LocalizationParam | undefined, + options: Partial | undefined, + ): Toaster.ToasterId { + return this.show(message, title, 'warning', options); + } +} +``` +```js +// app.module.ts + +import { ToasterService } from '@abp/ng.theme.shared'; + +@NgModule({ + providers: [ + // ... + { + provide: ToasterService, + useClass: CustomToasterService, + }, + ] +}) +``` ## API ### success @@ -153,7 +249,3 @@ Removes all open toasts. ## See Also - [Confirmation Popup](./Confirmation-Service.md) - -## What's Next? - -- [Modifying the Menu](./Modifying-the-Menu.md) diff --git a/docs/en/UI/Angular/Track-By-Service.md b/docs/en/UI/Angular/Track-By-Service.md index 7883be4754..a7df7b80b6 100644 --- a/docs/en/UI/Angular/Track-By-Service.md +++ b/docs/en/UI/Angular/Track-By-Service.md @@ -111,9 +111,3 @@ class DemoComponent { trackByTenantAccountId = trackByDeep('tenant', 'account', 'id'); } ``` - - - -## What's Next? - -- [Inserting Scripts & Styles to DOM](./Dom-Insertion-Service.md) diff --git a/docs/en/UI/Angular/images/form-validation---custom-error-template.gif b/docs/en/UI/Angular/images/form-validation---custom-error-template.gif new file mode 100644 index 0000000000..6d9f492ce4 Binary files /dev/null and b/docs/en/UI/Angular/images/form-validation---custom-error-template.gif differ diff --git a/docs/en/UI/Angular/images/form-validation---error-display-user-experience.gif b/docs/en/UI/Angular/images/form-validation---error-display-user-experience.gif new file mode 100644 index 0000000000..9070a0f730 Binary files /dev/null and b/docs/en/UI/Angular/images/form-validation---error-display-user-experience.gif differ diff --git a/docs/en/UI/Angular/images/form-validation---new-error-message.gif b/docs/en/UI/Angular/images/form-validation---new-error-message.gif new file mode 100644 index 0000000000..ae61215f61 Binary files /dev/null and b/docs/en/UI/Angular/images/form-validation---new-error-message.gif differ diff --git a/docs/en/UI/Angular/images/form-validation---overwrite-error-message.gif b/docs/en/UI/Angular/images/form-validation---overwrite-error-message.gif new file mode 100644 index 0000000000..b6af5a68b7 Binary files /dev/null and b/docs/en/UI/Angular/images/form-validation---overwrite-error-message.gif differ diff --git a/docs/en/UI/AspNetCore/Basic-Theme.md b/docs/en/UI/AspNetCore/Basic-Theme.md new file mode 100644 index 0000000000..67977ffd4e --- /dev/null +++ b/docs/en/UI/AspNetCore/Basic-Theme.md @@ -0,0 +1,90 @@ +# ASP.NET Core MVC / Razor Pages: The Basic Theme + +The Basic Theme is a theme implementation for the ASP.NET Core MVC / Razor Pages UI. It is a minimalist theme that doesn't add any styling on top of the plain [Bootstrap](https://getbootstrap.com/). You can take the Basic Theme as the **base theme** and build your own theme or styling on top of it. See the *Customization* section. + +The Basic Theme has RTL (Right-to-Left language) support. + +> If you are looking for a professional, enterprise ready theme, you can check the [Lepton Theme](https://commercial.abp.io/themes), which is a part of the [ABP Commercial](https://commercial.abp.io/). + +> See the [Theming document](Theming.md) to learn about themes. + +## Installation + +**This theme is already installed** when you create a new solution using the [startup templates](../../Startup-Templates/Index.md). If you need to manually install it, follow the steps below: + +* Install the [Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic) NuGet package to your web project. +* Add `AbpAspNetCoreMvcUiBasicThemeModule` into the `[DependsOn(...)]` attribute for your [module class](../../Module-Development-Basics.md) in the web project. +* Install the [@abp/aspnetcore.mvc.ui.theme.basic](https://www.npmjs.com/package/@abp/aspnetcore.mvc.ui.theme.basic) NPM package to your web project (e.g. `npm install @abp/aspnetcore.mvc.ui.theme.basic` or `yarn add @abp/aspnetcore.mvc.ui.theme.basic`). +* Run `gulp` command in a command line terminal in the web project's folder. + +## Layouts + +The Basic Theme implements the standard layouts. All the layouts implement the following parts; + +* Global [Bundles](Bundling-Minification.md) +* [Page Alerts](Page-Alerts.md) +* [Layout Hooks](Layout-Hooks.md) +* [Widget](Widgets.md) Resources + +### The Application Layout + +![basic-theme-application-layout](../../images/basic-theme-application-layout.png) + +Application Layout implements the following parts, in addition to the common parts mentioned above; + +* Branding +* Main [Menu](Navigation-Menu.md) +* Main [Toolbar](Toolbars.md) with Language Selection & User Menu + +### The Account Layout + +![basic-theme-account-layout](../../images/basic-theme-account-layout.png) + +Application Layout implements the following parts, in addition to the common parts mentioned above; + +* Branding +* Main [Menu](Navigation-Menu.md) +* Main [Toolbar](Toolbars.md) with Language Selection & User Menu +* Tenant Switch Area + +### Empty Layout + +Empty layout is empty, as its name stands for. However, it implements the common parts mentioned above. + +## Customization + +You have two options two customize this theme: + +### Overriding Styles/Components + +In this approach, you continue to use the the theme as NuGet and NPM packages and customize the parts you need to. There are several ways to customize it; + +#### Override the Styles + +1. Create a CSS file in the `wwwroot` folder of your project: + +![example-global-styles](../../images/example-global-styles.png) + +2. Add the style file to the global bundle, in the `ConfigureServices` method of your [module](../../Module-Development-Basics.md): + +````csharp +Configure(options => +{ + options.StyleBundles.Configure(BasicThemeBundles.Styles.Global, bundle => + { + bundle.AddFiles("/styles/global-styles.css"); + }); +}); +```` + +#### Override the Components + +See the [User Interface Customization Guide](Customization-User-Interface.md) to learn how you can replace components, customize and extend the user interface. + +### Copy & Customize + +You can download the [source code](https://github.com/abpframework/abp/tree/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic) of the Basic Theme, copy the project content into your solution, re-arrange the package/module dependencies (see the Installation section above to understand how it was installed to the project) and freely customize the theme based on your application requirements. + +## See Also + +* [Theming](Theming.md) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Branding.md b/docs/en/UI/AspNetCore/Branding.md new file mode 100644 index 0000000000..e4a9ee0f3b --- /dev/null +++ b/docs/en/UI/AspNetCore/Branding.md @@ -0,0 +1,45 @@ +# ASP.NET Core MVC / Razor Pages: Branding + +## IBrandingProvider + +`IBrandingProvider` is a simple interface that is used to show the application name and logo on the layout. + +The screenshot below shows *MyProject* as the application name: + +![branding-nobrand](../../images/branding-nobrand.png) + +You can implement the `IBrandingProvider` interface or inherit from the `DefaultBrandingProvider` to set the application name: + +````csharp +using Volo.Abp.Ui.Branding; +using Volo.Abp.DependencyInjection; + +namespace MyProject.Web +{ + [Dependency(ReplaceServices = true)] + public class MyProjectBrandingProvider : DefaultBrandingProvider + { + public override string AppName => "Book Store"; + } +} +```` + +The result will be like shown below: + +![branding-appname](../../images/branding-appname.png) + +`IBrandingProvider` has the following properties: + +* `AppName`: The application name. +* `LogoUrl`: A URL to show the application logo. +* `LogoReverseUrl`: A URL to show the application logo on a reverse color theme (dark, for example). + +> **Tip**: `IBrandingProvider` is used in every page refresh. For a multi-tenant application, you can return a tenant specific application name to customize it per tenant. + +## Overriding the Branding Area + +The [Basic Theme](Basic-Theme.md) doesn't implement the logos. However, you can see the [UI Customization Guide](Customization-User-Interface.md) to learn how you can replace the branding area with a custom view component. + +An example screenshot with an image is used in the branding area: + +![bookstore-added-logo](../../images/bookstore-added-logo.png) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Client-Side-Package-Management.md b/docs/en/UI/AspNetCore/Client-Side-Package-Management.md index 63c5cec225..645200a363 100644 --- a/docs/en/UI/AspNetCore/Client-Side-Package-Management.md +++ b/docs/en/UI/AspNetCore/Client-Side-Package-Management.md @@ -76,7 +76,8 @@ module.exports = { "@libs": "./wwwroot/libs" }, clean: [ - "@libs" + "@libs", + "!@libs/**/foo.txt" ], mappings: { @@ -85,7 +86,7 @@ module.exports = { ```` * **aliases** section defines standard aliases (placeholders) that can be used in the mapping paths. **@node_modules** and **@libs** are required (by the standard packages), you can define your own aliases to reduce duplication. -* **clean** section is a list of folders to clean before copying the files. +* **clean** section is a list of folders to clean before copying the files. Glob matching and negation is enabled, so you can fine-tune what to delete and keep. The example above will clean everything inside `./wwwroot/libs`, but keep any `foo.txt` files. * **mappings** section is a list of mappings of files/folders to copy. This example does not copy any resource itself, but depends on a standard package. An example mapping configuration is shown below: @@ -94,7 +95,8 @@ An example mapping configuration is shown below: mappings: { "@node_modules/bootstrap/dist/css/bootstrap.css": "@libs/bootstrap/css/", "@node_modules/bootstrap/dist/js/bootstrap.bundle.js": "@libs/bootstrap/js/", - "@node_modules/bootstrap-datepicker/dist/locales/*.*": "@libs/bootstrap-datepicker/locales/" + "@node_modules/bootstrap-datepicker/dist/locales/*.*": "@libs/bootstrap-datepicker/locales/", + "@node_modules/bootstrap-v4-rtl/dist/**/*": "@libs/bootstrap-v4-rtl/dist/" } ```` diff --git a/docs/en/UI/AspNetCore/Customization-User-Interface.md b/docs/en/UI/AspNetCore/Customization-User-Interface.md index f1f0174c89..111a43ddcb 100644 --- a/docs/en/UI/AspNetCore/Customization-User-Interface.md +++ b/docs/en/UI/AspNetCore/Customization-User-Interface.md @@ -1,6 +1,6 @@ # ASP.NET Core (MVC / Razor Pages) User Interface Customization Guide -This document explains how to override the user interface of a depended [application module](../../Modules/Index.md) for ASP.NET Core MVC / Razor Page applications. +This document explains how to override the user interface of a depended [application module](../../Modules/Index.md) or [theme](Theming.md) for ASP.NET Core MVC / Razor Page applications. ## Overriding a Page @@ -28,15 +28,15 @@ namespace Acme.BookStore.Web.Pages.Identity.Users public class MyEditModalModel : EditModalModel { public MyEditModalModel( - IIdentityUserAppService identityUserAppService, + IIdentityUserAppService identityUserAppService, IIdentityRoleAppService identityRoleAppService ) : base( - identityUserAppService, + identityUserAppService, identityRoleAppService) { } - public override async Task OnPostAsync() + public async override Task OnPostAsync() { //TODO: Additional logic await base.OnPostAsync(); @@ -84,10 +84,10 @@ Create a page model class deriving from the ` LoginModel ` (defined in the ` Vol public class MyLoginModel : LoginModel { public MyLoginModel( - IAuthenticationSchemeProvider schemeProvider, + IAuthenticationSchemeProvider schemeProvider, IOptions accountOptions ) : base( - schemeProvider, + schemeProvider, accountOptions) { @@ -128,11 +128,11 @@ The ABP Framework, pre-built themes and modules define some **re-usable view com ### Example -The screenshot below was taken from the **basic theme** comes with the application startup template. +The screenshot below was taken from the [Basic Theme](Basic-Theme.md) comes with the application startup template. ![bookstore-brand-area-highlighted](../../images/bookstore-brand-area-highlighted.png) -[The basic theme](../../Themes/Basic.md) defines some view components for the layout. For example, the highlighted area with the red rectangle above is called **Brand component**. You probably want to customize this component by adding your **own application logo**. Let's see how to do it. +The [Basic Theme](Basic-Theme.md) defines some view components for the layout. For example, the highlighted area with the red rectangle above is called **Brand component**. You probably want to customize this component by adding your **own application logo**. Let's see how to do it. First, create your logo and place under a folder in your web application. We used `wwwroot/logos/bookstore-logo.png` path. Then copy the Brand component's view ([from here](https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Components/Brand/Default.cshtml)) from the basic theme files under the `Themes/Basic/Components/Brand` folder. The result should be similar the picture below: @@ -376,7 +376,7 @@ Assume that you need to add the Google Analytics script to the layout (that will ![bookstore-google-analytics-view-component](../../images/bookstore-google-analytics-view-component.png) -**NotificationViewComponent.cs** +**GoogleAnalyticsViewComponent.cs** ````csharp public class GoogleAnalyticsViewComponent : AbpViewComponent @@ -437,11 +437,11 @@ See the layouts section below to learn more about the layout system. Layout system allows themes to define standard, named layouts and allows any page to select a proper layout for its purpose. There are three pre-defined layouts: -* "**Application**": The main (and the default) layout for an application. It typically contains header, menu (sidebar), footer, toolbar... etc. +* "**Application**": The main (and the default) layout for an application. It typically contains header, menu (sidebar), footer, toolbar... etc. * "**Account**": This layout is used by login, register and other similar pages. It is used for the pages under the `/Pages/Account` folder by default. * "**Empty**": Empty and minimal layout. -These names are defined in the `StandardLayouts` class as constants. You can definitely create your own layouts, but these are standard layout names and implemented by all the themes out of the box. +These names are defined in the `StandardLayouts` class as constants. You can definitely create your own layouts, but these are the standard layout names and implemented by all the themes out of the box. #### Layout Location diff --git a/docs/en/UI/AspNetCore/Data-Tables.md b/docs/en/UI/AspNetCore/Data-Tables.md new file mode 100644 index 0000000000..a9dbf1eecf --- /dev/null +++ b/docs/en/UI/AspNetCore/Data-Tables.md @@ -0,0 +1,263 @@ +# ASP.NET Core MVC / Razor Pages: Data Tables + +A Data Table (aka Data Grid) is a UI component to show tabular data to the users. There are a lot of Data table components/libraries and **you can use any one you like** with the ABP Framework. However, the startup templates come with the [DataTables.Net](https://datatables.net/) library as **pre-installed and configured**. ABP Framework provides adapters for this library and make it easy to use with the API endpoints. + +An example screenshot from the user management page that shows the user list in a data table: + +![datatables-example](../../images/datatables-example.png) + +## DataTables.Net Integration + +First of all, you can follow the official documentation to understand how the [DataTables.Net](https://datatables.net/) works. This section will focus on the ABP addons & integration points rather than fully covering the usage of this library. + +### A Quick Example + +You can follow the [web application development tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=MVC) for a complete example application that uses the DataTables.Net as the Data Table. This section shows a minimalist example. + +You do nothing to add DataTables.Net library to the page since it is already added to the global [bundle](Bundling-Minification.md) by default. + +First, add an `abp-table` as shown below, with an `id`: + +````html + +```` + +> `abp-table` is a [Tag Helper](Tag-Helpers/Index.md) defined by the ABP Framework, but a simple `` tag would also work. + +Then call the `DataTable` plugin on the table selector: + +````js +var dataTable = $('#BooksTable').DataTable( + abp.libs.datatables.normalizeConfiguration({ + serverSide: true, + paging: true, + order: [[1, "asc"]], + searching: false, + ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList), + columnDefs: [ + { + title: l('Actions'), + rowAction: { + items: + [ + { + text: l('Edit'), + action: function (data) { + ///... + } + } + ] + } + }, + { + title: l('Name'), + data: "name" + }, + { + title: l('PublishDate'), + data: "publishDate", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(); + } + }, + { + title: l('Price'), + data: "price" + } + ] + }) +); +```` + +The example code above uses some ABP integration features those will be explained in the next sections. + +### Configuration Normalization + +`abp.libs.datatables.normalizeConfiguration` function takes a DataTables configuration and normalizes to simplify it; + +* Sets `scrollX` option to `true`, if not set. +* Sets `target` index for the column definitions. +* Sets the `language` option to [localize](../../Localization.md) the table in the current language. + +#### Default Configuration + +`normalizeConfiguration` uses the default configuration. You can change the default configuration using the `abp.libs.datatables.defaultConfigurations` object. Example: + +````js +abp.libs.datatables.defaultConfigurations.scrollX = false; +```` + +Here, the all configuration options; + +* `scrollX`: `false` by default. +* `dom`: Default value is `<"dataTable_filters"f>rt<"row dataTable_footer"<"col-auto"l><"col-auto"i><"col"p>>`. +* `language`: A function that returns the localization text using the current language. + +### AJAX Adapter + +DataTables.Net has its own expected data format while getting results of an AJAX call to the server to get the table data. They are especially related how paging and sorting parameters are sent and received. ABP Framework also offers its own conventions for the client-server [AJAX](JavaScript-API/Ajax.md) communication. + +The `abp.libs.datatables.createAjax` method (used in the example above) adapts request and response data format and perfectly works with the [Dynamic JavaScript Client Proxy](Dynamic-JavaScript-Proxies.md) system. + +This works automatically, so most of the times you don't need to know how it works. See the [DTO document](../../Data-Transfer-Objects.md) if you want to learn more about `IPagedAndSortedResultRequest`, `IPagedResult` and other standard interfaces and base DTO classes those are used in client to server communication. + +### Row Actions + +`rowAction` is an option defined by the ABP Framework to the column definitions to show a drop down button to take actions for a row in the table. + +The example screenshot below shows the actions for each user in the user management table: + +![datatables-example](../../images/datatables-row-actions.png) + +`rowAction` is defined as a part of a column definition: + +````csharp +{ + title: l('Actions'), + rowAction: { + //TODO: CONFIGURATION + } +}, +```` + +**Example: Show *Edit* and *Delete* actions for a book row** + +````js +{ + title: l('Actions'), + rowAction: { + items: + [ + { + text: l('Edit'), + action: function (data) { + //TODO: Open a modal to edit the book + } + }, + { + text: l('Delete'), + confirmMessage: function (data) { + return "Are you sure to delete the book " + data.record.name; + }, + action: function (data) { + acme.bookStore.books.book + .delete(data.record.id) + .then(function() { + abp.notify.info("Successfully deleted!"); + data.table.ajax.reload(); + }); + } + } + ] + } +}, +```` + +#### Action Items + +`items` is an array of action definitions. An action definition can have the following options; + +* `text`: The text (a `string`) for this action to be shown in the actions drop down. +* `action`: A `function` that is executed when the user clicks to the action. The function takes a `data` argument that has the following fields; + * `data.record`: This is the data object related to the row. You can access the data fields like `data.record.id`, `data.record.name`... etc. + * `data.table`: The DataTables instance. +* `confirmMessage`: A `function` (see the example above) that returns a message (`string`) to show a dialog to get a confirmation from the user before executing the `action`. Example confirmation dialog: + +![datatables-row-actions-confirmation](../../images/datatables-row-actions-confirmation.png) + +You can use the [localization](JavaScript-API/Localization.md) system to show a localized message. + +* `visible`: A `bool` or a `function` that returns a `bool`. If the result is `false`, then the action is not shown in the actions dropdown. This is generally combined by the [authorization](JavaScript-API/Auth.md) system to hide the action if the user has no permission to take this action. Example: + +````js +visible: abp.auth.isGranted('BookStore.Books.Delete'); +```` + +If you define a `function`, then the `function` has two arguments: `record` (the data object of the related row) and the `table` (the DataTable instance). So, you can decide to show/hide the action dynamically, based on the row data and other conditions. + +* `iconClass`: Can be used to show a font-icon, like a [Font-Awesome](https://fontawesome.com/) icon (ex: `fas fa-trash-alt`), near to the action text. Example screenshot: + +![datatables-row-actions-confirmation](../../images/datatables-row-actions-icon.png) + +* `enabled`: A `function` that returns a `bool` to disable the action. The `function` takes a `data` object with two fields: `data.record` is the data object related to the row and `data.table` is the DataTables instance. +* `displayNameHtml`: Set this to `true` is the `text` value contains HTML tags. + +There are some rules with the action items; + +* If none of the action items is visible then the actions column is not rendered. + +### Data Format + +#### The Problem + +See the *Creation Time* column in the example below: + +````js +{ + title: l('CreationTime'), + data: "creationTime", + render: function (data) { + return luxon + .DateTime + .fromISO(data, { + locale: abp.localization.currentCulture.name + }).toLocaleString(luxon.DateTime.DATETIME_SHORT); + } +} +```` + +The `render` is a standard DataTables option to render the column content by a custom function. This example uses the [luxon](https://moment.github.io/luxon/) library (which is installed by default) to write a human readable value of the `creationTime` in the current user's language. Example output of the column: + +![datatables-custom-render-date](../../images/datatables-custom-render-date.png) + +If you don't define the render option, then the result will be ugly and not user friendly: + +![datatables-custom-render-date](../../images/datatables-default-render-date.png) + +However, rendering a `DateTime` is almost same and repeating the same rendering logic everywhere is against to the DRY (Don't Repeat Yourself!) principle. + +#### dataFormat Option + +`dataFormat` column option specifies the data format that is used to render the column data. The same output could be accomplished using the following column definition: + +````js +{ + title: l('CreationTime'), + data: "creationTime", + dataFormat: 'datetime' +} +```` + +`dataFormat: 'datetime'` specifies the data format for this column. There are a few pre-defined `dataFormat`s: + +* `boolean`: Shows a `check` icon for `true` and `times` icon for `false` value and useful to render `bool` values. +* `date`: Shows date part of a `DateTime` value, formatted based on the current culture. +* `datetime`: Shows date & time (excluding seconds) of a `DateTime` value, formatted based on the current culture. + +### Default Renderers + +`abp.libs.datatables.defaultRenderers` option allows you to define new data formats and set renderers for them. + +**Example: Render male / female icons based on the gender** + +````js +abp.libs.datatables.defaultRenderers['gender'] = function(value) { + if (value === 'f') { + return ''; + } else { + return ''; + } +}; +```` + +Assuming that the possible values for a column data is `f` and `m`, the `gender` data format shows female/male icons instead of `f` and `m` texts. You can now set `dataFormat: 'gender'` for a column definition that has the proper data values. + +> You can write the default renderers in a single JavaScript file and add it to the [Global Script Bundle](Bundling-Minification.md), so you can reuse them in all the pages. + +## Other Data Grids + +You can use any library you like. For example, [see this article](https://community.abp.io/articles/using-devextreme-components-with-the-abp-framework-zb8z7yqv) to learn how to use DevExtreme Data Grid in your applications. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Dynamic-JavaScript-Proxies.md b/docs/en/UI/AspNetCore/Dynamic-JavaScript-Proxies.md index 391a63a910..3464d4bc68 100644 --- a/docs/en/UI/AspNetCore/Dynamic-JavaScript-Proxies.md +++ b/docs/en/UI/AspNetCore/Dynamic-JavaScript-Proxies.md @@ -1,3 +1,91 @@ -# Dynamic JavaScript HTTP API Proxies +# Dynamic JavaScript API Client Proxies -TODO \ No newline at end of file +It is typical to consume your HTTP APIs from your JavaScript code. To do that, you normally deal with low level AJAX calls, like $.ajax, or better [abp.ajax](JavaScript-API/Ajax.md). ABP Framework provides **a better way** to call your HTTP APIs from your JavaScript code: Dynamic JavaScript API Client Proxies! + +## A Quick Example + +Assume that you have an application service defined as shown below: + +````csharp +using System; +using System.Threading.Tasks; +using Volo.Abp.Application.Dtos; +using Volo.Abp.Application.Services; + +namespace Acme.BookStore.Authors +{ + public interface IAuthorAppService : IApplicationService + { + Task GetAsync(Guid id); + + Task> GetListAsync(GetAuthorListDto input); + + Task CreateAsync(CreateAuthorDto input); + + Task UpdateAsync(Guid id, UpdateAuthorDto input); + + Task DeleteAsync(Guid id); + } +} +```` + +> You can follow the [web application development tutorial](../../Tutorials/Part-1.md) to learn how to create [application services](../../Application-Services.md), expose them as [HTTP APIs](../../API/Auto-API-Controllers.md) and consume from the JavaScript code as a complete example. + +You can call any of the methods just like calling a JavaScript function. The JavaScript function has the identical function **name**, **parameters** and the **return value** with the C# method. + +**Example: Get the authors list** + +````js +acme.bookStore.authors.author.getList({ + maxResultCount: 10 +}).then(function(result){ + console.log(result.items); +}); +```` + +**Example: Delete an author** + +```js +acme.bookStore.authors.author + .delete('7245a066-5457-4941-8aa7-3004778775f0') //Get id from somewhere! + .then(function() { + abp.notify.info('Successfully deleted!'); + }); +``` + +## AJAX Details + +Dynamic JavaScript client proxy functions use the [abp.ajax](JavaScript-API/Ajax.md) under the hood. So, you have the same benefits like **automatic error handling**. Also, you can fully control the AJAX call by providing the options. + +### The Return Value + +Every function returns a [Deferred object](https://api.jquery.com/category/deferred-object/). That means you can chain with `then` to get the result, `catch` to handle the error, `always` to perform an action once the operation completes (success or failed). + +### AJAX Options + +Every function gets an additional **last parameter** after your own parameters. The last parameter is called as `ajaxParams`. It is an object that overrides the AJAX options. + +**Example: Set `type` and `dataType` AJAX options** + +````js +acme.bookStore.authors.author + .delete('7245a066-5457-4941-8aa7-3004778775f0', { + type: 'POST', + dataType: 'xml' + }) + .then(function() { + abp.notify.info('Successfully deleted!'); + }); +```` + +See the [jQuery.ajax](https://api.jquery.com/jQuery.ajax/) documentation for all the available options. + +## Service Proxy Script Endpoint + +The magic is done by the `/Abp/ServiceProxyScript` endpoint defined by the ABP Framework and automatically added to the layout. You can visit this endpoint in your application to see the client proxy function definitions. This script file is automatically generated by the ABP Framework based on the server side method definitions and the related HTTP endpoint details. + +## See Also + +* [Web Application Development Tutorial](../../Tutorials/Part-1.md) +* [Auto API Controllers](../../API/Auto-API-Controllers.md) +* [Dynamic C# API Client Proxies](../../API/Dynamic-CSharp-API-Clients.md) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Forms-Validation.md b/docs/en/UI/AspNetCore/Forms-Validation.md index e62a6dc807..48d7937013 100644 --- a/docs/en/UI/AspNetCore/Forms-Validation.md +++ b/docs/en/UI/AspNetCore/Forms-Validation.md @@ -152,7 +152,7 @@ However, if you want to **render the form body yourself** (for example, you may Both of the Dynamic Form and the Form Tag Helpers **automatically validate** the input based on the data annotation attributes and shows validation error messages on the user interface. Error messages are **automatically localized** based on the current culture. -**Example: User leaves empty a requires string property** +**Example: User leaves empty a required string property** ![abp-form-input-validation-error](../../images/abp-form-input-validation-error.png) @@ -203,4 +203,4 @@ In this case, you can add an entry to the localization file using the key `MyNam ## See Also -* [Server Side Validation](../../Validation.md) \ No newline at end of file +* [Server Side Validation](../../Validation.md) diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Ajax.md b/docs/en/UI/AspNetCore/JavaScript-API/Ajax.md new file mode 100644 index 0000000000..dca3105b5c --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Ajax.md @@ -0,0 +1,150 @@ +# ASP.NET Core MVC / Razor Pages UI JavaScript AJAX API + +`abp.ajax` API provides a convenient way of performing AJAX calls to the server. It internally uses JQuery's `$.ajax`, but automates some common tasks for you; + +* Automatically **handles & localize the errors** and informs the user (using the [abp.message](Message.md)). So you typically don't care about errors. +* Automatically adds **anti forgery** token to the HTTP header to satisfy CSRF protection validation on the server side. +* Automatically sets **default options** and allows to configure the defaults in a single place. +* Can **block** a UI part (or the full page) during the AJAX operation. +* Allows to fully customize any AJAX call, by using the standard `$.ajax` **options**. + +> While `abp.ajax` makes the AJAX call pretty easier, you typically will use the [Dynamic JavaScript Client Proxy](Dynamic-JavaScript-Client-Proxies.md) system to perform calls to your server side HTTP APIs. `abp.ajax` can be used when you need to perform low level AJAX operations. + +## Basic Usage + +`abp.ajax` accepts an options object that is accepted by the standard [$.ajax](https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings). All the standard options are valid. It returns a [promise](https://api.jquery.com/category/deferred-object/) as the return value. + +**Example: Get the list of users** + +````js +abp.ajax({ + type: 'GET', + url: '/api/identity/users' +}).then(function(result){ + console.log(result); +}); +```` + +This command logs the list of users to the console, if you've **logged in** to the application and have [permission](../../../Authorization.md) for the user management page of the [Identity Module](../../../Modules/Identity.md). + +## Error Handling + +The example AJAX call above shows an **error message** if you haven't login to the application or you don't have the necessary permissions to perform this request: + +![ajax-error](../../../images/ajax-error.png) + +All kinds of errors are automatically handled by `abp.ajax`, unless you want to disable it. + +### Standard Error Response + +`abp.ajax` is compatible with the [exception handling system](../../../Exception-Handling.md) of the ABP Framework and it properly handles the standard error format returned from the server. A typical error message is a JSON as like below: + +````json +{ + "error": { + "code": "App:010042", + "message": "This topic is locked and can not add a new message", + "details": "A more detailed info about the error..." + } +} +```` + +The error message is directly shown to the user, using the `message` and `details` properties. + +### Non-Standard Error Response & HTTP Status Codes + +It also handles errors even if the standard error format was not sent by the server. This can be case if you bypass the ABP exception handling system and manually build the HTTP response on the server. In that case, **HTTP status codes** are considered. + +The following HTTP Status Codes are pre-defined; + +* **401**: Shows an error message like "*You should be authenticated (sign in) in order to perform this operation*". When the users click the OK button, they are redirected to the home page of the application to make them login again. +* **403**: Shows an error message like "*You are not allowed to perform this operation*". +* **404**: Shows an error message like "*The resource requested could not found on the server*". +* **Others**: Shows a generic error message like "*An error has occurred. Error detail not sent by server*". + +All these messages are localized based on the current user's language. + +### Manually Handling the Errors + +Since `abp.ajax` returns a promise, you can always chain a `.cactch(...)` call to register a callback that is executed if the AJAX request fails. + +**Example: Show an alert if the AJAX request fails** + +````js +abp.ajax({ + type: 'GET', + url: '/api/identity/users' +}).then(function(result){ + console.log(result); +}).catch(function(){ + alert("request failed :("); +}); +```` + +While your callback is fired, ABP still handles the error itself. If you want to disable automatic error handling, pass `abpHandleError: false` the the `abp.ajax` options. + +**Example: Disable the auto error handling** + +````js +abp.ajax({ + type: 'GET', + url: '/api/identity/users', + abpHandleError: false //DISABLE AUTO ERROR HANDLING +}).then(function(result){ + console.log(result); +}).catch(function(){ + alert("request failed :("); +}); +```` + +If you set `abpHandleError: false` and don't catch the error yourself, then the error will be hidden and the request silently fails. `abp.ajax` still logs the error to the browser console (see the *Configuration* section to override it). + +## Configuration + +`abp.ajax` has a **global configuration** that you can customize based on your requirements. + +### Default AJAX Options + +`abp.ajax.defaultOpts` object is used to configure default options used while performing an AJAX call, unless you override them. Default value of this object is shown below: + +````js +{ + dataType: 'json', + type: 'POST', + contentType: 'application/json', + headers: { + 'X-Requested-With': 'XMLHttpRequest' + } +} +```` + +So, if you want to change the default request type, you can do it as shown below: + +````js +abp.ajax.defaultOpts.type = 'GET'; +```` + +Write this code before all of your JavaScript code. You typically want to place such a configuration into a separate JavaScript file and add it to the layout using the global [bundle](../Bundling-Minification.md). + +### Log/Show Errors + +The following functions can be overridden to customize the logging and showing the error messages: + +* `abp.ajax.logError` function logs errors using the [abp.log.error(...)](Logging.md) by default. +* `abp.ajax.showError` function shows the error message using the [abp.message.error(...)](Message.md) by default. +* `abp.ajax.handleErrorStatusCode` handles different HTTP status codes and shows different messages based on the code. +* `abp.ajax.handleAbpErrorResponse` handles the errors sent with the standard ABP error format. +* `abp.ajax.handleNonAbpErrorResponse` handles the non-standard error responses. +* `abp.ajax.handleUnAuthorizedRequest` handles responses with `401` status code and redirect users to the home page of the application. + +**Example: Override the `logError` function** + +````js +abp.ajax.logError = function(error) { + //... +} +```` + +### Other Options + +* `abp.ajax.ajaxSendHandler` function is used to intercept the AJAX requests and add antiforgery token to the HTTP header. Note that this works for all AJAX requests, even if you don't use the `abp.ajax`. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Auth.md b/docs/en/UI/AspNetCore/JavaScript-API/Auth.md new file mode 100644 index 0000000000..45af8c4b3e --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Auth.md @@ -0,0 +1,24 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Auth API + +Auth API allows you to check permissions (policies) for the current user in the client side. In this way, you can conditionally show/hide UI parts or perform your client side logic based on the current permissions. + +> This document only explains the JavaScript API. See the [authorization document](../../../Authorization.md) to understand the ABP authorization & permission system. + +## Basic Usage + +`abp.auth.isGranted(...)` function is used to check if a permission/policy has granted or not: + +````js +if (abp.auth.isGranted('DeleteUsers')) { + //TODO: Delete the user +} else { + alert("You don't have permission to delete a user!"); +} +```` + +## Other Fields & Functions + +* ` abp.auth.isAnyGranted(...)`: Gets one or more permission/policy names and returns `true` if at least one of them has granted. +* `abp.auth.areAllGranted(...)`: Gets one or more permission/policy names and returns `true` if all of them of them have granted. +* `abp.auth.policies`: This is an object where its keys are the permission/policy names. You can find all permission/policy names here. +* `abp.auth.grantedPolicies`: This is an object where its keys are the permission/policy names. You can find the granted permission/policy names here. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Block-Busy.md b/docs/en/UI/AspNetCore/JavaScript-API/Block-Busy.md new file mode 100644 index 0000000000..943a651432 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Block-Busy.md @@ -0,0 +1,56 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript UI Block/Busy API + +UI Block API disables (blocks) the page or a part of the page. + +## Basic Usage + +**Example: Block (disable) the complete page** + +````js +abp.ui.block(); +```` + +**Example: Block (disable) an HTML element** + +````js +abp.ui.block('#MyContainer'); +```` + +**Example: Enables the previously blocked element or page:** + +````js +abp.ui.unblock(); +```` + +## Options + +`abp.ui.block()` method can get an options object which may contain the following fields: + +* `elm`: An optional selector to find the element to be blocked (e.g. `#MyContainerId`). If not provided, the entire page is blocked. The selector can also be directly passed to the `block()` method as shown above. +* `busy`: Set to `true` to show a progress indicator on the blocked area. +* `promise`: A promise object with `always` or `finally` callbacks. This can be helpful if you want to automatically unblock the blocked area when a deferred operation completes. + +**Example: Block an element with busy indicator** + +````js +abp.ui.block({ + elm: '#MySection', + busy: true +}); +```` + +The resulting UI will look like below: + +![ui-busy](../../../images/ui-busy.png) + +## setBusy + +`abp.ui.setBusy(...)` and `abp.ui.clearBusy()` are shortcut functions if you want to use the block with `busy` option. + +**Example: Block with busy** + +````js +abp.ui.setBusy('#MySection'); +```` + +Then you can use `abp.ui.clearBusy();` to re-enable the busy area/page. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/CurrentUser.md b/docs/en/UI/AspNetCore/JavaScript-API/CurrentUser.md new file mode 100644 index 0000000000..038bb9dff1 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/CurrentUser.md @@ -0,0 +1,49 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript CurrentUser API + +`abp.currentUser` is an object that contains information about the current user of the application. + +> This document only explains the JavaScript API. See the [CurrentUser document](../../../CurrentUser.md) to get information about the current user in the server side. + +## Authenticated User + +If the user was authenticated, this object will be something like below: + +````js +{ + isAuthenticated: true, + id: "34f1f4a7-13cc-4b91-84d1-b91c87afa95f", + tenantId: null, + userName: "john", + name: "John", + surName: "Nash", + email: "john.nash@abp.io", + emailVerified: true, + phoneNumber: null, + phoneNumberVerified: false, + roles: ["moderator","supporter"] +} +```` + +So, `abp.currentUser.userName` returns `john` in this case. + +## Anonymous User + +If the user was not authenticated, this object will be something like below: + +````js +{ + isAuthenticated: false, + id: null, + tenantId: null, + userName: null, + name: null, + surName: null, + email: null, + emailVerified: false, + phoneNumber: null, + phoneNumberVerified: false, + roles: [] +} +```` + +You can check `abp.currentUser.isAuthenticated` to understand if the use was authenticated or not. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/DOM.md b/docs/en/UI/AspNetCore/JavaScript-API/DOM.md new file mode 100644 index 0000000000..cdd4cef9db --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/DOM.md @@ -0,0 +1,117 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript DOM API + +`abp.dom` (Document Object Model) provides events that you can subscribe to get notified when elements dynamically added to and removed from the page (DOM). + +It is especially helpful if you want to initialize the new loaded elements. This is generally needed when you dynamically add elements to DOM (for example, get some HTML elements via AJAX) after page initialization. + +> ABP uses the [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe the changes made on the DOM. + +## Node Events + +### onNodeAdded + +This event is triggered when an element is added to the DOM. Example: + +````js +abp.dom.onNodeAdded(function(args){ + console.log(args.$el); +}); +```` + +`args` object has the following fields; + +* `$el`: The JQuery selection to get the new element inserted to the DOM. + +### onNodeRemoved + +This event is triggered when an element is removed from the DOM. Example: + +````js +abp.dom.onNodeRemoved(function(args){ + console.log(args.$el); +}); +```` + +`args` object has the following fields; + +* `$el`: The JQuery selection to get the element removed from the DOM. + +## Pre-Build Initializers + +ABP Framework is using the DOM events to initialize some kind of HTML elements when they are added to the DOM after than the page was already initialized. + +> Note that the same initializers also work if these elements were already included in the initial DOM. So, whether they are initially or lazy loaded, they work as expected. + +### Form Initializer + +The Form initializer (defined as `abp.dom.initializers.initializeForms`) initializes the lazy loaded forms; + +* Automatically enabled the `unobtrusive` validation on the form. +* Can automatically show a confirmation message when you submit the form. To enable this feature, just add `data-confirm` attribute with a message (like `data-confirm="Are you sure?"`) to the `form` element. +* If the `form` element has `data-ajaxForm="true"` attribute, then automatically calls the `.abpAjaxForm()` on the `form` element, to make the form posted via AJAX. + +See the [Forms & Validation](../Forms-Validation.md) document for more. + +### Script Initializer + +Script initializer (`abp.dom.initializers.initializeScript`) can execute a JavaScript code for a DOM element. + +**Example: Lazy load a component and execute some code when the element has loaded** + +Assume that you've a container to load the element inside: + +````html +
+```` + +And this is the component that will be loaded via AJAX from the server and inserted into the container: + +````html +
+

Sample message

+
+```` + +`data-script-class="MyCustomClass"` indicates the JavaScript class that will be used to perform some logic on this element: + +`MyCustomClass` is a global object defined as shown below: + +````js +MyCustomClass = function(){ + + function initDom($el){ + $el.css('color', 'red'); + } + + return { + initDom: initDom + } +}; +```` + +`initDom` is the function that is called by the ABP Framework. The `$el` argument is the loaded HTML element as a JQuery selection. + +Finally, you can load the component inside the container after an AJAX call: + +````js +$(function () { + setTimeout(function(){ + $.get('/get-my-element').then(function(response){ + $('#LazyComponent').html(response); + }); + }, 2000); +}); +```` + +Script Initialization system is especially helpful if you don't know how and when the component will be loaded into the DOM. This can be possible if you've developed a reusable UI component in a library and you want the application developer shouldn't care how to initialize the component in different use cases. + +> Script initialization doesn't work if the component was loaded in the initial DOM. In this case, you are responsible to initialize it. + +### Other Initializers + +The following Bootstrap components and libraries are automatically initialized when they are added to the DOM: + +* Tooltip +* Popover +* Timeage + diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Dynamic-JavaScript-Client-Proxies.md b/docs/en/UI/AspNetCore/JavaScript-API/Dynamic-JavaScript-Client-Proxies.md new file mode 100644 index 0000000000..5270852b60 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Dynamic-JavaScript-Client-Proxies.md @@ -0,0 +1,3 @@ +# ASP.NET Core MVC / Razor Pages UI: Dynamic JavaScript Client Proxies + +TODO \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Events.md b/docs/en/UI/AspNetCore/JavaScript-API/Events.md new file mode 100644 index 0000000000..3425355f44 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Events.md @@ -0,0 +1,88 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Events API + +`abp.event` object is a simple service that is used to publish and subscribe to global events **in the browser**. + +> This API is not related to server side local or distributed events. It works in the browser boundaries to make the UI components (code parts) communicate in a loosely coupled way. + +## Basic Usage + +### Publishing Events + +Use `abp.event.trigger` to publish events. + +**Example: Publish a *Basket Updated* event** + +````js +abp.event.trigger('basketUpdated'); +```` + +This will trigger all the subscribed callbacks. + +### Subscribing to the Events + +Use `abp.event.on` to subscribe to events. + +**Example: Consume the *Basket Updated* event** + +````js +abp.event.on('basketUpdated', function() { + console.log('Handled the basketUpdated event...'); +}); +```` + +You start to get events after you subscribe to the event. + +### Unsubscribing from the Events + +If you need to unsubscribe from a pre-subscribed event, you can use the `abp.event.off(eventName, callback)` function. In this case, you have the callback as a separate function declaration. + +**Example: Subscribe & Unsubscribe** + +````js +function onBasketUpdated() { + console.log('Handled the basketUpdated event...'); +} + +//Subscribe +abp.event.on('basketUpdated', onBasketUpdated); + +//Unsubscribe +abp.event.off('basketUpdated', onBasketUpdated); +```` + +You don't get events after you unsubscribe from the event. + +## Event Arguments + +You can pass arguments (of any count) to the `trigger` method and get them in the subscription callback. + +**Example: Add the basket as the event argument** + +````js +//Subscribe to the event +abp.event.on('basketUpdated', function(basket) { + console.log('The new basket object: '); + console.log(basket); +}); + +//Trigger the event +abp.event.trigger('basketUpdated', { + items: [ + { + "productId": "123", + "count": 2 + }, + { + "productId": "832", + "count": 1 + } + ] +}); +```` + +### Multiple Arguments + +If you want to pass multiple arguments, you can pass like `abp.event.on('basketUpdated', arg0, arg1, agr2)`. Then you can add the same argument list to the callback function on the subscriber side. + +> **Tip:** Alternatively, you can send a single object that has a separate field for each argument. This makes easier to extend/change the event arguments in the future without breaking the subscribers. + diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Features.md b/docs/en/UI/AspNetCore/JavaScript-API/Features.md new file mode 100644 index 0000000000..8d58347f49 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Features.md @@ -0,0 +1,29 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Features API + +`abp.features` API allows you to check features or get the values of the features on the client side. You can read the current value of a feature in the client side only if it is allowed by the feature definition (on the server side). + +> This document only explains the JavaScript API. See the [Features](../../../Features.md) document to understand the ABP Features system. + +## Basic Usage + +````js +//Gets a value as string. +var value = abp.features.get('ExportingToExcel'); + +//Check the feature is enabled +var enabled = abp.features.isEnabled('ExportingToExcel.Enabled'); +```` + +## All Values + +`abp.features.values` can be used to access to the all feature values. + +An example value of this object is shown below: + +````js +{ + Identity.TwoFactor: "Optional", + ExportingToExcel.Enabled: "true", + ... +} +```` \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Index.md b/docs/en/UI/AspNetCore/JavaScript-API/Index.md index 9f584eacfb..3473140392 100644 --- a/docs/en/UI/AspNetCore/JavaScript-API/Index.md +++ b/docs/en/UI/AspNetCore/JavaScript-API/Index.md @@ -1,23 +1,19 @@ # JavaScript API -ABP provides some JavaScript APIs for ASP.NET Core MVC / Razor Pages applications. They can be used to perform some common application requirements in the client side. +ABP provides a set of JavaScript APIs for ASP.NET Core MVC / Razor Pages applications. They can be used to perform common application requirements easily in the client side and integrate to the server side. ## APIs -* abp.ajax -* abp.auth -* abp.currentUser -* abp.dom -* abp.event -* abp.features -* abp.localization -* abp.log -* abp.ModalManager -* abp.notify -* abp.security -* abp.setting -* abp.ui -* abp.utils -* abp.ResourceLoader -* abp.WidgetManager -* Other APIs \ No newline at end of file +* [AJAX](Ajax.md) +* [Auth](Auth.md) +* [CurrentUser](CurrentUser.md) +* [DOM](DOM.md) +* [Events](Events.md) +* [Features](Features.md) +* [Localization](Localization.md) +* [Logging](Logging.md) +* [ResourceLoader](ResourceLoader.md) +* [Settings](Settings.md) +* [UI Block/Busy](Block-Busy.md) +* [UI Message](Message.md) +* [UI Notification](Notify.md) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Localization.md b/docs/en/UI/AspNetCore/JavaScript-API/Localization.md new file mode 100644 index 0000000000..0897b99268 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Localization.md @@ -0,0 +1,143 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Localization API + +Localization API allows you to reuse the server side localization resources in the client side. + +> This document only explains the JavaScript API. See the [localization document](../../../Localization.md) to understand the ABP localization system. + +## Basic Usage + +`abp.localization.getResource(...)` function is used to get a localization resource: + +````js +var testResource = abp.localization.getResource('Test'); +```` + +Then you can localize a string based on this resource: + +````js +var str = testResource('HelloWorld'); +```` + +`abp.localization.localize(...)` function is a shortcut where you can both specify the text name and the resource name: + +````js +var str = abp.localization.localize('HelloWorld', 'Test'); +```` + +`HelloWorld` is the text to localize, where `Test` is the localization resource name here. + +### Fallback Logic + +If given texts was not localized, localization method returns the given key as the localization result. + +### Default Localization Resource + +If you don't specify the localization resource name, it uses the **default localization resource** defined on the `AbpLocalizationOptions` (see the [localization document](../../../Localization.md)). + +**Example: Using the default localization resource** + +````js +var str = abp.localization.localize('HelloWorld'); //uses the default resource +```` + +### Format Arguments + +If your localized string contains arguments, like `Hello {0}, welcome!`, you can pass arguments to the localization methods. Examples: + +````js +var testSource = abp.localization.getResource('Test'); +var str1 = testSource('HelloWelcomeMessage', 'John'); +var str2 = abp.localization.localize('HelloWelcomeMessage', 'Test', 'John'); +```` + +Assuming the `HelloWelcomeMessage` is localized as `Hello {0}, welcome!`, both of the samples above produce the output `Hello John, welcome!`. + +## Other Properties & Methods + +### abp.localization.values + +`abp.localization.values` property stores all the localization resources, keys and their values. + +### abp.localization.isLocalized + +Returns a boolean indicating that if the given text was localized or not. + +**Example** + +````js +abp.localization.isLocalized('ProductName', 'MyResource'); +```` + +Returns `true` if the `ProductName` text was localized for the `MyResource` resource. Otherwise, returns `false`. You can leave the resource name empty to use the default localization resource. + +### abp.localization.defaultResourceName + +`abp.localization.defaultResourceName` can be set to change the default localization resource. You normally don't set this since the ABP Framework automatically sets is based on the server side configuration. + +### abp.localization.currentCulture + +`abp.localization.currentCulture` returns an object to get information about the **currently selected language**. + +An example value of this object is shown below: + +````js +{ + "displayName": "English", + "englishName": "English", + "threeLetterIsoLanguageName": "eng", + "twoLetterIsoLanguageName": "en", + "isRightToLeft": false, + "cultureName": "en", + "name": "en", + "nativeName": "English", + "dateTimeFormat": { + "calendarAlgorithmType": "SolarCalendar", + "dateTimeFormatLong": "dddd, MMMM d, yyyy", + "shortDatePattern": "M/d/yyyy", + "fullDateTimePattern": "dddd, MMMM d, yyyy h:mm:ss tt", + "dateSeparator": "/", + "shortTimePattern": "h:mm tt", + "longTimePattern": "h:mm:ss tt" + } +} +```` + +### abp.localization.languages + +Used to get list of all **available languages** in the application. An example value of this object is shown below: + +````js +[ + { + "cultureName": "en", + "uiCultureName": "en", + "displayName": "English", + "flagIcon": null + }, + { + "cultureName": "fr", + "uiCultureName": "fr", + "displayName": "Français", + "flagIcon": null + }, + { + "cultureName": "pt-BR", + "uiCultureName": "pt-BR", + "displayName": "Português", + "flagIcon": null + }, + { + "cultureName": "tr", + "uiCultureName": "tr", + "displayName": "Türkçe", + "flagIcon": null + }, + { + "cultureName": "zh-Hans", + "uiCultureName": "zh-Hans", + "displayName": "简体中文", + "flagIcon": null + } +] +```` + diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Logging.md b/docs/en/UI/AspNetCore/JavaScript-API/Logging.md new file mode 100644 index 0000000000..a46203b019 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Logging.md @@ -0,0 +1,50 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Logging API + +`abp.log` API is used to write simple logs in the client side. + +> The logs are written to console, using the `console.log`, by default. + +> This document is for simple client side logging. See the [Logging](../../../Logging.md) document for server side logging system. + +## Basic Usage + +Use one of the `abp.log.xxx(...)` methods based on the severity of your log message. + +````js +abp.log.debug("Some debug log here..."); //Logging a simple debug message +abp.log.info({ name: "john", age: 42 }); //Logging an object as an information log +abp.log.warn("A warning message"); //Logging a warning message +abp.log.error('An error happens...'); //Error message +abp.log.fatal('Network connection has gone away!'); //Fatal error +```` + +## Log Levels + +There are 5 levels for a log message: + +* DEBUG = 1 +* INFO = 2 +* WARN = 3 +* ERROR = 4 +* FATAL = 5 + +These are defined in the `abp.log.levels` object (like `abp.log.levels.WARN`). + +### Changing the Current Log Level + +You can control the log level as shown below: + +````js +abp.log.level = abp.log.levels.WARN; +```` + +Default log level is `DEBUG`. + +### Logging with Specifying the Level + +Instead of calling `abp.log.info(...)` function, you can use the `abp.log.log` by specifying the log level as a parameter: + +````js +abp.log.log("log message...", abp.log.levels.INFO); +```` + diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Message.md b/docs/en/UI/AspNetCore/JavaScript-API/Message.md new file mode 100644 index 0000000000..68c74914c6 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Message.md @@ -0,0 +1,128 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Message API + +Message API is used to show nice looking messages to the user as a blocking dialog. Message API is an abstraction provided by the ABP Framework and implemented using the [SweetAlert2](https://sweetalert2.github.io/) library by default. + +## Quick Example + +Use `abp.message.success(...)` function to show a success message: + +````js +abp.message.success('Your changes have been successfully saved!', 'Congratulations'); +```` + +It will show a dialog on the UI: + +![js-message-success](../../../images/js-message-success.png) + +## Informative Messages + +There are four types of informative message functions: + +* `abp.message.info(...)` +* `abp.message.success(...)` +* `abp.message.warn(...)` +* `abp.message.error(...)` + +All these methods get two parameters: + +* `message`: The message (`string`) to be shown. +* `title`: An optional (`string`) title. + +**Example: Show an error message** + +````js +abp.message.error('Your credit card number is not valid!'); +```` + +![js-message-error](../../../images/js-message-error.png) + +## Confirmation Message + +`abp.message.confirm(...)` function can be used to get a confirmation from the user. + +**Example** + +Use the following code to get a confirmation result from the user: + +````js +abp.message.confirm('Are you sure to delete the "admin" role?') +.then(function(confirmed){ + if(confirmed){ + console.log('TODO: deleting the role...'); + } +}); +```` + +The resulting UI will be like shown below: + +![js-message-confirm](../../../images/js-message-confirm.png) + +If user has clicked the `Yes` button, the `confirmed` argument in the `then` callback function will be `true`. + +> "*Are you sure?*" is the default title (localized based on the current language) and you can override it. + +### The Return Value + +The return value of the `abp.message.confirm(...)` function is a promise, so you can chain a `then` callback as shown above. + +### Parameters + +`abp.message.confirm(...)` function has the following parameters: + +* `message`: A message (string) to show to the user. +* `titleOrCallback` (optional): A title or a callback function. If you supply a string, it is shown as the title. If you supply a callback function (that gets a `bool` parameter) then it's called with the result. +* `callback` (optional): If you've passes a title to the second parameter, you can pass your callback function as the 3rd parameter. + +Passing a callback function is an alternative to the `then` callback shown above. + +**Example: Providing all the parameters and getting result with the callback function** + +````js +abp.message.confirm( + 'Are you sure to delete the "admin" role?', + 'Be careful!', + function(confirmed){ + if(confirmed){ + console.log('TODO: deleting the role...'); + } + }); +```` + +## SweetAlert Configuration + +The Message API is implemented using the [SweetAlert2](https://sweetalert2.github.io/) library by default. If you want to change its configuration, you can set the options in the `abp.libs.sweetAlert.config` object. The default configuration object is shown below: + +````js +{ + 'default': { + }, + info: { + icon: 'info' + }, + success: { + icon: 'success' + }, + warn: { + icon: 'warning' + }, + error: { + icon: 'error' + }, + confirm: { + icon: 'warning', + title: 'Are you sure?', + buttons: ['Cancel', 'Yes'] + } +} +```` + +> "Are you sure?", "Cancel" and "Yes" texts are automatically localized based on the current language. + +So, if you want to set the `warn` icon, you can set it like: + +````js +abp.libs.sweetAlert.config.warn.icon = 'error'; +```` + +See the [SweetAlert document](https://sweetalert2.github.io/) for all the configuration options. + diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Notify.md b/docs/en/UI/AspNetCore/JavaScript-API/Notify.md new file mode 100644 index 0000000000..371aa8d4b9 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Notify.md @@ -0,0 +1,45 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Notify API + +Notify API is used to show toast style, auto disappearing UI notifications to the end user. It is implemented by the [Toastr](https://github.com/CodeSeven/toastr) library by default. + +## Quick Example + +Use `abp.notify.success(...)` function to show a success message: + +````js +abp.notify.success( + 'The product "Acme Atom Re-Arranger" has been successfully deleted.', + 'Deleted the Product' +); +```` + +A notification message is shown at the bottom right of the page: + +![js-message-success](../../../images/js-notify-success.png) + +## Notification Types + +There are four types of pre-defined notifications; + +* `abp.notify.success(...)` +* `abp.notify.info(...)` +* `abp.notify.warn(...)` +* `abp.notify.error(...)` + +All of the methods above gets the following parameters; + +* `message`: A message (`string`) to show to the user. +* `title`: An optional title (`string`). +* `options`: Additional options to be passed to the underlying library, to the Toastr by default. + +## Toastr Configuration + +The notification API is implemented by the [Toastr](https://github.com/CodeSeven/toastr) library by default. You can see its own configuration options. + +**Example: Show toast messages on the top right of the page** + +````js +toastr.options.positionClass = 'toast-top-right'; +```` + +> ABP sets this option to `toast-bottom-right` by default. You can override it just as shown above. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/JavaScript-API/ResourceLoader.md b/docs/en/UI/AspNetCore/JavaScript-API/ResourceLoader.md new file mode 100644 index 0000000000..10b8c36f59 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/ResourceLoader.md @@ -0,0 +1,40 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Resource Loader API + +`abp.ResourceLoader` is a service that can load a JavaScript or CSS file on demand. It guarantees to load the file only once even if you request multiple times. + +## Loading Script Files + +`abp.ResourceLoader.loadScript(...)` function **loads** a JavaScript file from the server and **executes** it. + +**Example: Load a JavaScript file** + +````js +abp.ResourceLoader.loadScript('/Pages/my-script.js'); +```` + +### Parameters + +`loadScript` function can get three parameters; + +* `url` (required, `string`): The URL of the script file to be loaded. +* `loadCallback` (optional, `function`): A callback function that is called once the script is loaded & executed. In this callback you can safely use the code in the script file. This callback is called even if the file was loaded before. +* `failCallback` (optional, `function`): A callback function that is called if loading the script fails. + +**Example: Provide the `loadCallback` argument** + +````js +abp.ResourceLoader.loadScript('/Pages/my-script.js', function() { + console.log('successfully loaded :)'); +}); +```` + +## Loading Style Files + +`abp.ResourceLoader.loadStyle(...)` function adds a `link` element to the `head` of the document for the given URL, so the CSS file is automatically loaded by the browser. + +**Example: Load a CSS file** + +````js +abp.ResourceLoader.loadStyle('/Pages/my-styles.css'); +```` + diff --git a/docs/en/UI/AspNetCore/JavaScript-API/Settings.md b/docs/en/UI/AspNetCore/JavaScript-API/Settings.md new file mode 100644 index 0000000000..cf96cecdd0 --- /dev/null +++ b/docs/en/UI/AspNetCore/JavaScript-API/Settings.md @@ -0,0 +1,33 @@ +# ASP.NET Core MVC / Razor Pages UI: JavaScript Setting API + +Localization API allows you to get the values of the settings on the client side. You can read the current value of a setting in the client side only if it is allowed by the setting definition (on the server side). + +> This document only explains the JavaScript API. See the [settings document](../../../Settings.md) to understand the ABP setting system. + +## Basic Usage + +````js +//Gets a value as string. +var language = abp.setting.get('Abp.Localization.DefaultLanguage'); + +//Gets an integer value. +var requiredLength = abp.setting.getInt('Abp.Identity.Password.RequiredLength'); + +//Gets a boolean value. +var requireDigit = abp.setting.getBoolean('Abp.Identity.Password.RequireDigit'); +```` + +## All Values + +`abp.setting.values` can be used to obtain all the setting values as an object where the object properties are setting names and property values are the setting values. + +An example value of this object is shown below: + +````js +{ + Abp.Localization.DefaultLanguage: "en", + Abp.Timing.TimeZone: "UTC", + ... +} +```` + diff --git a/docs/en/UI/AspNetCore/Layout-Hooks.md b/docs/en/UI/AspNetCore/Layout-Hooks.md index 49b334c6c0..168454a7c2 100644 --- a/docs/en/UI/AspNetCore/Layout-Hooks.md +++ b/docs/en/UI/AspNetCore/Layout-Hooks.md @@ -1,3 +1,105 @@ -# Layout Hooks +# ASP.NET Core MVC / Razor Pages: Layout Hooks -TODO \ No newline at end of file +ABP Framework theming system places the page layout into the [theme](Theming.md) NuGet packages. That means the final application doesn't include a `Layout.cshtml`, so you can't directly change the layout code to customize it. + +You copy the theme code into your solution. In this case you are completely free to customize it. However, then you won't be able to get automatic updates of the theme (by upgrading the theme NuGet package). + +ABP Framework provides different ways of [customizing the UI](Customization-User-Interface.md). + +The **Layout Hook System** allows you to **add code** at some specific parts of the layout. All layouts of all themes should implement these hooks. Finally, you can add a **view component** into a hook point. + +## Example: Add Google Analytics Script + +Assume that you need to add the Google Analytics script to the layout (that will be available for all the pages). First, **create a view component** in your project: + +![bookstore-google-analytics-view-component](../../images/bookstore-google-analytics-view-component.png) + +**NotificationViewComponent.cs** + +````csharp +public class GoogleAnalyticsViewComponent : AbpViewComponent +{ + public IViewComponentResult Invoke() + { + return View("/Pages/Shared/Components/GoogleAnalytics/Default.cshtml"); + } +} +```` + +**Default.cshtml** + +````html + +```` + +Change `UA-xxxxxx-1` with your own code. + +You can then add this component to any of the hook points in the `ConfigureServices` of your module: + +````csharp +Configure(options => +{ + options.Add( + LayoutHooks.Head.Last, //The hook name + typeof(GoogleAnalyticsViewComponent) //The component to add + ); +}); +```` + +Now, the GA code will be inserted in the `head` of the page as the last item. + +### Specifying the Layout + +The configuration above adds the `GoogleAnalyticsViewComponent` to all layouts. You may want to only add to a specific layout: + +````csharp +Configure(options => +{ + options.Add( + LayoutHooks.Head.Last, + typeof(GoogleAnalyticsViewComponent), + layout: StandardLayouts.Application //Set the layout to add + ); +}); +```` + +See the *Layouts* section below to learn more about the layout system. + +## Layout Hook Points + +There are some pre-defined layout hook points. The `LayoutHooks.Head.Last` used above was one of them. The standard hook points are; + +* `LayoutHooks.Head.First`: Used to add a component as the first item in the HTML head tag. +* `LayoutHooks.Head.Last`: Used to add a component as the last item in the HTML head tag. +* `LayoutHooks.Body.First`: Used to add a component as the first item in the HTML body tag. +* `LayoutHooks.Body.Last`: Used to add a component as the last item in the HTML body tag. +* `LayoutHooks.PageContent.First`: Used to add a component just before the page content (the `@RenderBody()` in the layout). +* `LayoutHooks.PageContent.Last`: Used to add a component just after the page content (the `@RenderBody()` in the layout). + +> You (or the modules you are using) can add **multiple items to the same hook point**. All of them will be added to the layout by the order they were added. + +## Layouts + +Layout system allows themes to define standard, named layouts and allows any page to select a proper layout for its purpose. There are three pre-defined layouts: + +* "**Application**": The main (and the default) layout for an application. It typically contains header, menu (sidebar), footer, toolbar... etc. +* "**Account**": This layout is used by login, register and other similar pages. It is used for the pages under the `/Pages/Account` folder by default. +* "**Empty**": Empty and minimal layout. + +These names are defined in the `StandardLayouts` class as constants. You can definitely create your own layouts, but these are the standard layout names and implemented by all the themes out of the box. + +### Layout Location + +You can find the layout files [here](https://github.com/abpframework/abp/tree/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Layouts) for the basic theme. You can take them as references to build your own layouts or you can override them if necessary. + +## See Also + +* [Customizing the User Interface](Customization-User-Interface.md) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Libraries/DatatablesNet.md b/docs/en/UI/AspNetCore/Libraries/DatatablesNet.md deleted file mode 100644 index a5a66e9e19..0000000000 --- a/docs/en/UI/AspNetCore/Libraries/DatatablesNet.md +++ /dev/null @@ -1,3 +0,0 @@ -# ABP Datatables.Net Integration for ASP.NET Core UI - -TODO \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Modals.md b/docs/en/UI/AspNetCore/Modals.md new file mode 100644 index 0000000000..9de9542307 --- /dev/null +++ b/docs/en/UI/AspNetCore/Modals.md @@ -0,0 +1,483 @@ +# ASP.NET Core MVC / Razor Pages UI: Modals + +While you can continue to use the standard [Bootstrap way](https://getbootstrap.com/docs/4.5/components/modal/) to create, open and manage modals in your applications, ABP Framework provides a **flexible** way to manage modals by **automating common tasks** for you. + +**Example: A modal dialog to create a new role entity** + +![modal-manager-example-modal](../../images/modal-manager-example-modal.png) + +ABP Framework provides the following benefits for such a modal with a form inside it; + +* **Lazy loads** the modal HTML into the page and **removes** it from the DOM once its closed. This makes easy to consume a reusable modal dialog. Also, every time you open the modal, it will be a fresh new modal, so you don't have to deal with resetting the modal content. +* **Auto-focuses** the first input of the form once the modal has been opened. +* Automatically determines the **form** inside a modal and posts the form via **AJAX** instead of normal page post. +* Automatically checks if the form inside the modal **has changed, but not saved**. It warns the user in this case. +* Automatically **disables the modal buttons** (save & cancel) until the AJAX operation completes. +* Makes it easy to register a **JavaScript object that is initialized** once the modal has loaded. + +So, it makes you write less code when you deal with the modals, especially the modals with a form inside. + +## Basic Usage + +### Creating a Modal as a Razor Page + +To demonstrate the usage, we are creating a simple Razor Page, named `ProductInfoModal.cshtml`, under the `/Pages/Products` folder: + +![modal-page-on-rider](../../images/modal-page-on-rider.png) + +**ProductInfoModal.cshtml Content:** + +````html +@page +@model MyProject.Web.Pages.Products.ProductInfoModalModel +@{ + Layout = null; +} + + + +

@Model.ProductName

+
+ +
+

+ @Model.ProductDescription +

+

+ Reference: https://acme.com/catalog/ +

+
+ +
+```` + +* This page sets the `Layout` to `null` since we will show this as a modal. So, no need to wrap with a layout. +* It uses [abp-modal tag helper](Tag-Helpers/Modals.md) to simplify creating the modal HTML code. You can use the standard Bootstrap modal code if you prefer it. + +**ProductInfoModalModel.cshtml.cs Content:** + +```csharp +using Volo.Abp.AspNetCore.Mvc.UI.RazorPages; + +namespace MyProject.Web.Pages.Products +{ + public class ProductInfoModalModel : AbpPageModel + { + public string ProductName { get; set; } + + public string ProductDescription { get; set; } + + public string ProductImageUrl { get; set; } + + public void OnGet() + { + ProductName = "Acme Indestructo Steel Ball"; + ProductDescription = "The ACME Indestructo Steel Ball is completely indestructible, there is nothing that can destroy it!"; + ProductImageUrl = "https://acme.com/catalog/acmeindestructo.jpg"; + } + } +} +``` + +You can surely get the product info from a database or API. We are setting the properties hard-coded for the sake of simplicity, + +### Defining the Modal Manager + +Once you have a modal, you can open it in any page using some simple **JavaScript** code. + +First, create an `abp.ModalManager` object by setting the `viewUrl`, in the JavaScript file of the page that will use the modal: + +````js +var productInfoModal = new abp.ModalManager({ + viewUrl: '/Products/ProductInfoModal' +}); +```` + +> If you only need to specify the `viewUrl`, you can directly pass it to the `ModalManager` constructor, as a shortcut. Example: `new abp.ModalManager('/Products/ProductInfoModal');` + +### Opening the Modal + +Then open the modal whenever you need: + +````js +productInfoModal.open(); +```` + +You typically want to open the modal when something happens; For example, when the user clicks a button: + +````js +$('#OpenProductInfoModal').click(function(){ + productInfoModal.open(); +}); +```` + +The resulting modal will be like that: + +![modal-example-product-info](../../images/modal-example-product-info.png) + +#### Opening the Modal with Arguments + +When you call the `open()` method, `ModalManager` loads the modal HTML by requesting it from the `viewUrl`. You can pass some **query string parameters** to this URL when you open the modal. + +**Example: Pass the product id while opening the modal** + +````js +productInfoModal.open({ + productId: 42 +}); +```` + +You can add a `productId` parameter to the get method: + +````csharp +using Volo.Abp.AspNetCore.Mvc.UI.RazorPages; + +namespace MyProject.Web.Pages.Products +{ + public class ProductInfoModalModel : AbpPageModel + { + //... + + public async Task OnGetAsync(int productId) //Add productId parameter + { + //TODO: Get the product with database with the given productId + //... + } + } +} +```` + +In this way, you can use the `productId` to query the product from a data source. + +## Modals with Forms + +`abp.ModalManager` handles various common tasks (described in the introduction) when you want to use a form inside the modal. + +### Example Modal with a Form + +This section shows an example form to create a new product. + +#### Creating the Razor Page + +For this example, creating a new Razor Page, named `ProductCreateModal.cshtml`, under the `/Pages/Products` folder: + +![product-create-modal-page-on-rider](../../images/product-create-modal-page-on-rider.png) + +**ProductCreateModal.cshtml Content:** + +````html +@page +@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal +@model MyProject.Web.Pages.Products.ProductCreateModalModel +@{ + Layout = null; +} +
+ + + + + + + + + +
+```` + +* The `abp-modal` has been wrapped by the `form`. This is needed to place the `Save` and the `Cancel` buttons into the form. In this way, the `Save` button acts as the `submit` button for the `form`. +* Used the [abp-input tag helpers](Tag-Helpers/Form-Elements.md) to simplify to create the form elements. Otherwise, you need to write more HTML. + +**ProductCreateModal.cshtml.cs Content:** + +```csharp +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Volo.Abp.AspNetCore.Mvc.UI.RazorPages; + +namespace MyProject.Web.Pages.Products +{ + public class ProductCreateModalModel : AbpPageModel + { + [BindProperty] + public PoductCreationDto Product { get; set; } + + public async Task OnGetAsync() + { + //TODO: Get logic, if available + } + + public async Task OnPostAsync() + { + //TODO: Save the Product... + + return NoContent(); + } + } +} +``` + +* This is a simple `PageModal` class. The `[BindProperty]` make the form binding to the model when you post (submit) the form; The standard ASP.NET Core system. +* `OnPostAsync` returns `NoContent` (this method is defined by the base `AbpPageModel` class). Because we don't need to a return value in the client side, after the form post operation. + +**PoductCreationDto:** + +`ProductCreateModalModel` uses a `PoductCreationDto` class defined as shown below: + +````csharp +using System; +using System.ComponentModel.DataAnnotations; +using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form; + +namespace MyProject.Web.Pages.Products +{ + public class PoductCreationDto + { + [Required] + [StringLength(128)] + public string Name { get; set; } + + [TextArea(Rows = 4)] + [StringLength(2000)] + public string Description { get; set; } + + [DataType(DataType.Date)] + public DateTime ReleaseDate { get; set; } + } +} +```` + +* `abp-input` Tag Helper can understand the data annotation attributes and uses them to shape and validate the form elements. See the [abp-input tag helpers](Tag-Helpers/Form-Elements.md) document to learn more. + +#### Defining the Modal Manager + +Again, create an `abp.ModalManager` object by setting the `viewUrl`, in the JavaScript file of the page that will use the modal: + +````js +var productCreateModal = new abp.ModalManager({ + viewUrl: '/Products/ProductCreateModal' +}); +```` + +#### Opening the Modal + +Then open the modal whenever you need: + +````js +productCreateModal.open(); +```` + +You typically want to open the modal when something happens; For example, when the user clicks a button: + +````js +$('#OpenProductCreateModal').click(function(){ + productCreateModal.open(); +}); +```` + +So, the complete code will be something like that (assuming you have a `button` with `id` is `OpenProductCreateModal` on the view side): + +```js +$(function () { + + var productCreateModal = new abp.ModalManager({ + viewUrl: '/Products/ProductCreateModal' + }); + + $('#OpenProductCreateModal').click(function () { + productCreateModal.open(); + }); + +}); +``` + +The resulting modal will be like that: + +![modal-example-product-create](../../images/modal-example-product-create.png) + +#### Saving the Modal + +When you click to the `Save` button, the form is posted to the server. If the server returns a **success response**, then the `onResult` event is triggered with some arguments including the server response and the modal is automatically closed. + +An example callback that logs the arguments passed to the `onResult` method: + +````js +productCreateModal.onResult(function(){ + console.log(arguments); +}); +```` + +If the server returns a failed response, it shows the error message returned from the server and keeps the modal open. + +> See the *Modal Manager Reference* section below for other modal events. + +#### Canceling the Modal + +If you click to the Cancel button with some changes made but not saved, you get such a warning message: + +![modal-manager-cancel-warning](../../images/modal-manager-cancel-warning.png) + +If you don't want such a check & message, you can add `data-check-form-on-close="false"` attribute to your `form` element. Example: + +````html +
+```` + +### Form Validation + +`ModalManager` automatically triggers the form validation when you click to the `Save` button or hit the `Enter` key on the form: + +![modal-manager-validation](../../images/modal-manager-validation.png) + +See the [Forms & Validation document](Forms-Validation.md) to learn more about the validation. + +## Modals with Script Files + +You may need to perform some logic for your modal. To do that, create a JavaScript file like below: + +````js +abp.modals.ProductInfo = function () { + + function initModal(modalManager, args) { + var $modal = modalManager.getModal(); + var $form = modalManager.getForm(); + + $modal.find('h3').css('color', 'red'); + + console.log('initialized the modal...'); + }; + + return { + initModal: initModal + }; +}; +```` + +* This code simply adds a `ProductInfo` class into the `abp.modals` namespace. The `ProductInfo` class exposes a single public function: `initModal`. +* `initModal` method is called by the `ModalManager` once the modal HTML is inserted to DOM and ready for the initialization logic. +* `modalManager` parameter is the `ModalManager` object related to this modal instance. So, you can use any function on it in your code. See the *ModalManager Reference* section. + +Then include this file to the page that you use the modal: + +````html + + +```` + +* We've use the `abp-script` Tag Helper here. See the [Bundling & Minification](Bundling-Minification.md) document if you want to understand it. You can use the standard `script` tag. It doesn't matter for this case. + +Finally, set the `modalClass` option while creating the `ModalManager` instance: + +````js +var productInfoModal = new abp.ModalManager({ + viewUrl: '/Products/ProductInfoModal', + modalClass: 'ProductInfo' //Matches to the abp.modals.ProductInfo +}); +```` + +### Lazy Loading the Script File + +Instead of adding the `ProductInfoModal.js` to the page you use the modal, you can configure it to lazy load the script file when the first time the modal is opened. + +Example: + +````js +var productInfoModal = new abp.ModalManager({ + viewUrl: '/Products/ProductInfoModal', + scriptUrl: '/Pages/Products/ProductInfoModal.js', //Lazy Load URL + modalClass: 'ProductInfo' +}); +```` + +* `scriptUrl` is used to set the URL to load the script file of the modal. +* In this case, you no longer need to include the `ProductInfoModal.js` to the page. It will be loaded on demand. + +#### Tip: Bundling & Minification + +While lazy loading seems cool at the beginning, it requires an additional call to the server when you first open the modal. + +Instead, you can use the [Bundling & Minification](Bundling-Minification.md) system to create a bundle (that is a single and minified file on production) for all the used script files for a page: + +````html + + + + +```` + +This is efficient if the script file is not large and frequently opened while users use the page. + +Alternatively, you can define the `abp.modals.ProductInfo` class in the page's main JavaScript file if the modal is only and always used in the same page. In this case, you don't need to another external script file at all. + +## ModalManager Reference + +### Options + +Options can be passed when you create a new `ModalManager` object: + +````js +var productInfoModal = new abp.ModalManager({ + viewUrl: '/Products/ProductInfoModal', + //...other options +}); +```` + +Here, the list of all available options; + +* `viewUrl` (required, `string`): The URL to lazy load the HTML of the modal. +* `scriptUrl` (optional, `string`): A URL to lazy load a JavaScript file. It is loaded only once, when the modal first opened. +* `modalClass` (optional, `string`): A JavaScript class defined in the `abp.modals` namespace that can be used to execute code related to the modal. + +### Functions + +When you create a new `ModalManager` object, you can use its functions to perform operations on the modal. Example: + +````js +var myModal = new abp.ModalManager({ + //...options +}); + +//Open the modal +myModal.open(); + +//Close the modal +myModal.close(); +```` + +Here, the list of all available functions of the `ModalManager` object; + +* `open([args])`: Opens the modal dialog. It can get an `args` object that is converted to query string while getting the `viewUrl` from the server. For example, if `args` is `{ productId: 42 }`, then the `ModalManager` passes `?productId=42` to the end of the `viewUrl` while loading the view from the server. +* `reopen()`: Opens the modal with the latest provided `args` for the `open()` method. So, it is a shortcut if you want to re-open the modal with the same `args`. +* `close()`: Closes the modal. The modal HTML is automatically removed from DOM once it has been closed. +* `getModalId()`: Gets the `id` attribute of the container that contains the view returned from the server. This is a unique id per modal and it doesn't change after you create the `ModalManager`. +* `getModal()`: Returns the modal wrapper DOM element (the HTML element with the `modal` CSS class) as a JQuery selection, so you can perform any JQuery method on it. +* `getForm()`: Returns the `form` HTML element as a JQuery selection, so you can perform any JQuery method on it. It returns `null` if the modal has no form inside it. +* `getArgs()` Gets the latest arguments object provided while opening the modal. +* `getOptions()`: Gets the options object passed to the `ModalManager` constructor. +* `setResult(...)`: Triggers the `onResult` event with the provided arguments. You can pass zero or more arguments those are directly passed to the `onResult` event. This function is generally called by the modal script to notify the page that uses the modal. + +### Events + +When you create a new `ModalManager` object, you can use its functions register to events of the modal. Examples: + +````js +var myModal = new abp.ModalManager({ + //...options +}); + +myModal.onOpen(function () { + console.log('opened the modal...'); +}); + +myModal.onClose(function () { + console.log('closed the modal...'); +}); +```` + +Here, the list of all available functions to register to events of the `ModalManager` object; + +* `onOpen(callback)`: Registers a callback function to get notified once the modal is opened. It is triggered when the modal is completely visible on the UI. +* `onClose(callback)`: Registers a callback function to get notified once the modal is closed. It is triggered when the modal is completely invisible on the UI. +* `onResult(callback)`: Registers a callback function that is triggered when the ``setResult(...)` method is called. All the parameters sent to the `setResult` method is passed to the callback. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Navigation-Menu.md b/docs/en/UI/AspNetCore/Navigation-Menu.md index 4e0164ec72..7a8fe31e3e 100644 --- a/docs/en/UI/AspNetCore/Navigation-Menu.md +++ b/docs/en/UI/AspNetCore/Navigation-Menu.md @@ -1,3 +1,217 @@ -# Navigation Menu +# ASP.NET Core MVC / Razor Pages UI: Navigation Menu + +Every application has a main menu to allow users to navigate to pages/screens of the application. Some applications may contain more than one menu in different sections of the UI. + +ABP Framework is a [modular](../../Module-Development-Basics.md) application development framework. **Every module may need to add items to the menu**. + +So, ABP Framework **provides a menu infrastructure** where; + +* The application or the modules can add items to a menu, without knowing how the menu is rendered. +* The [theme](Theming.md) properly renders the menu. + +## Adding Menu Items + +In order to add menu items (or manipulate the existing items) you need to create a class implementing the `IMenuContributor` interface. + +> The [application startup template](../../Startup-Templates/Application.md) already contains an implementation of the `IMenuContributor`. So, you can add items inside that class instead of creating a new one. + +**Example: Add a *CRM* menu item with *Customers* and *Orders* sub menu items** + +```csharp +using System.Threading.Tasks; +using MyProject.Localization; +using Volo.Abp.UI.Navigation; + +namespace MyProject.Web.Menus +{ + public class MyProjectMenuContributor : IMenuContributor + { + public async Task ConfigureMenuAsync(MenuConfigurationContext context) + { + if (context.Menu.Name == StandardMenus.Main) + { + await ConfigureMainMenuAsync(context); + } + } + + private async Task ConfigureMainMenuAsync(MenuConfigurationContext context) + { + var l = context.GetLocalizer(); + + context.Menu.AddItem( + new ApplicationMenuItem("MyProject.Crm", l["Menu:CRM"]) + .AddItem(new ApplicationMenuItem( + name: "MyProject.Crm.Customers", + displayName: l["Menu:Customers"], + url: "/crm/customers") + ).AddItem(new ApplicationMenuItem( + name: "MyProject.Crm.Orders", + displayName: l["Menu:Orders"], + url: "/crm/orders") + ) + ); + } + } +} +``` + +* This example adds items only to the main menu (`StandardMenus.Main`: see the *Standard Menus* section below). +* It gets a `IStringLocalizer` from `context` to [localize](../../Localization.md) the display names of the menu items. +* Adds the Customers and Orders as children of the CRM menu. + +Once you create a menu contributor, you need to add it to the `AbpNavigationOptions` in the `ConfigureServices` method of your module: + +````csharp +Configure(options => +{ + options.MenuContributors.Add(new MyProjectMenuContributor()); +}); +```` + +This example uses some localization keys as display names those should be defined in the localization file: + +````json +"Menu:CRM": "CRM", +"Menu:Orders": "Orders", +"Menu:Customers": "Customers" +```` + +See the [localization document](../../Localization.md) to learn more about the localization. + +When you run the application, you will see the menu items added to the main menu: + +![nav-main-menu](../../images/nav-main-menu.png) + +> The menu is rendered by the current UI theme. So, the look of the main menu can be completely different based on your theme. + +Here, a few notes on the menu contributors; + +* ABP Framework calls the `ConfigureMenuAsync` method **whenever need to render** the menu. +* Every menu item can have **children**. So, you can add menu items with **unlimited depth** (however, your UI theme may not support unlimited depth). +* Only leaf menu items have `url`s normally. When you click to a parent menu, its sub menu is opened or closed, you don't navigate the `url` of a parent menu item. +* If a menu item has no children and has no `url` defined, then it is not rendered on the UI. This simplifies to authorize the menu items: You only authorize the child items (see the next section). If none of the children are authorized, then the parent automatically disappears. + +### Menu Item Properties + +There are more options of a menu item (the constructor of the `ApplicationMenuItem` class). Here, the list of all available options; + +* `name` (`string`, required): The **unique name** of the menu item. +* `displayName` (`string`, required): Display name/text of the menu item. You can [localize](../../Localization.md) this as shown before. +* `url` (`string`): The URL of the menu item. +* `icon` (`string`): An icon name. Free [Font Awesome](https://fontawesome.com/) icon classes are supported out of the box. Example: `fa fa-book`. You can use any CSS font icon class as long as you include the necessary CSS files to your application. +* `order` (`int`): The order of the menu item. Default value is `1000`. Items are sorted by the adding order unless you specify an order value. +* `customData` (`object`): A custom object that you can associate to the menu item and use it while rendering the menu item. +* `target` (`string`): Target of the menu item. Can be `null` (default), "\_*blank*", "\_*self*", "\_*parent*", "\_*top*" or a frame name for web applications. +* `elementId` (`string`): Can be used to render the element with a specific HTML `id` attribute. +* `cssClass` (`string`): Additional string classes for the menu item. + +### Authorization + +As seen above, a menu contributor contributes to the menu dynamically. So, you can perform any custom logic or get menu items from any source. + +One use case is the [authorization](../../Authorization.md). You typically want to add menu items by checking a permission. + +**Example: Check if the current user has a permission** + +````csharp +if (await context.IsGrantedAsync("MyPermissionName")) +{ + //...add menu items +} +```` + +> You can use `context.AuthorizationService` to directly access to the `IAuthorizationService`. + +### Resolving Dependencies + +`context.ServiceProvider` can be used to resolve any service dependency. + +**Example: Get a service** + +````csharp +var myService = context.ServiceProvider.GetRequiredService(); +//...use the service +```` + +> You don't need to care about releasing/disposing services. ABP Framework handles it. + +### The Administration Menu + +There is a special menu item in the menu menu that is added by the ABP Framework: The *Administration* menu. It is typically used by the pre-built admin [application modules](../../Modules/Index.md): + +![nav-main-menu-administration](../../images/nav-main-menu-administration.png) + +If you want to add menu items under the *Administration* menu item, you can use the `context.Menu.GetAdministration()` extension method: + +````csharp +context.Menu.GetAdministration().AddItem(...) +```` + +### Manipulating the Existing Menu Items + +ABP Framework executes the menu contributors by the [module dependency order](../../Module-Development-Basics.md). So, you can manipulate the menu items that your application or module (directly or indirectly) depends on. + +**Example: Set an icon for the `Users` menu item added by the [Identity Module](../../Modules/Identity.md)** + +````csharp +var userMenu = context.Menu.FindMenuItem(IdentityMenuNames.Users); +userMenu.Icon = "fa fa-users"; +```` + +> `context.Menu` gives you ability to access to all the menu items those have been added by the previous menu contributors. + +## Standard Menus + +A menu is a **named** component. An application may contain more than one menus with different, unique names. There are two pre-defined standard menus: + +* `Main`: The main menu of the application. Contains links to the page of the application. Defined as a constant: `Volo.Abp.UI.Navigation.StandardMenus.Main`. +* `User`: User profile menu. Defined as a constant: `Volo.Abp.UI.Navigation.StandardMenus.User`. + +The `Main` menu already covered above. The `User` menu is available when a user has logged in: + +![user-menu](../../images/user-menu.png) + +You can add items to the `User` menu by checking the `context.Menu.Name` as shown below: + +```csharp +if (context.Menu.Name == StandardMenus.User) +{ + //...add items +} +``` + +## IMenuManager + +`IMenuManager` is generally used by the UI [theme](Theming.md) to render the menu items on the UI. So, **you generally don't need to directly use** the `IMenuManager`. + +**Example: Getting the `Main` menu items** + +```csharp +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Volo.Abp.UI.Navigation; + +namespace MyProject.Web.Pages +{ + public class IndexModel : PageModel + { + private readonly IMenuManager _menuManager; + + public IndexModel(IMenuManager menuManager) + { + _menuManager = menuManager; + } + + public async Task OnGetAsync() + { + var mainMenu = await _menuManager.GetAsync(StandardMenus.Main); + + foreach (var menuItem in mainMenu.Items) + { + //... + } + } + } +} +``` -TODO \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Overall.md b/docs/en/UI/AspNetCore/Overall.md new file mode 100644 index 0000000000..8cd9dd3f5e --- /dev/null +++ b/docs/en/UI/AspNetCore/Overall.md @@ -0,0 +1,159 @@ +# ASP.NET Core MVC / Razor Pages UI + +## Introduction + +ABP Framework provides a convenient and comfortable way of creating web applications using the ASP.NET Core MVC / Razor Pages as the User Interface framework. + +> ABP doesn't offer a new/custom way of UI development. You can continue to use your current skills to create the UI. However, it offers a lot of features to make your development easier and have a more maintainable code base. + +### MVC vs Razor Pages + +ASP.NET Core provides two models for UI development: + +* **[MVC (Model-View-Controller)](https://docs.microsoft.com/en-us/aspnet/core/mvc/)** is the classic way that exists from the version 1.0. This model can be used to create UI pages/components and HTTP APIs. +* **[Razor Pages](https://docs.microsoft.com/en-us/aspnet/core/razor-pages/)** was introduced with the ASP.NET Core 2.0 as a new way to create web pages. + +**ABP Framework supports both** of the MVC and the Razor Pages models. However, it is suggested to create the **UI pages with Razor Pages** approach and use the **MVC model to build HTTP APIs**. So, all the pre-build modules, samples and the documentation is based on the Razor Pages for the UI development, while you can always apply the MVC pattern to create your own pages. + +### Modularity + +[Modularity](../../Module-Development-Basics.md) is one of the key goals of the ABP Framework. It is not different for the UI; It is possible to develop modular applications and reusable application modules with isolated and reusable UI pages and components. + +The [application startup template](../../Startup-Templates/Application.md) comes with some application modules pre-installed. These modules have their own UI pages embedded into their own NuGet packages. You don't see their code in your solution, but they work as expected on runtime. + +## Theme System + +ABP Framework provides a complete [Theming](Theming.md) system with the following goals: + +* Reusable [application modules](../../Modules/Index.md) are developed **theme-independent**, so they can work with any UI theme. +* UI theme is **decided by the final application**. +* The theme is distributed via NuGet/NPM packages, so it is **easily upgradable**. +* The final application can **customize** the selected theme. + +### Current Themes + +Currently, two themes are **officially provided**: + +* The [Basic Theme](Basic-Theme.md) is the minimalist theme with the plain Bootstrap style. It is **open source and free**. +* The [Lepton Theme](https://commercial.abp.io/themes) is a **commercial** theme developed by the core ABP team and is a part of the [ABP Commercial](https://commercial.abp.io/) license. + +There are also some community-driven themes for the ABP Framework (you can search on the web). + +### Base Libraries + +There are a set of standard JavaScript/CSS libraries that comes pre-installed and supported by all the themes: + +- [Twitter Bootstrap](https://getbootstrap.com/) as the fundamental HTML/CSS framework. +- [JQuery](https://jquery.com/) for DOM manipulation. +- [DataTables.Net](https://datatables.net/) for data grids. +- [JQuery Validation](https://jqueryvalidation.org/) for client side & [unobtrusive](https://github.com/aspnet/jquery-validation-unobtrusive) validation +- [FontAwesome](https://fontawesome.com/) as the fundamental CSS font library. +- [SweetAlert](https://sweetalert.js.org/) to show fancy alert message and confirmation dialogs. +- [Toastr](https://github.com/CodeSeven/toastr) to show toast notifications. +- [Lodash](https://lodash.com/) as a utility library. +- [Luxon](https://moment.github.io/luxon/) for date/time operations. +- [JQuery Form](https://github.com/jquery-form/form) for AJAX forms. +- [bootstrap-datepicker](https://github.com/uxsolutions/bootstrap-datepicker) to show date pickers. +- [Select2](https://select2.org/) for better select/combo boxes. +- [Timeago](http://timeago.yarp.com/) to show automatically updating fuzzy timestamps. +- [malihu-custom-scrollbar-plugin](https://github.com/malihu/malihu-custom-scrollbar-plugin) for custom scrollbars. + +You can use these libraries directly in your applications, without needing to manually import your page. + +### Layouts + +The themes provide the standard layouts. So, you have responsive layouts with the standard features already implemented. The screenshot below has taken from the Application Layout of the [Basic Theme](Basic-Theme.md): + +![basic-theme-application-layout](../../images/basic-theme-application-layout.png) + +See the [Theming](Theming.md) document for more layout options and other details. + +### Layout Parts + +A typical layout consists of multiple parts. The [Theming](Theming.md) system provides [menus](Navigation-Menu.md), [toolbars](Toolbars.md), [layout hooks](Layout-Hooks.md) and more to dynamically control the layout by your application and the modules you are using. + +## Features + +This section highlights some of the features provided by the ABP Framework for the ASP.NET Core MVC / Razor Pages UI. + +### Dynamic JavaScript API Client Proxies + +Dynamic JavaScript API Client Proxy system allows you to consume your server side HTTP APIs from your JavaScript client code, just like calling local functions. + +**Example: Get a list of authors from the server** + +````js +acme.bookStore.authors.author.getList({ + maxResultCount: 10 +}).then(function(result){ + console.log(result.items); +}); +```` + +`acme.bookStore.authors.author.getList` is an auto-generated function that internally makes an AJAX call to the server. + +See the [Dynamic JavaScript API Client Proxies](Dynamic-JavaScript-Proxies.md) document for more. + +### Bootstrap Tag Helpers + +ABP makes it easier & type safe to write Bootstrap HTML. + +**Example: Render a Bootstrap modal** + +````html + + + + Woohoo, you're reading this text in a modal! + + + +```` + +See the [Tag Helpers](Tag-Helpers/Index.md) document for more. + +### Forms & Validation + +ABP provides `abp-dynamic-form` and `abp-input` tag helpers to dramatically simplify to create a fully functional form that automates localization, validation and AJAX submission. + +**Example: Use `abp-dynamic-form` to create a complete form based on a model** + +````html + +```` + +See the [Forms & Validation](Forms-Validation.md) document for details. + +### Bundling & Minification / Client Side Libraries + +ABP provides a flexible and modular Bundling & Minification system to create bundles and minify style/script files on runtime. + +````html + + + + + + +```` + +Also, Client Side Package Management system offers a modular and consistent way of managing 3rd-party library dependencies. + +See the [Bundling & Minification](Bundling-Minification.md) and [Client Side Package Management](Client-Side-Package-Management.md) documents. + +### JavaScript APIs + +[JavaScript APIs](JavaScript-API/Index.md) provides a strong abstractions to the server side localization, settings, permissions, features... etc. They also provide a simple way to show messages and **notifications** to the user. + +### Modals, Alerts, Widgets and More + +ABP Framework provides a lot of built-in solutions to common application requirements; + +* [Widget System](Widgets.md) can be used to create reusable widgets & create dashboards. +* [Page Alerts](Page-Alerts.md) makes it easy to show alerts to the user. +* [Modal Manager](Modals.md) provides a simple way to build and use modals. +* [Data Tables](Data-Tables.md) integration makes straightforward to create data grids. + +## Customization + +There are a lot of ways to customize the theme and the UIs of the pre-built modules. You can override components, pages, static resources, bundles and more. See the [User Interface Customization Guide](Customization-User-Interface.md). diff --git a/docs/en/UI/AspNetCore/Page-Alerts.md b/docs/en/UI/AspNetCore/Page-Alerts.md new file mode 100644 index 0000000000..cbf6eb493d --- /dev/null +++ b/docs/en/UI/AspNetCore/Page-Alerts.md @@ -0,0 +1,84 @@ +# ASP.NET Core MVC / Razor Pages: Page Alerts + +It is common to show error, warning or information alerts to inform the user. An example *Service Interruption* alert is shown below: + +![page-alert-example](../../images/page-alert-example.png) + +## Basic Usage + +If you directly or indirectly inherit from `AbpPageModel`, you can use the `Alerts` property to add alerts to be rendered after the request completes. + +**Example: Show a Warning alert** + +```csharp +namespace MyProject.Web.Pages +{ + public class IndexModel : MyProjectPageModel //or inherit from AbpPageModel + { + public void OnGet() + { + Alerts.Warning( + text: "We will have a service interruption between 02:00 AM and 04:00 AM at October 23, 2023!", + title: "Service Interruption" + ); + } + } +} +``` + +This usage renders an alert that was shown above. If you need to localize the messages, you can always use the standard [localization](../../Localization.md) system. + +### Exceptions / Invalid Model States + +It is typical to show alerts when you manually handle exceptions (with try/catch statements) or want to handle `!ModelState.IsValid` case and warn the user. For example, the Account Module shows a warning if user enters an incorrect username or password: + +![page-alert-account-layout](../../images/page-alert-account-layout.png) + +> Note that you generally don't need to manually handle exceptions since ABP Framework provides an automatic [exception handling](../../Exception-Handling.md) system. + +### Alert Types + +`Warning` is used to show a warning alert. Other common methods are `Info`, `Danger` and `Success`. + +Beside the standard methods, you can use the `Alerts.Add` method by passing an `AlertType` `enum` with one of these values: `Default`, `Primary`, `Secondary`, `Success`, `Danger`, `Warning`, `Info`, `Light`, `Dark`. + +### Dismissible + +All alert methods gets an optional `dismissible` parameter. Default value is `true` which makes the alert box dismissible. Set it to `false` to create a sticky alert box. + +## IAlertManager + +If you need to add alert messages from another part of your code, you can inject the `IAlertManager` service and use its `Alerts` list. + +**Example: Inject the `IAlertManager`** + +```csharp +using Volo.Abp.AspNetCore.Mvc.UI.Alerts; +using Volo.Abp.DependencyInjection; + +namespace MyProject.Web.Pages +{ + public class MyService : ITransientDependency + { + private readonly IAlertManager _alertManager; + + public MyService(IAlertManager alertManager) + { + _alertManager = alertManager; + } + + public void Test() + { + _alertManager.Alerts.Add(AlertType.Danger, "Test message!"); + } + } +} +``` + +## Notes + +### AJAX Requests + +Page Alert system was designed to be used in a regular full page request. It is not for AJAX/partial requests. The alerts are rendered in the page layout, so a full page refresh is needed. + +For AJAX requests, it is more proper to throw exceptions (e.g. `UserFriendlyException`). See the [exception handling](../../Exception-Handling.md) document. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Page-Header.md b/docs/en/UI/AspNetCore/Page-Header.md new file mode 100644 index 0000000000..f6ec3074de --- /dev/null +++ b/docs/en/UI/AspNetCore/Page-Header.md @@ -0,0 +1,58 @@ +# ASP.NET Core MVC / Razor Pages: Page Header + +`IPageLayout` service can be used to set the page title, selected menu item and the breadcrumb items for a page. It's the [theme](Theming.md)'s responsibility to render these on the page. + +## IPageLayout + +`IPageLayout` can be injected in any page/view to set the page header properties. + +### Page Title + +Page Title can be set as shown in the example below: + +````csharp +@inject IPageLayout PageLayout +@{ + PageLayout.Content.Title = "Book List"; +} +```` + +* The Page Title is set to the HTML `title` tag (in addition to the [brand/application name](Branding.md)). +* The theme may render the Page Title before the Page Content (not implemented by the Basic Theme). + +### Breadcrumb + +> **The [Basic Theme](Basic-Theme.md) currently doesn't implement the breadcrumbs.** + +Breadcrumb items can be added to the `PageLayout.Content.BreadCrumb`. + +**Example: Add Language Management to the breadcrumb items.** + +```` +PageLayout.Content.BreadCrumb.Add("Language Management"); +```` + +The theme then renders the breadcrumb. An example render result can be: + +![breadcrumbs-example](../../images/breadcrumbs-example.png) + +* The Home icon is rendered by default. Set `PageLayout.Content.BreadCrumb.ShowHome` to `false` to hide it. +* Current Page name (got from the `PageLayout.Content.Title`) is added as the last by default. Set `PageLayout.Content.BreadCrumb.ShowCurrent` to `false` to hide it. + +Any item that you add is inserted between Home and Current Page items. You can add as many item as you need. `BreadCrumb.Add(...)` method gets three parameters: + +* `text`: The text to show for the breadcrumb item. +* `url` (optional): A URL to navigate to, if the user clicks to the breadcrumb item. +* `icon` (optional): An icon class (like `fas fa-user-tie` for Font-Awesome) to show with the `text`. + +### The Selected Menu Item + +> **The [Basic Theme](Basic-Theme.md) currently doesn't implement the selected menu item since it is not applicable to the top menu which is the only option for the Basic Theme for now.** + +You can set the Menu Item name related to this page: + +````csharp +PageLayout.Content.MenuItemName = "BookStore.Books"; +```` + +Menu item name should match a unique menu item name defined using the [Navigation / Menu](Navigation-Menu.md) system. In this case, it is expected from the theme to make the menu item "active" in the main menu. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Badges.md b/docs/en/UI/AspNetCore/Tag-Helpers/Badges.md index 66727cc112..c627273062 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Badges.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Badges.md @@ -2,11 +2,11 @@ ## Introduction -`abp-badge` and `abp-badge-pill` are abp tags for badges. +`abp-badge` and `abp-badge-pill` are ABP Tag Helper attributes for `a` and `span` html tags. Basic usage: -````csharp +````html Primary Info Danger @@ -22,8 +22,7 @@ See the [badges demo page](https://bootstrap-taghelpers.abp.io/Components/Badges * Indicates the type of the badge. Should be one of the following values: - * `_` (default value) - * `Default` (default value) + * `Default` * `Primary` * `Secondary` * `Success` @@ -35,6 +34,7 @@ See the [badges demo page](https://bootstrap-taghelpers.abp.io/Components/Badges Example: -````csharp +````html Danger ```` + diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Blockquote.md b/docs/en/UI/AspNetCore/Tag-Helpers/Blockquote.md new file mode 100644 index 0000000000..a63187aeb3 --- /dev/null +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Blockquote.md @@ -0,0 +1,18 @@ +# Blockquote + +`abp-blockquote` is the main container for blockquote items. + +Basic usages: + +````html + +

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

+
+ + +

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

+
Someone famous in Source Title
+
+```` + +It adds `blockquote` class to main container, also adds `blockquote-footer` class to inner `footer` element and `mb-0` class to inner `p` element. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Borders.md b/docs/en/UI/AspNetCore/Tag-Helpers/Borders.md index 1dc070e8ad..e1d98ac7d8 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Borders.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Borders.md @@ -2,11 +2,11 @@ ## Introduction -`abp-border` is a main element for border styling. +`abp-border` is ABP Tag Helper attribute for border styling. Basic usage: -````csharp +````html @@ -124,3 +124,5 @@ A value indicates type, position and the color of the border. Should be one of t * `Bottom_Light_0` * `Bottom_Dark_0` * `Bottom_White_0` + +(Values with `_0` at the end is for [Subtractive](https://getbootstrap.com/docs/4.0/utilities/borders/#subtractive) usages) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Breadcrumbs.md b/docs/en/UI/AspNetCore/Tag-Helpers/Breadcrumbs.md index 59332cf8de..b7082696c5 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Breadcrumbs.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Breadcrumbs.md @@ -6,7 +6,7 @@ Basic usage: -````csharp +````html diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Button-groups.md b/docs/en/UI/AspNetCore/Tag-Helpers/Button-groups.md index 93865e0d74..bfd558f89e 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Button-groups.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Button-groups.md @@ -6,7 +6,7 @@ Basic usage: -````csharp +````html Left Middle diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Carousel.md b/docs/en/UI/AspNetCore/Tag-Helpers/Carousel.md index 6088977068..3b91087838 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Carousel.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Carousel.md @@ -6,7 +6,7 @@ Basic usage: -````csharp +````html diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Collapse.md b/docs/en/UI/AspNetCore/Tag-Helpers/Collapse.md index 38fab4d44b..dfbe8ea248 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Collapse.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Collapse.md @@ -6,7 +6,7 @@ Basic usage: -````xml +````html Link with href diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Figure.md b/docs/en/UI/AspNetCore/Tag-Helpers/Figure.md new file mode 100644 index 0000000000..e3b0e0d0a4 --- /dev/null +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Figure.md @@ -0,0 +1,14 @@ +# Figures + +`abp-figure` is the main container for bootstrap figure items. + +Basic usage: + +````html + + + A caption for the above image. + +```` + +It adds `figure` class to main container, also adds `figure-img` class to inner `abp-image` element and `figure-caption` class to inner `abp-figcaption` element. \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Index.md b/docs/en/UI/AspNetCore/Tag-Helpers/Index.md index 229460de92..5b16d9ccdc 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Index.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Index.md @@ -13,19 +13,26 @@ ABP Framework also adds some **useful features** to the standard bootstrap compo Here, the list of components those are wrapped by the ABP Framework: * [Alerts](Alerts.md) +* [Badges](Badges.md) +* [Blockquote](Blockquote.md) +* [Borders](Borders.md) +* [Breadcrumb](Breadcrumbs.md) * [Buttons](Buttons.md) * [Cards](Cards.md) +* [Carousel](Carousel.md) * [Collapse](Collapse.md) * [Dropdowns](Dropdowns.md) +* [Figures](Figure.md) * [Grids](Grids.md) * [List Groups](List-Groups.md) * [Modals](Modals.md) +* [Navigation](Navs.md) * [Paginator](Paginator.md) * [Popovers](Popovers.md) * [Progress Bars](Progress-Bars.md) +* [Tables](Tables.md) * [Tabs](Tabs.md) * [Tooltips](Tooltips.md) -* ... > Until all the tag helpers are documented, you can visit https://bootstrap-taghelpers.abp.io/ to see them with live samples. @@ -35,4 +42,4 @@ Here, the list of components those are wrapped by the ABP Framework: ## Dynamic Forms -**Abp Tag helpers** offer an easy way to build complete **Bootstrap forms**. See [Dynamic Forms documentation](Dynamic-Forms.md). \ No newline at end of file +**Abp Tag helpers** offer an easy way to build complete **Bootstrap forms**. See [Dynamic Forms documentation](Dynamic-Forms.md). diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Modals.md b/docs/en/UI/AspNetCore/Tag-Helpers/Modals.md index 9cf1258373..c811dee0bc 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Modals.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Modals.md @@ -1,5 +1,7 @@ # Modals +> This document explains the details of the `abp-modal` Tag Helper, which simplifies to build the HTML markup for a modal dialog. Read [that documentation](../Modals.md) to learn how to work with modals. + ## Introduction `abp-modal` is a main element to create a modal. @@ -18,8 +20,6 @@ Basic usage: ```` - - ## Demo See the [modals demo page](https://bootstrap-taghelpers.abp.io/Components/Modals) to see it in action. diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Navs.md b/docs/en/UI/AspNetCore/Tag-Helpers/Navs.md index c7503fa51d..9c8347b831 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Navs.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Navs.md @@ -6,7 +6,7 @@ Basic usage: -````csharp +````html Active @@ -78,7 +78,7 @@ See the [navs demo page](https://bootstrap-taghelpers.abp.io/Components/Navs) to Example: -````csharp +````html Navbar diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Paginator.md b/docs/en/UI/AspNetCore/Tag-Helpers/Paginator.md index 9969bcf3cc..c30e68eed9 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Paginator.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Paginator.md @@ -12,7 +12,7 @@ Basic usage: Model: -````xml +````csharp using Microsoft.AspNetCore.Mvc.RazorPages; using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Pagination; diff --git a/docs/en/UI/AspNetCore/Tag-Helpers/Tables.md b/docs/en/UI/AspNetCore/Tag-Helpers/Tables.md index 50e6c3baf9..db30db6a09 100644 --- a/docs/en/UI/AspNetCore/Tag-Helpers/Tables.md +++ b/docs/en/UI/AspNetCore/Tag-Helpers/Tables.md @@ -6,7 +6,7 @@ Basic usage: -````csharp +````html diff --git a/docs/en/UI/AspNetCore/Testing.md b/docs/en/UI/AspNetCore/Testing.md new file mode 100644 index 0000000000..2c880594d3 --- /dev/null +++ b/docs/en/UI/AspNetCore/Testing.md @@ -0,0 +1,220 @@ +# ASP.NET Core MVC / Razor Pages: Testing + +> You can follow the [ASP.NET Core Integration Tests documentation](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests) to learn details of ASP.NET Core integration tests. This document explains the additional test infrastructure provided by the ABP Framework. + +## The Application Startup Template + +The Application Startup Template contains the `.Web` project that contains UI views/pages/components of the application and a `.Web.Tests` project to test these. + +![aspnetcore-web-tests-in-solution](../../images/aspnetcore-web-tests-in-solution.png) + +## Testing the Razor Pages + +Assume that you've created a Razor Page, named `Issues.cshtml` with the following contents; + +**Issues.cshtml.cs** + +````csharp +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.RazorPages; +using MyProject.Issues; + +namespace MyProject.Web.Pages +{ + public class IssuesModel : PageModel + { + public List Issues { get; set; } + + private readonly IIssueAppService _issueAppService; + + public IssuesModel(IIssueAppService issueAppService) + { + _issueAppService = issueAppService; + } + + public async Task OnGetAsync() + { + Issues = await _issueAppService.GetListAsync(); + } + } +} +```` + +**Issues.cshtml** + +````html +@page +@model MyProject.Web.Pages.IssuesModel +

Issue List

+ + + + + + + + + @foreach (var issue in Model.Issues) + { + + + + + } + +
IssueClosed?
@issue.Title + @if (issue.IsClosed) + { + Closed + } + else + { + Open + } +
+```` + +This page simply creates a table with the issues: + +![issue-list](../../images/issue-list.png) + +You can write a test class inside the `.Web.Tests` project just like the example below: + +````csharp +using System.Threading.Tasks; +using HtmlAgilityPack; +using Shouldly; +using Xunit; + +namespace MyProject.Pages +{ + public class Issues_Tests : MyProjectWebTestBase + { + [Fact] + public async Task Should_Get_Table_Of_Issues() + { + // Act + + var response = await GetResponseAsStringAsync("/Issues"); + + //Assert + + var htmlDocument = new HtmlDocument(); + htmlDocument.LoadHtml(response); + + var tableElement = htmlDocument.GetElementbyId("IssueTable"); + tableElement.ShouldNotBeNull(); + + var trNodes = tableElement.SelectNodes("//tbody/tr"); + trNodes.Count.ShouldBeGreaterThan(0); + } + } +} +```` + +`GetResponseAsStringAsync` is a shortcut method that comes from the base class that performs a HTTP GET request, checks if the resulting HTTP Status is `200` and returns the response as a `string`. + +> You can use the base `Client` object (of type `HttpClient`) to perform any kind of request to the server and read the response yourself. `GetResponseAsStringAsync` is just a shortcut method. + +This example uses the [HtmlAgilityPack](https://html-agility-pack.net/) library to parse the incoming HTML and test if it contains the issue table. + +> This example assumes there are some initial issues in the database. See the *The Data Seed* section of the [Testing document](../../Testing.md) to learn how to seed test data, so your tests can assume some initial data available in the database. + +## Testing the Controllers + +Testing a controller is not different. Just perform a request to the server with a proper URL, get the response and make your assertions. + +### View Result + +If the controller returns a View, you can use a similar code to test the returned HTML. See the Razor Pages example above. + +### Object Result + +If the controller returns an object result, you can use the `GetResponseAsObjectAsync` base method. + +Assume that you've a controller as defined below: + +````csharp +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using MyProject.Issues; +using Volo.Abp.AspNetCore.Mvc; + +namespace MyProject.Web.Controllers +{ + [Route("api/issues")] + public class IssueController : AbpController + { + private readonly IIssueAppService _issueAppService; + + public IssueController(IIssueAppService issueAppService) + { + _issueAppService = issueAppService; + } + + [HttpGet] + public async Task> GetAsync() + { + return await _issueAppService.GetListAsync(); + } + } +} +```` + +You can write a test code to execute the API and get the result: + +````csharp +using System.Collections.Generic; +using System.Threading.Tasks; +using MyProject.Issues; +using Shouldly; +using Xunit; + +namespace MyProject.Pages +{ + public class Issues_Tests : MyProjectWebTestBase + { + [Fact] + public async Task Should_Get_Issues_From_Api() + { + var issues = await GetResponseAsObjectAsync>("/api/issues"); + + issues.ShouldNotBeNull(); + issues.Count.ShouldBeGreaterThan(0); + } + } +} +```` + +## Testing the JavaScript Code + +ABP Framework doesn't provide any infrastructure to test your JavaScript code. You can use any test framework and tooling to test your JavaScript code. + +## The Test Infrastructure + +[Volo.Abp.AspNetCore.TestBase](https://www.nuget.org/packages/Volo.Abp.AspNetCore.TestBase) package provides the test infrastructure that is integrated to the ABP Framework and ASP.NET Core. + +> Volo.Abp.AspNetCore.TestBase package is already installed in the `.Web.Tests` project. + +This package provides the `AbpAspNetCoreIntegratedTestBase` as the fundamental base class to derive the test classes from. The `MyProjectWebTestBase` base class used above inherits from the `AbpAspNetCoreIntegratedTestBase`, so we indirectly inherited the `AbpAspNetCoreIntegratedTestBase`. + +### Base Properties + +The `AbpAspNetCoreIntegratedTestBase` provides the following base properties those are used in the tests: + +* `Server`: A `TestServer` instance that hosts the web application in tests. +* `Client`: An `HttpClient` instance that is configured to perform requests to the test server. +* `ServiceProvider`: The service provider that you can resolve services in case of need. + +### Base Methods + +`AbpAspNetCoreIntegratedTestBase` provides the following methods that you can override if you need to customize the test server: + +* `ConfigureServices` can be overridden to register/replace services only for the derived test class. +* `CreateHostBuilder` can be used to customize building the `IHostBuilder`. + +See Also + +* [Overall / Server Side Testing](../../Testing.md) \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Theming.md b/docs/en/UI/AspNetCore/Theming.md index e41545635c..8c680973b8 100644 --- a/docs/en/UI/AspNetCore/Theming.md +++ b/docs/en/UI/AspNetCore/Theming.md @@ -1,3 +1,436 @@ -# ASP.NET Core MVC / Razor Pages Theming +# ASP.NET Core MVC / Razor Pages: UI Theming + +## Introduction + +ABP Framework provides a complete **UI Theming** system with the following goals: + +* Reusable [application modules](../../Modules/Index.md) are developed **theme-independent**, so they can work with any UI theme. +* UI theme is **decided by the final application**. +* The theme is distributed via NuGet/NPM packages, so it is **easily upgradable**. +* The final application can **customize** the selected theme. + +In order to accomplish these goals, ABP Framework; + +* Determines a set of **base libraries** used and adapted by all the themes. So, module and application developers can depend on and use these libraries without depending on a particular theme. +* Provides a system that consists of [navigation menus](Navigation-Menu.md), [toolbars](Toolbars.md), [layout hooks](Layout-Hooks.md)... that is implemented by all the themes. So, the modules and the application to contribute to the layout to compose a consistent application UI. + +### Current Themes + +Currently, two themes are **officially provided**: + +* The [Basic Theme](Basic-Theme.md) is the minimalist theme with the plain Bootstrap style. It is **open source and free**. +* The [Lepton Theme](https://commercial.abp.io/themes) is a **commercial** theme developed by the core ABP team and is a part of the [ABP Commercial](https://commercial.abp.io/) license. + +There are also some community-driven themes for the ABP Framework (you can search on the web). + +## Overall + +### The Base Libraries + +All the themes must depend on the [@abp/aspnetcore.mvc.ui.theme.shared](https://www.npmjs.com/package/@abp/aspnetcore.mvc.ui.theme.shared) NPM package, so they are indirectly depending on the following libraries: + +* [Twitter Bootstrap](https://getbootstrap.com/) as the fundamental HTML/CSS framework. +* [JQuery](https://jquery.com/) for DOM manipulation. +* [DataTables.Net](https://datatables.net/) for data grids. +* [JQuery Validation](https://jqueryvalidation.org/) for client side & [unobtrusive](https://github.com/aspnet/jquery-validation-unobtrusive) validation +* [FontAwesome](https://fontawesome.com/) as the fundamental CSS font library. +* [SweetAlert](https://sweetalert.js.org/) to show fancy alert message and confirmation dialogs. +* [Toastr](https://github.com/CodeSeven/toastr) to show toast notifications. +* [Lodesh](https://lodash.com/) as a utility library. +* [Luxon](https://moment.github.io/luxon/) for date/time operations. +* [JQuery Form](https://github.com/jquery-form/form) for AJAX forms. +* [bootstrap-datepicker](https://github.com/uxsolutions/bootstrap-datepicker) to show date pickers. +* [Select2](https://select2.org/) for better select/combo boxes. +* [Timeago](http://timeago.yarp.com/) to show automatically updating fuzzy timestamps. +* [malihu-custom-scrollbar-plugin](https://github.com/malihu/malihu-custom-scrollbar-plugin) for custom scrollbars. + +These libraries are selected as the base libraries and available to the applications and modules. + +#### Abstractions / Wrappers + +There are some abstractions in the ABP Framework to make your code independent from some of these libraries too. Examples; + +* [Tag Helpers](Tag-Helpers/Index.md) makes it easy to generate the Bootstrap UIs. +* JavaScript [Message](JavaScript-API/Message.md) and [Notification](JavaScript-API/Notify.md) APIs provides abstractions to use the Sweetalert and Toastr. +* [Forms & Validation](Forms-Validation.md) system automatically handles the validation, so you mostly don't directly type any validation code. + +### The Standard Layouts + +The main responsibility of a theme is to provide the layouts. There are **three pre-defined layouts must be implemented by all the themes**: + +* **Application**: The default layout which is used by the main application pages. +* **Account**: Mostly used by the [account module](../../Modules/Account.md) for login, register, forgot password... pages. +* **Empty**: The Minimal layout that has no layout components at all. + +Layout names are constants defined in the `Volo.Abp.AspNetCore.Mvc.UI.Theming.StandardLayouts` class. + +#### The Application Layout + +This is the default layout which is used by the main application pages. The following image shows the user management page in the [Basic Theme](Basic-Theme.md) application layout: + +![basic-theme-application-layout](../../images/basic-theme-application-layout.png) + +And the same page is shown below with the [Lepton Theme](https://commercial.abp.io/themes) application layout: + +![lepton-theme-application-layout](../../images/lepton-theme-application-layout.png) + +As you can see, the page is the same, but the look is completely different in the themes above. + +The application layout typically includes the following parts; + +* A [main menu](Navigation-Menu.md) +* Main [Toolbar](Toolbars.md) with the following components; + * User menu + * Language switch dropdown +* [Page alerts](Page-Alerts.md) +* The page content (aka `RenderBody()`) +* [Layout hooks](Layout-Hooks.md) + +Some themes may provide more parts like breadcrumbs, page header & toolbar... etc. See the *Layout Parts* section. + +#### The Account Layout + +The Account layout is typically used by the [account module](../../Modules/Account.md) for login, register, forgot password... pages. + +![basic-theme-account-layout](../../images/basic-theme-account-layout.png) + +This layout typically provides the following parts; + +* Language switch dropdown +* Tenant switch area (if the application is [multi-tenant](../../Multi-Tenancy.md) and the current is resolved by the cookie) +* [Page alerts](Page-Alerts.md) +* The page content (aka `RenderBody()`) +* [Layout hooks](Layout-Hooks.md) + +The [Basic Theme](Basic-Theme.md) renders the top navigation bar for this layout too (as shown above) + +Here, the account layout of the Lepton Theme: + +![lepton-theme-account-layout](../../images/lepton-theme-account-layout.png) + +The [Lepton Theme](https://commercial.abp.io/themes) shows the application logo and footer in this layout. + +> You can override theme layouts completely or partially in an application to [customize](Customization-User-Interface.md) it. + +#### The Empty Layout + +The empty layout provides an empty page. It typically includes the following parts; + +* [Page alerts](Page-Alerts.md) +* The page content (aka `RenderBody()`) +* [Layout hooks](Layout-Hooks.md) + +## Implementing a Theme + +### The Easy Way + +The easiest way to create a new theme is to copy the [Basic Theme Source Code](https://github.com/abpframework/abp/tree/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic) and customize it. Once you get a copy of the theme in your solution, remove the `Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic` NuGet package and reference to the local project. + +### The ITheme Interface + +`ITheme` interface is used by the ABP Framework to select the layout for the current page. A theme must implement this interface to provide the requested layout path. + +This is the `ITheme` implementation of the [Basic Theme](Basic-Theme.md). + +````csharp +using Volo.Abp.AspNetCore.Mvc.UI.Theming; +using Volo.Abp.DependencyInjection; + +namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic +{ + [ThemeName(Name)] + public class BasicTheme : ITheme, ITransientDependency + { + public const string Name = "Basic"; + + public virtual string GetLayout(string name, bool fallbackToDefault = true) + { + switch (name) + { + case StandardLayouts.Application: + return "~/Themes/Basic/Layouts/Application.cshtml"; + case StandardLayouts.Account: + return "~/Themes/Basic/Layouts/Account.cshtml"; + case StandardLayouts.Empty: + return "~/Themes/Basic/Layouts/Empty.cshtml"; + default: + return fallbackToDefault + ? "~/Themes/Basic/Layouts/Application.cshtml" + : null; + } + } + } +} +```` + +* `[ThemeName]` attribute is required and a theme must have a unique name, `Basic` in this sample. +* `GetLayout` method should return a path if the requested layout (`name`) is provided by the theme. *The Standard Layouts* should be implemented if the theme is aimed to be used by a standard application. It may implement additional layouts. + +Once the theme implements the `ITheme` interface, it should add the theme to the `AbpThemingOptions` in the `ConfigureServices` method of the [module](../../Module-Development-Basics.md). + +````csharp +Configure(options => +{ + options.Themes.Add(); +}); +```` + +#### The IThemeSelector Service + +ABP Framework allows to use multiple themes together. This is why `options.Themes` is a list. `IThemeSelector` service selects the theme on the runtime. The application developer can set the `AbpThemingOptions.DefaultThemeName` to set the theme to be used, or replace the `IThemeSelector` service implementation (the default implementation is `DefaultThemeSelector`) to completely control the theme selection on runtime. + +### Bundles + +[Bundling system](Bundling-Minification.md) provides a standard way to import style & script files into pages. There are two standard bundles defined by the ABP Framework: + +* `StandardBundles.Styles.Global`: The global bundle that includes the style files used in all the pages. Typically, it includes the CSS files of the Base Libraries. +* `StandardBundles.Scripts.Global`: The global bundle that includes the script files used in all the pages. Typically, it includes the JavaScript files of the Base Libraries. + +A theme generally extends these standard bundles by adding theme specific CSS/JavaScript files. + +The best way to define new bundles, inherit from the standard bundles and add to the `AbpBundlingOptions` as shown below (this code is from the [Basic Theme](Basic-Theme.md)): + +````csharp +Configure(options => +{ + options + .StyleBundles + .Add(BasicThemeBundles.Styles.Global, bundle => + { + bundle + .AddBaseBundles(StandardBundles.Styles.Global) + .AddContributors(typeof(BasicThemeGlobalStyleContributor)); + }); + + options + .ScriptBundles + .Add(BasicThemeBundles.Scripts.Global, bundle => + { + bundle + .AddBaseBundles(StandardBundles.Scripts.Global) + .AddContributors(typeof(BasicThemeGlobalScriptContributor)); + }); +}); +```` + +`BasicThemeGlobalStyleContributor` and `BasicThemeGlobalScriptContributor` are bundle contributors. For example, `BasicThemeGlobalStyleContributor` is defined as shown below: + +```csharp +public class BasicThemeGlobalStyleContributor : BundleContributor +{ + public override void ConfigureBundle(BundleConfigurationContext context) + { + context.Files.Add("/themes/basic/layout.css"); + } +} +``` + +Then the theme can render these bundles in a layout. For example, you can render the Global Styles as shown below: + +````html + +```` + +See the [Bundle & Minification](Bundling-Minification.md) document to understand the Bundling system better. + +### Layout Parts + +A typical Layout consists of several parts. The theme should include the necessary parts in each layout. + +**Example: The Basic Theme has the following parts for the Application Layout** + +![basic-theme-application-layout-parts](../../images/basic-theme-application-layout-parts.png) + +The application code and the modules can only show contents in the Page Content part. If they need to change the other parts (to add a menu item, to add a toolbar item, to change the application name in the branding area...) they should use the ABP Framework APIs. + +The following sections explain the fundamental parts pre-defined by the ABP Framework and can be implemented by the themes. + +> It is a good practice to split the layout into components/partials, so the final application can override them partially for customization purpose. + +#### Branding + +`IBrandingProvider` service should be used to get the name and the logo URL of the application to render in the Branding part. + +The [Application Startup Template](../../Startup-Templates/Application.md) has an implementation of this interface to set the values by the application developer. + +#### Main Menu + +`IMenuManager` service is used to get the main menu items and render on the layout. + +**Example: Get the Main Menu to render in a view component** + +```csharp +public class MainNavbarMenuViewComponent : AbpViewComponent +{ + private readonly IMenuManager _menuManager; + + public MainNavbarMenuViewComponent(IMenuManager menuManager) + { + _menuManager = menuManager; + } + + public async Task InvokeAsync() + { + var menu = await _menuManager.GetAsync(StandardMenus.Main); + return View("~/Themes/Basic/Components/Menu/Default.cshtml", menu); + } +} +``` + +See the [Navigation / Menus](Navigation-Menu.md) document to learn more about the navigation system. + +#### Main Toolbar + +`IToolbarManager` service is used to get the Main Toolbar items and render on the layout. Each item of this toolbar is a View Component, so it may include any type of UI elements. Inject the `IToolbarManager` and use the `GetAsync` to get the toolbar items: + +````csharp +var toolbar = await _toolbarManager.GetAsync(StandardToolbars.Main); +```` + +> See the [Toolbars](Toolbars.md) document to learn more on the toolbar system. + +The theme has a responsibility to add two pre-defined items to the main toolbar: Language Selection and User Menu. To do that, create a class implementing the `IToolbarContributor` interface and add it to the `AbpToolbarOptions` as shown below: + +```csharp +Configure(options => +{ + options.Contributors.Add(new BasicThemeMainTopToolbarContributor()); +}); +``` + +##### Language Selection + +Language Selection toolbar item is generally a dropdown that is used to switch between languages. `ILanguageProvider` is used to get the list of available languages and `CultureInfo.CurrentUICulture` is used to learn the current language. + +`/Abp/Languages/Switch` endpoint can be used to switch the language This endpoint accepts the following query string parameters: + +* `culture`: The selected culture, like `en-US` or `en`. +* `uiCulture`: The selected UI culture, like `en-US` or `en`. +* `returnUrl` (optional): Can be used to return a given URL after switching the language. + +`culture` and `uiCulture` should match one of the available languages. ABP Framework sets a culture cookie in the `/Abp/Languages/Switch` endpoint. + +##### User Menu + +User menu includes links related to the user account. `IMenuManager` is used just like the Main Menu, but this time with `StandardMenus.User` parameter like shown below: + +````csharp +var menu = await _menuManager.GetAsync(StandardMenus.User); +```` + +[ICurrentUser](../../CurrentUser.md) and [ICurrentTenant](../../Multi-Tenancy.md) services can be used to obtain the current user and tenant names. + +#### Page Alerts + +`IAlertManager` service is used to get the current page alerts to render on the layout. Use the `Alerts` list of the `IAlertManager`. It is generally rendered just before the page content (`RenderBody()`). + +See the [Page Alerts](Page-Alerts.md) document to learn more. + +#### Layout Hooks + +Since the Layout is in the theme package, the final application or any module can't directly manipulate the layout content. The [Layout Hook](Layout-Hooks.md) system allows to inject components to some specific points of the layout. + +The theme is responsible to render the hooks in the correct place. + +**Example: Render the `LayoutHooks.Head.First` Hook in the Application Layout** + +````html + + @await Component.InvokeLayoutHookAsync(LayoutHooks.Head.First, StandardLayouts.Application) + ... +```` + +See the [Layout Hook](Layout-Hooks.md) document to learn the standard layout hooks. + +#### Script / Style Sections + +Every layout should render the following optional sections: + +* `styles` section is rendered in the end of the `head`, just before the `LayoutHooks.Head.Last`. +* `scripts` section is rendered in the end of the `body`, just before the `LayoutHooks.Body.Last`. + +In this way, the page can import styles and scripts to the layout. + +**Example: Render the `styles` section** + +````csharp +@await RenderSectionAsync("styles", required: false) +```` + +#### Content Toolbar Section + +Another pre-defined section is the Content Toolbar section which can be used by the pages to add code just before the page content. The Basic Theme renders it as shown below: + +````html +
+
+ @RenderSection("content_toolbar", false) +
+
+```` + +The container div's id must be `AbpContentToolbar`. This section should come before the `RenderBody()`. + +#### Widget Resources + +The [Widget System](Widgets.md) allows to define reusable widgets with their own style/script files. All the layouts should render the widget style and scripts. + +**Widget Styles** is rendered as shown below, just before the `styles` section, after the global style bundle: + +````csharp +@await Component.InvokeAsync(typeof(WidgetStylesViewComponent)) +```` + +**Widget Scripts** is rendered as shown below, just before the `scripts` section, after the global script bundle: + +````csharp +@await Component.InvokeAsync(typeof(WidgetScriptsViewComponent)) +```` + +#### ABP Scripts + +ABP has some special scripts those should be included into every layout. They are not included in the global bundles since they are dynamically created based on the current user. + +ABP scripts (`ApplicationConfigurationScript` and `ServiceProxyScript`) should be added just after the global script bundle, as shown below: + +````html + + +```` + +#### Page Title, Selected Menu Item and Breadcrumbs + +`IPageLayout` service can be injected by any page to set the Page Title, the selected menu item name and the breadcrumb items. Then the theme can use this service to get these values and render on the UI. + +The Basic Theme doesn't implement this service, but the Lepton Theme implements: + +![breadcrumbs-example](../../images/breadcrumbs-example.png) + +See the [Page Header](Page-Header.md) document for more. + +#### Tenant Switch + +The Account Layout should allow the user to switch the current tenant if the application is multi-tenant and the tenant was resolved from the cookies. See the [Basic Theme Account Layout](https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Layouts/Account.cshtml) as an example implementation. + +### Layout Classes + +The Standard Layouts (`Application`, `Account` and `Empty`) should add the following CSS classes to the `body` tag: + +* `abp-application-layout` for the `Application` layout. +* `abp-account-layout` for the `Account` layout. +* `abp-empty-layout` for the `Empty` layout. + +In this way, applications or modules can have selectors based on the current layout. + +### RTL + +To support Right-To-Left languages, the Layout should check the current culture and add `dir="rtl"` to the `html` tag and `rtl` CSS class the the `body` tag. + +You can check `CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft` to understand if the current language is a RTL language. + +### The NPM Package + +A theme should have a NPM package that depends on the [@abp/aspnetcore.mvc.ui.theme.shared](https://www.npmjs.com/package/@abp/aspnetcore.mvc.ui.theme.shared) package. In this way, it inherits all the Base Libraries. If the theme requires additional libraries, then it should define these dependencies too. + +Applications use the [Client Side Package Management](Client-Side-Package-Management.md) system to add client side libraries to the project. So, if an application uses your theme, it should add dependency to your theme's NPM package as well as the NuGet package dependency. -TODO \ No newline at end of file diff --git a/docs/en/UI/AspNetCore/Toolbars.md b/docs/en/UI/AspNetCore/Toolbars.md index cc3bcd95be..3f1185f61b 100644 --- a/docs/en/UI/AspNetCore/Toolbars.md +++ b/docs/en/UI/AspNetCore/Toolbars.md @@ -1,3 +1,74 @@ -# Toolbars +# ASP.NET Core MVC / Razor Pages UI: Toolbars -TODO \ No newline at end of file +The Toolbar system is used to define **toolbars** on the user interface. Modules (or your application) can add **items** to a toolbar, then the [theme](Theming.md) renders the toolbar on the **layout**. + +There is only one **standard toolbar** named "Main" (defined as a constant: `StandardToolbars.Main`). The [Basic Theme](Basic-Theme) renders the main toolbar as shown below: + +![bookstore-toolbar-highlighted](../../images/bookstore-toolbar-highlighted.png) + +In the screenshot above, there are two items added to the main toolbar: Language switch component & user menu. You can add your own items here. + +## Example: Add a Notification Icon + +In this example, we will add a **notification (bell) icon** to the left of the language switch item. A item in the toolbar should be a **view component**. So, first, create a new view component in your project: + +![bookstore-notification-view-component](../../images/bookstore-notification-view-component.png) + +**NotificationViewComponent.cs** + +````csharp +public class NotificationViewComponent : AbpViewComponent +{ + public async Task InvokeAsync() + { + return View("/Pages/Shared/Components/Notification/Default.cshtml"); + } +} +```` + +**Default.cshtml** + +````xml +
+ +
+```` + +Now, we can create a class implementing the `IToolbarContributor` interface: + +````csharp +public class MyToolbarContributor : IToolbarContributor +{ + public Task ConfigureToolbarAsync(IToolbarConfigurationContext context) + { + if (context.Toolbar.Name == StandardToolbars.Main) + { + context.Toolbar.Items + .Insert(0, new ToolbarItem(typeof(NotificationViewComponent))); + } + + return Task.CompletedTask; + } +} +```` + +This class adds the `NotificationViewComponent` as the first item in the `Main` toolbar. + +Finally, you need to add this contributor to the `AbpToolbarOptions`, in the `ConfigureServices` of your [module](../../Module-Development-Basics.md): + +````csharp +Configure(options => +{ + options.Contributors.Add(new MyToolbarContributor()); +}); +```` + +That's all, you will see the notification icon on the toolbar when you run the application: + +![bookstore-notification-icon-on-toolbar](../../images/bookstore-notification-icon-on-toolbar.png) + +`NotificationViewComponent` in this sample simply returns a view without any data. In real life, you probably want to **query database** (or call an HTTP API) to get notifications and pass to the view. If you need, you can add a `JavaScript` or `CSS` file to the global [bundle](Bundling-Minification.md) for your toolbar item. + +## IToolbarManager + +`IToolbarManager` is used to render the toolbar. It returns the toolbar items by a toolbar name. This is generally used by the [themes](Theming.md) to render the toolbar on the layout. \ No newline at end of file diff --git a/docs/en/UI/Blazor/Authentication.md b/docs/en/UI/Blazor/Authentication.md new file mode 100644 index 0000000000..6c1cdb31f5 --- /dev/null +++ b/docs/en/UI/Blazor/Authentication.md @@ -0,0 +1,3 @@ +# Blazor UI: Authentication + +TODO \ No newline at end of file diff --git a/docs/en/UI/Blazor/Basic-Theme.md b/docs/en/UI/Blazor/Basic-Theme.md new file mode 100644 index 0000000000..926d15cf11 --- /dev/null +++ b/docs/en/UI/Blazor/Basic-Theme.md @@ -0,0 +1,57 @@ +# Blazor UI: Basic Theme + +The Basic Theme is a theme implementation for the Blazor UI. It is a minimalist theme that doesn't add any styling on top of the plain [Bootstrap](https://getbootstrap.com/). You can take the Basic Theme as the **base theme** and build your own theme or styling on top of it. See the *Customization* section. + +> If you are looking for a professional, enterprise ready theme, you can check the [Lepton Theme](https://commercial.abp.io/themes), which is a part of the [ABP Commercial](https://commercial.abp.io/). + +> See the [Theming document](Theming.md) to learn about themes. + +## Installation + +**This theme is already installed** when you create a new solution using the [startup templates](../../Startup-Templates/Index.md). If you need to manually install it, follow the steps below: + +* Install the [Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme) NuGet package to your web project. +* Add `AbpAspNetCoreComponentsWebAssemblyBasicThemeModule` into the `[DependsOn(...)]` attribute for your [module class](../../Module-Development-Basics.md) in the your Blazor UI project. +* Use `Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic.App` as the root component of your application in the `ConfigureServices` method of your module: + +````csharp +var builder = context.Services.GetSingletonInstance(); +builder.RootComponents.Add("#ApplicationContainer"); +```` + +`#ApplicationContainer` is a selector (like `
Loading...
`) in the `index.html`. + +## The Layout + +![basic-theme-application-layout](../../images/basic-theme-application-layout.png) + +Application Layout implements the following parts, in addition to the common parts mentioned above; + +* [Branding](Branding.md) Area +* Main [Menu](Navigation-Menu.md) +* Main [Toolbar](Toolbars.md) with Language Selection & User Menu +* [Page Alerts](Page-Alerts.md) + +## Customization + +You have two options two customize this theme: + +### Overriding Styles / Components + +In this approach, you continue to use the the theme as NuGet and NPM packages and customize the parts you need to. There are several ways to customize it; + +#### Override the Styles + +You can simply override the styles in the Global Styles file of your application. + +#### Override the Components + +See the [Customization / Overriding Components](Customization-Overriding-Components.md) to learn how you can replace components, customize and extend the user interface. + +### Copy & Customize + +You can download the [source code](https://github.com/abpframework/abp/tree/dev/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme) of the Basic Theme, copy the project content into your solution, re-arrange the package/module dependencies (see the Installation section above to understand how it was installed to the project) and freely customize the theme based on your application requirements. + +## See Also + +* [Theming](Theming.md) \ No newline at end of file diff --git a/docs/en/UI/Blazor/Branding.md b/docs/en/UI/Blazor/Branding.md new file mode 100644 index 0000000000..94bcb2bad5 --- /dev/null +++ b/docs/en/UI/Blazor/Branding.md @@ -0,0 +1,37 @@ +# Blazor UI: Branding + +## IBrandingProvider + +`IBrandingProvider` is a simple interface that is used to show the application name and logo on the layout. + +The screenshot below shows *MyProject* as the application name: + +![branding-nobrand](../../images/branding-nobrand.png) + +You can implement the `IBrandingProvider` interface or inherit from the `DefaultBrandingProvider` to set the application name: + +````csharp +using Volo.Abp.DependencyInjection; +using Volo.Abp.Ui.Branding; + +namespace MyCompanyName.MyProjectName.Blazor +{ + [Dependency(ReplaceServices = true)] + public class MyProjectNameBrandingProvider : DefaultBrandingProvider + { + public override string AppName => "Book Store"; + } +} +```` + +The result will be like shown below: + +![branding-appname](../../images/branding-appname.png) + +`IBrandingProvider` has the following properties: + +* `AppName`: The application name. +* `LogoUrl`: A URL to show the application logo. +* `LogoReverseUrl`: A URL to show the application logo on a reverse color theme (dark, for example). + +> **Tip**: `IBrandingProvider` is used in every page refresh. For a multi-tenant application, you can return a tenant specific application name to customize it per tenant. diff --git a/docs/en/UI/Blazor/Customization-Overriding-Components.md b/docs/en/UI/Blazor/Customization-Overriding-Components.md new file mode 100644 index 0000000000..995213f9e7 --- /dev/null +++ b/docs/en/UI/Blazor/Customization-Overriding-Components.md @@ -0,0 +1,86 @@ +# Blazor UI: Customization / Overriding Components + +This document explains how to override the user interface of a depended [application module](../../Modules/Index.md) or [theme](Theming.md) for Blazor applications. + +## Overriding a Razor Component + +The ABP Framework, pre-built themes and modules define some **re-usable razor components and pages**. These pages and components can be replaced by your application or module. + +> Since pages are just the razor components, the same principle is valid for pages too. + +### Example: Replacing the Branding Area + +The screenshot below was taken from the [Basic Theme](Basic-Theme.md) comes with the application startup template. + +![bookstore-brand-area-highlighted](../../images/bookstore-brand-area-highlighted.png) + +The [Basic Theme](Basic-Theme.md) defines some razor components for the layout. For example, the highlighted area with the red rectangle above is called *Branding* component. You probably want to customize this component by adding your **own application logo**. Let's see how to do it. + +First, create your logo and place under a folder in your web application. We used `wwwroot/bookstore-logo.png` path: + +![bookstore-logo-blazor](../../images/bookstore-logo-blazor.png) + +The next step is to create a razor component, like `MyBlazor.razor`, in your application: + +![bookstore-logo-blazor](../../images/bookstore-branding-blazor.png) + +The content of the `MyBlazor.razor` is shown below: + +````html +@using Volo.Abp.DependencyInjection +@using Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic +@inherits Branding +@attribute [ExposeServices(typeof(Branding))] +@attribute [Dependency(ReplaceServices = true)] + + + +```` + +Let's explain the code: + +* `@inherits Branding` line inherits the Branding component defined by the [Basic Theme](Basic-Theme.md) (in the `Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic` namespace). +* `@attribute [ExposeServices(typeof(Branding))]` registers this service (component) to [dependency injection](../../Dependency-Injection.md) for the `Branding` service (component). +* `@attribute [Dependency(ReplaceServices = true)]` replaces the `Branding` class (component) with this new `MyBranding` class (component). +* The rest of the code is related the content and styling of the component. + +Now, you can run the application to see the result: + +![bookstore-added-logo](../../images/bookstore-added-logo.png) + +> Since the component inherits from the component it is replacing, you can use all the non-private fields/properties/methods of the base component in the derived component. + +### Example: Replacing with the Code Behind File + +If you prefer to use code-behind file for the C# code of your component, you can use the attributes in the C# side. + +**MyBlazor.razor** + +````html +@using Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic +@inherits Branding + + + +```` + +**MyBlazor.razor.cs** + +````csharp +using Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic; +using Volo.Abp.DependencyInjection; + +namespace MyProject.Blazor.Components +{ + [ExposeServices(typeof(Branding))] + [Dependency(ReplaceServices = true)] + public partial class MyBranding + { + + } +} +```` + +## Theming + +The [Theming](Theming.md) system allows you to build your own theme. You can create your theme from scratch or get the [Basic Theme](Basic-Theme.md) and change however you like. diff --git a/docs/en/UI/Blazor/Global-Scripts-Styles.md b/docs/en/UI/Blazor/Global-Scripts-Styles.md new file mode 100644 index 0000000000..a9a69c76d0 --- /dev/null +++ b/docs/en/UI/Blazor/Global-Scripts-Styles.md @@ -0,0 +1,38 @@ +# Blazor UI: Managing Global Scripts & Styles + +Some modules may require additional styles or scripts that need to be referenced in **index.html** file. It's not easy to find and update these types of references in Blazor apps. ABP offers a simple, powerful, and modular way to manage global style and scripts in Blazor apps. + +To update script & style references without worrying about dependencies, ordering, etc in a project, you can use the [bundle command](../../CLI.md#bundle). + +You can also add custom styles and scripts and let ABP manage them for you. In your Blazor project, you can create a class implementing `IBundleContributor` interface. + +`IBundleContributor` interface contains two methods. + +* `AddScripts(...)` +* `AddStyles(...)` + +Both methods get `BundleContext` as a parameter. You can add scripts and styles to the `BundleContext` and run [bundle command](../../CLI.md#bundle). Bundle command detects custom styles and scripts with module dependencies and updates `index.html` file. + +## Example Usage +```csharp +namespace MyProject.Blazor +{ + public class MyProjectBundleContributor : IBundleContributor + { + public void AddScripts(BundleContext context) + { + context.Add("site.js"); + } + + public void AddStyles(BundleContext context) + { + context.Add("main.css"); + context.Add("custom-styles.css"); + } + } +} +``` + +> There is a BundleContributor class implementing `IBundleContributor` interface coming by default with the startup templates. So, most of the time, you don't need to add it manually. + +> Bundle command adds style and script references individually. Bundling and minification support will be added to incoming releases. \ No newline at end of file diff --git a/docs/en/UI/Blazor/Localization.md b/docs/en/UI/Blazor/Localization.md new file mode 100644 index 0000000000..d42249388e --- /dev/null +++ b/docs/en/UI/Blazor/Localization.md @@ -0,0 +1,78 @@ +# Blazor UI: Localization + +Blazor applications can reuse the same `IStringLocalizer` service that is explained in the [localization document](../../Localization.md). + +All the localization resources and texts available in the server side are usable in the Blazor application. + +## IStringLocalizer + +`IStringLocalizer` (`T` is the localization resource class) can be injected in any service or component to use the localization service. + +### Razor Components + +Use `@inject IStringLocalizer` to use the localization in a razor component. + +**Example: Localization in a Razor Component** + +````csharp +@page "/" +@using MyCompanyName.MyProjectName.Localization +@using Microsoft.Extensions.Localization +@inject IStringLocalizer L + +

+ @L["LongWelcomeMessage"] +

+```` + +> `L` is a name that we love and use as the name of a `IStringLocalizer` instance, while you can give any name. + +#### The AbpComponentBase + +`AbpComponentBase` is a useful base class that you can derive the components from. It has some useful properties/methods you typically need in a component. + +The `AbpComponentBase` already defines a base `L` property (of type `IStringLocalizer`). It only requires to set the resource type (in the constructor of the derived class). If you created your application from the ABP's application startup template, then you should have a *YourProjectComponentBase* class in the Blazor project. Inherit components from this class to have the localizer pre-injected. + +**Example: Derive from the base component class** + +````csharp +@page "/" +@inherits MyProjectNameComponentBase + +

+ @L["LongWelcomeMessage"] +

+```` + +### Other Services + +`IStringLocalizer` can be injected into any service. + +**Example** + +````csharp +public class MyService : ITransientDependency +{ + private readonly IStringLocalizer _localizer; + + public MyService(IStringLocalizer localizer) + { + _localizer = localizer; + } + + public void Foo() + { + var str = _localizer["HelloWorld"]; + } +} +```` + +### Format Arguments + +Format arguments can be passed after the localization key. If your message is `Hello {0}, welcome!`, then you can pass the `{0}` argument to the localizer like `_localizer["HelloMessage", "John"]`. + +> Refer to the [Microsoft's localization documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization) for details about using the localization. + +## See Also + +* [Localization](../../Localization.md) \ No newline at end of file diff --git a/docs/en/UI/Blazor/Message.md b/docs/en/UI/Blazor/Message.md new file mode 100644 index 0000000000..a2faee2548 --- /dev/null +++ b/docs/en/UI/Blazor/Message.md @@ -0,0 +1,129 @@ +# Blazor UI: Message Service + +UI message service is used to show nice-looking messages to the user as a blocking dialog. + +## Quick Example + +Simply [inject](../../Dependency-Injection.md) `IUiMessageService` to your page or component and call the `Success` method to show a success message. + +```csharp +namespace MyProject.Blazor.Pages +{ + public partial class Index + { + private readonly IUiMessageService _uiMessageService; + + public Index(IUiMessageService uiMessageService) + { + _uiMessageService = uiMessageService; + } + + public async Task SaveAsync() + { + await _uiMessageService.Success( + "Your changes have been successfully saved!", + "Congratulations"); + } + } +} +``` + +It will show a dialog on the UI: + +![blazor-message-success](../../images/blazor-message-success.png) + +If you inherit your page or component from the `AbpComponentBase` class, you can use the `Message` property to access the `IUiMessageService` as a pre-injected property. + +```csharp +namespace MyProject.Blazor.Pages +{ + public partial class Index : AbpComponentBase + { + public async Task SaveAsync() + { + await Message.Success( + "Your changes have been successfully saved!", + "Congratulations"); + } + } +} +``` +> You typically use `@inherits AbpComponentBase` in the `.razor` file to inherit from the `AbpComponentBase`, instead of inheriting in the code behind file. + +## Informative Messages + +There are four types of informative message functions: + +* `Info(...)` +* `Success(...)` +* `Warn(...)` +* `Error(...)` + +All of these methods get three parameters: + +* `message`: The message (`string`) to be shown. +* `title`: An optional (`string`) title. +* `options`: An optional (`Action`) to configure UI message options. + +**Example: Show an error message** + +````csharp +_uiMessageService.Error('Your credit card number is not valid!'); +```` + +![blazor-message-success](../../images/blazor-message-error.png) + + +## Confirmation Message + +`IUiMessageService.Confirm(...)` method can be used to get a confirmation from the user. + +**Example** + +Use the following code to get a confirmation result from the user: + +```csharp +public async Task DeleteAsync() +{ + var confirmed = await _uiMessageService.Confirm("Are you sure to delete the 'admin' role?"); + if(confirmed) + { + //Delete the 'admin' role here. + } +} +``` + +The resulting UI will be like shown below: + +![blazor-message-confirm](../../images/blazor-message-confirm.png) + +If the user has clicked the `Yes` button, the `Confirm` method's return value will be `true`. + +## Configuration + +It is easy to change default message options if you like to it per message. Provide an `action` to the `options` parameter as shown below. + +```csharp +await _uiMessageService.Success( + "Your changes have been successfully saved!", + "Congratulations", + (options) => + { + options.MessageIcon = "msg-icon-new"; + options.CenterMessage = false; + }); +``` + +List of the options that you can change by providing the `action` parameter. + +* `CenterMessage` : (Default: true) If true, the message dialogue will be centered on the screen. +* `ShowMessageIcon` : (Default: true) If true, the message dialogue will show the large icon for the current message type. +* `MessageIcon` : Overrides the build-in message icon. +* `OkButtonText` : Custom text for the OK button. +* `OkButtonIcon` : Custom icon for the OK button. +* `ConfirmButtonText` : Custom text for the Confirmation button. +* `ConfirmButtonIcon` : Custom icon for the Confirmation button. +* `CancelButtonText` : Custom text for the Cancel button. +* `CancelButtonIcon` : Custom icon for the Cancel button. + +> "Confirm", "Cancel" and "Yes" texts are automatically localized based on the current language. \ No newline at end of file diff --git a/docs/en/UI/Blazor/Navigation-Menu.md b/docs/en/UI/Blazor/Navigation-Menu.md new file mode 100644 index 0000000000..331de7a4cb --- /dev/null +++ b/docs/en/UI/Blazor/Navigation-Menu.md @@ -0,0 +1,207 @@ +# Blazor UI: Navigation / Menu + +Every application has a main menu to allow users to navigate to pages/screens of the application. Some applications may contain more than one menu in different sections of the UI. + +ABP Framework is a [modular](../../Module-Development-Basics.md) application development framework. **Every module may need to add items to the menu**. + +So, ABP Framework **provides a menu infrastructure** where; + +* The application or the modules can add items to a menu, without knowing how the menu is rendered. +* The [theme](Theming.md) properly renders the menu. + +## Adding Menu Items + +In order to add menu items (or manipulate the existing items) you need to create a class implementing the `IMenuContributor` interface. + +> The [application startup template](../../Startup-Templates/Application.md) already contains an implementation of the `IMenuContributor`. So, you can add items inside that class instead of creating a new one. + +**Example: Add a *CRM* menu item with *Customers* and *Orders* sub menu items** + +```csharp +using System.Threading.Tasks; +using MyProject.Localization; +using Volo.Abp.UI.Navigation; + +namespace MyProject.Web.Menus +{ + public class MyProjectMenuContributor : IMenuContributor + { + public async Task ConfigureMenuAsync(MenuConfigurationContext context) + { + if (context.Menu.Name == StandardMenus.Main) + { + await ConfigureMainMenuAsync(context); + } + } + + private async Task ConfigureMainMenuAsync(MenuConfigurationContext context) + { + var l = context.GetLocalizer(); + + context.Menu.AddItem( + new ApplicationMenuItem("MyProject.Crm", l["Menu:CRM"]) + .AddItem(new ApplicationMenuItem( + name: "MyProject.Crm.Customers", + displayName: l["Menu:Customers"], + url: "/crm/customers") + ).AddItem(new ApplicationMenuItem( + name: "MyProject.Crm.Orders", + displayName: l["Menu:Orders"], + url: "/crm/orders") + ) + ); + } + } +} +``` + +* This example adds items only to the main menu (`StandardMenus.Main`: see the *Standard Menus* section below). +* It gets a `IStringLocalizer` from `context` to [localize](../../Localization.md) the display names of the menu items. +* Adds the Customers and Orders as children of the CRM menu. + +Once you create a menu contributor, you need to add it to the `AbpNavigationOptions` in the `ConfigureServices` method of your module: + +````csharp +Configure(options => +{ + options.MenuContributors.Add(new MyProjectMenuContributor()); +}); +```` + +This example uses some localization keys as display names those should be defined in the localization file: + +````json +"Menu:CRM": "CRM", +"Menu:Orders": "Orders", +"Menu:Customers": "Customers" +```` + +See the [localization document](../../Localization.md) to learn more about the localization. + +When you run the application, you will see the menu items added to the main menu: + +![nav-main-menu](../../images/nav-main-menu.png) + +> The menu is rendered by the current UI [theme](Theming.md). So, the look of the main menu can be completely different based on your theme. + +Here, a few notes on the menu contributors; + +* ABP Framework calls the `ConfigureMenuAsync` method **whenever need to render** the menu. +* Every menu item can have **children**. So, you can add menu items with **unlimited depth** (however, your UI theme may not support unlimited depth). +* Only leaf menu items have `url`s normally. When you click to a parent menu, its sub menu is opened or closed, you don't navigate the `url` of a parent menu item. +* If a menu item has no children and has no `url` defined, then it is not rendered on the UI. This simplifies to authorize the menu items: You only authorize the child items (see the next section). If none of the children are authorized, then the parent automatically disappears. + +### Menu Item Properties + +There are more options of a menu item (the constructor of the `ApplicationMenuItem` class). Here, the list of all available options; + +* `name` (`string`, required): The **unique name** of the menu item. +* `displayName` (`string`, required): Display name/text of the menu item. You can [localize](../../Localization.md) this as shown before. +* `url` (`string`): The URL of the menu item. +* `icon` (`string`): An icon name. Free [Font Awesome](https://fontawesome.com/) icon classes are supported out of the box. Example: `fa fa-book`. You can use any CSS font icon class as long as you include the necessary CSS files to your application. +* `order` (`int`): The order of the menu item. Default value is `1000`. Items are sorted by the adding order unless you specify an order value. +* `customData` (`object`): A custom object that you can associate to the menu item and use it while rendering the menu item. +* `target` (`string`): Target of the menu item. Can be `null` (default), "\_*blank*", "\_*self*", "\_*parent*", "\_*top*" or a frame name for web applications. +* `elementId` (`string`): Can be used to render the element with a specific HTML `id` attribute. +* `cssClass` (`string`): Additional string classes for the menu item. + +### Authorization + +As seen above, a menu contributor contributes to the menu dynamically. So, you can perform any custom logic or get menu items from any source. + +One use case is the [authorization](Authorization.md). You typically want to add menu items by checking a permission. + +**Example: Check if the current user has a permission** + +````csharp +if (await context.IsGrantedAsync("MyPermissionName")) +{ + //...add menu items +} +```` + +> You can use `context.AuthorizationService` to directly access to the `IAuthorizationService`. + +### Resolving Dependencies + +`context.ServiceProvider` can be used to resolve any service dependency. + +**Example: Get a service** + +````csharp +var myService = context.ServiceProvider.GetRequiredService(); +//...use the service +```` + +> You don't need to care about releasing/disposing services. ABP Framework handles it. + +### The Administration Menu + +There is a special menu item in the menu menu that is added by the ABP Framework: The *Administration* menu. It is typically used by the pre-built admin [application modules](../../Modules/Index.md): + +![nav-main-menu-administration](../../images/nav-main-menu-administration.png) + +If you want to add menu items under the *Administration* menu item, you can use the `context.Menu.GetAdministration()` extension method: + +````csharp +context.Menu.GetAdministration().AddItem(...) +```` + +### Manipulating the Existing Menu Items + +ABP Framework executes the menu contributors by the [module dependency order](../../Module-Development-Basics.md). So, you can manipulate the menu items that your application or module (directly or indirectly) depends on. + +**Example: Set an icon for the `Users` menu item added by the [Identity Module](../../Modules/Identity.md)** + +````csharp +var userMenu = context.Menu.FindMenuItem(IdentityMenuNames.Users); +userMenu.Icon = "fa fa-users"; +```` + +> `context.Menu` gives you ability to access to all the menu items those have been added by the previous menu contributors. + +## Standard Menus + +A menu is a **named** component. An application may contain more than one menus with different, unique names. There are two pre-defined standard menus: + +* `Main`: The main menu of the application. Contains links to the page of the application. Defined as a constant: `Volo.Abp.UI.Navigation.StandardMenus.Main`. +* `User`: User profile menu. Defined as a constant: `Volo.Abp.UI.Navigation.StandardMenus.User`. + +The `Main` menu already covered above. The `User` menu is available when a user has logged in: + +![user-menu](../../images/user-menu.png) + +You can add items to the `User` menu by checking the `context.Menu.Name` as shown below: + +```csharp +if (context.Menu.Name == StandardMenus.User) +{ + //...add items +} +``` + +## IMenuManager + +`IMenuManager` is generally used by the UI [theme](Theming.md) to render the menu items on the UI. So, **you generally don't need to directly use** the `IMenuManager`. + +**Example: Get the Main Menu to render in a razor component** + +```csharp +// Code behind file of a razor component +public partial class NavMenu +{ + private readonly IMenuManager _menuManager; + + public NavMenu(IMenuManager menuManager) + { + _menuManager = menuManager; + } + + protected override async Task OnInitializedAsync() + { + var menu = await _menuManager.GetAsync(StandardMenus.Main); + //... + } +} +``` + diff --git a/docs/en/UI/Blazor/Notification.md b/docs/en/UI/Blazor/Notification.md new file mode 100644 index 0000000000..24b589b75c --- /dev/null +++ b/docs/en/UI/Blazor/Notification.md @@ -0,0 +1,103 @@ +# Blazor UI: Notification Service + +`IUiNotificationService` is used to show toast style notifications on the user interface. + +## Quick Example + +Simply [inject](../../Dependency-Injection.md) `IUiNotificationService` to your page or component and call the `Success` method to show a success message. + +```csharp +namespace MyProject.Blazor.Pages +{ + public partial class Index + { + private readonly IUiNotificationService _uiNotificationService; + + public Index(IUiNotificationService uiNotificationService) + { + _uiNotificationService = uiNotificationService; + } + + public async Task DeleteAsync() + { + await _uiNotificationService.Success( + "The product 'Acme Atom Re-Arranger' has been successfully deleted." + ); + } + } +} +``` + +![blazor-notification-sucess](../../images/blazor-notification-success.png) + +If you inherit your page or component from the `AbpComponentBase` class, you can use the the `Notify` property to access the `IUiNotificationService` as a pre-injected property. + +```csharp +namespace MyProject.Blazor.Pages +{ + public partial class Index : AbpComponentBase + { + public async Task DeleteAsync() + { + await Notify.Success( + "The product 'Acme Atom Re-Arranger' has been successfully deleted." + ); + } + } +} +``` + +> You typically use `@inherits AbpComponentBase` in the `.razor` file to inherit from the `AbpComponentBase`, instead of inheriting in the code behind file. + +## Notification Types + +There are four types of pre-defined notifications; + +* `Info(...)` +* `Success(...)` +* `Warn(...)` +* `Error(...)` + +All of the methods above gets the following parameters; + +* `message`: The message (`string`) to be shown. +* `title`: An optional (`string`) title. +* `options`: An optional (`Action`) to configure notification options. + +## Configuration + +### Per Notification + +It is easy to change default notification options if you like to customize it per notification. Provide an action to the `options` parameter as shown below: + +```csharp +await UiNotificationService.Success( + "The product 'Acme Atom Re-Arranger' has been successfully deleted.", + options: (options) => + { + options.OkButtonText = + LocalizableString.Create("CustomOK"); + }); +``` + +### Available Options + +Here, the list of all available options; + +* `OkButtonText` : Custom text for the OK button. +* `OkButtonIcon` : Custom icon for the OK button + +### Global Configuration + +You can also configure global notification options to control the it in a single point. Configure the `UiNotificationOptions` [options class](../../Options.md) in the `ConfigureServices` of your [module](../../Module-Development-Basics.md): + +````csharp +Configure(options => +{ + options.OkButtonText = LocalizableString.Create("CustomOK"); +}); +```` + +The same options are available here. + +> *Per notification* configuration overrides the default values. \ No newline at end of file diff --git a/docs/en/UI/Blazor/Overall.md b/docs/en/UI/Blazor/Overall.md index 74c469e3c4..cf8287f0de 100644 --- a/docs/en/UI/Blazor/Overall.md +++ b/docs/en/UI/Blazor/Overall.md @@ -1,6 +1,155 @@ -# Blazor UI for the ABP Framework +# Blazor UI: Overall -The detailed documentation for the Blazor UI is in progress. However, you can follow the documents below to start with the Blazor UI today. +## Introduction -* [Get started](https://docs.abp.io/en/abp/latest/Getting-Started?UI=Blazor) with the Blazor UI for the ABP Framework. -* [Web Application Development Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=Blazor) with the Blazor UI. \ No newline at end of file +[Blazor](https://docs.microsoft.com/en-us/aspnet/core/blazor/) is a framework for building interactive client-side web UI with .NET. It is promising for a .NET developer that you can create Single-Page Web Applications using C# and the Razor syntax. + +ABP provides infrastructure and integrations that make your Blazor development even easier, comfortable and enjoyable. + +This document provides an overview for the ABP Framework Blazor UI integration and highlights some major features. + +### Getting Started + +You can follow the documents below to start with the ABP Framework and the Blazor UI now: + +* [Get started](../../Getting-Started.md) with the Blazor UI for the ABP Framework. +* [Web Application Development Tutorial](../../Tutorials/Part-1.md) with the Blazor UI. + +## Modularity + +[Modularity](../../Module-Development-Basics.md) is one of the key goals of the ABP Framework. It is not different for the UI; It is possible to develop modular applications and reusable application modules with isolated and reusable UI pages and components. + +The [application startup template](../../Startup-Templates/Application.md) comes with some application modules pre-installed. These modules have their own UI pages embedded into their own NuGet packages. You don't see their code in your solution, but they work as expected on runtime. + +## Dynamic C# Client Proxies + +Dynamic C# Client Proxy system makes extremely easy to consume server side HTTP APIs from the UI. You just **inject** the [application service](../../Application-Services.md) **interface** and consume the remote APIs just like using local service method calls. + +**Example: Get list of books from server and list on the UI** + +````csharp +@page "/books" +@using Acme.BookStore.Books +@using Volo.Abp.Application.Dtos +@inject IBookAppService BookAppService + +
    + @foreach (var book in Books) + { +
  • + @book.Name (by @book.AuthorName) +
  • + } +
+ +@code { + private IReadOnlyList Books { get; set; } = new List(); + + protected override async Task OnInitializedAsync() + { + var result = await BookAppService.GetListAsync( + new PagedAndSortedResultRequestDto() + ); + + Books = result.Items; + } +} +```` + +* This razor component (page) uses `@inject IBookAppService BookAppService` to get a reference to the service proxy. +* It uses `BookAppService.GetListAsync` in the `OnInitializedAsync` and gets the list of the books, just like a regular C# method call. +* Finally, the page renders the books in a list on the UI. + +ABP Framework handles all the low level details for you, including a proper HTTP call, JSON serialization, exception handling and authentication. + +See the [Dynamic C# Client Proxies](../../API/Dynamic-CSharp-API-Clients.md) document for more. + +## Theming System + +ABP Framework provides a complete [Theming](Theming.md) system with the following goals: + +* Reusable [application modules](../../Modules/Index.md) are developed **theme-independent**, so they can work with any UI theme. +* UI theme is **decided by the final application**. +* The theme is distributed as NuGet package, so it is **easily upgradable**. +* The final application can **customize** the selected theme. + +### Current Themes + +Currently, two themes are **officially provided**: + +* The [Basic Theme](Basic-Theme.md) is the minimalist theme with the plain Bootstrap style. It is **open source and free**. +* The [Lepton Theme](https://commercial.abp.io/themes) is a **commercial** theme developed by the core ABP team and is a part of the [ABP Commercial](https://commercial.abp.io/) license. + +### Base Libraries + +There are a set of standard libraries that comes pre-installed and supported by all the themes: + +* [Twitter Bootstrap](https://getbootstrap.com/) as the fundamental HTML/CSS framework. +* [Blazorise](https://github.com/stsrki/Blazorise) as a component library that supports the Bootstrap and adds extra components like Data Grid and Tree. +* [FontAwesome](https://fontawesome.com/) as the fundamental CSS font library. +* [Flag Icon](https://github.com/lipis/flag-icon-css) as a library to show flags of countries. + +These libraries are selected as the base libraries and available to the applications and modules. + +> Bootstrap's JavaScript part is not used since the Blazorise library already provides the necessary functionalities to the Bootstrap components in a native way. + +### The Layout + +The themes provide the layout. So, you have a responsive layout with the standard features already implemented. The screenshot below has taken from the layout of the [Basic Theme](Basic-Theme.md): + +![basic-theme-application-layout](../../images/basic-theme-application-layout.png) + +See the [Theming](Theming.md) document for more layout options and other details. + +### Layout Parts + +A typical layout consists of multiple parts. The [Theming](Theming.md) system provides [menus](Navigation-Menu.md), [toolbars](Toolbars.md), [page alerts](Page-Alerts.md) and more to dynamically control the layout by your application and the modules you are using. + +## Global Styles & Scripts / Bundling & Minification + +ABP provides a standard way to manage the global script and style dependencies of an application. This is an essential feature for modularity since some modules may have such dependencies and they can declare dependencies in that way. + +See the [Managing Global Scripts & Styles](Global-Scripts-Styles.md) document. + +## Services + +ABP provides useful services that you can consume in your applications. Some of them are; + +* [IUiMessageService](Message.md) is used to show modal messages to the user. +* [IUiNotificationService](Notification.md) is used to show toast-style notifications. +* [IAlertManager](Page-Alerts.md) is used to show in-page alerts. +* [ISettingProvider](Settings.md) is used to access to the current setting values. +* `ICurrentUser` and `ICurrentTenant` is used to get information about the current user and the tenant. + +## Dependency Injection + +Razor components doesn't support [constructor injection](../../Dependency-Injection.md) by default. ABP makes possible to inject dependencies into the constructor of the code-behind file of a component. + +**Example: Constructor-inject a service in the code-behind file of a component** + +````csharp +using Microsoft.AspNetCore.Components; + +namespace MyProject.Blazor.Pages +{ + public partial class Index + { + private readonly NavigationManager _navigationManager; + + public Index(NavigationManager navigationManager) + { + _navigationManager = navigationManager; + } + } +} +```` + +ABP makes this possible by auto registering components to and resolving the component from the [Dependency Injection](../../Dependency-Injection.md) system. + +> You can still continue to use property injection and the standard `[Inject]` approach if you prefer. + +Resolving a component from the Dependency Injection system makes it possible to easily replace components of a depended module. + +## Customization + +While the theme and some modules come as NuGet packages, you can still replace/override and customize them on need. See the [Customization / Overriding Components](Customization-Overriding-Components.md) document. \ No newline at end of file diff --git a/docs/en/UI/Blazor/Page-Alerts.md b/docs/en/UI/Blazor/Page-Alerts.md new file mode 100644 index 0000000000..cfac721572 --- /dev/null +++ b/docs/en/UI/Blazor/Page-Alerts.md @@ -0,0 +1,62 @@ +# Blazor UI: Page Alerts + +It is common to show error, warning or information alerts to inform the user. An example *Service Interruption* alert is shown below: + +![blazor-page-alert-example](../../images/blazor-page-alert-example.png) + +## Quick Example + +Simply [inject](../../Dependency-Injection.md) `IAlertManager` to your page or component and call the `Alerts.Warning` method to show a success message. + +```csharp +namespace MyProject.Blazor.Pages +{ + public partial class Index + { + private readonly IAlertManager _alertManager; + + public Index(IAlertManager alertManager) + { + this._alertManager = alertManager; + } + + protected override void OnInitialized() + { + _alertManager.Alerts.Warning( + "We will have a service interruption between 02:00 AM and 04:00 AM at October 23, 2023!", + "Service Interruption"); + base.OnInitialized(); + } + } +} +``` + +If you inherit your page or component from the `AbpComponentBase` class, you can use the `Alerts` property to add alerts. + +```csharp +namespace MyProject.Blazor.Pages +{ + public partial class Index : AbpComponentBase + { + protected override void OnInitialized() + { + Alerts.Warning( + "We will have a service interruption between 02:00 AM and 04:00 AM at October 23, 2023!", + "Service Interruption"); + base.OnInitialized(); + } + } +} +``` + +> You typically use `@inherits AbpComponentBase` in the `.razor` file to inherit from the `AbpComponentBase`, instead of inheriting in the code behind file. + +### Alert Types + +`Warning` is used to show a warning alert. Other common methods are `Info`, `Danger` and `Success`. + +Beside the standard methods, you can use the `Alerts.Add` method by passing an `AlertType` `enum` with one of these values: `Default`, `Primary`, `Secondary`, `Success`, `Danger`, `Warning`, `Info`, `Light`, `Dark`. + +### Dismissible + +All alert methods gets an optional `dismissible` parameter. Default value is `true` which makes the alert box dismissible. Set it to `false` to create a sticky alert box. diff --git a/docs/en/UI/Blazor/Services/Notification.md b/docs/en/UI/Blazor/Services/Notification.md deleted file mode 100644 index 0e5ababa0e..0000000000 --- a/docs/en/UI/Blazor/Services/Notification.md +++ /dev/null @@ -1,3 +0,0 @@ -# Blazor UI Notification - -`UiNotificationService` is used to show toastr style notifications on the user interface. The documentation is in progress... \ No newline at end of file diff --git a/docs/en/UI/Blazor/Settings.md b/docs/en/UI/Blazor/Settings.md new file mode 100644 index 0000000000..e146b7ea69 --- /dev/null +++ b/docs/en/UI/Blazor/Settings.md @@ -0,0 +1,63 @@ +# Blazor UI: Settings + +Blazor applications can reuse the same `ISettingProvider` service that is explained in the [settings document](../../Settings.md). + +## ISettingProvider + +`ISettingProvider` is used to get the value of a setting or get the values of all the settings. + +**Example usages in a simple service** + +````csharp +public class MyService : ITransientDependency +{ + private readonly ISettingProvider _settingProvider; + + //Inject ISettingProvider in the constructor + public MyService(ISettingProvider settingProvider) + { + _settingProvider = settingProvider; + } + + public async Task FooAsync() + { + //Get a value as string. + string setting1 = await _settingProvider.GetOrNullAsync("MySettingName"); + + //Get a bool value and fallback to the default value (false) if not set. + bool setting2 = await _settingProvider.GetAsync("MyBoolSettingName"); + + //Get a bool value and fallback to the provided default value (true) if not set. + bool setting3 = await _settingProvider.GetAsync( + "MyBoolSettingName", defaultValue: true); + + //Get a bool value with the IsTrueAsync shortcut extension method + bool setting4 = await _settingProvider.IsTrueAsync("MyBoolSettingName"); + + //Get an int value or the default value (0) if not set + int setting5 = (await _settingProvider.GetAsync("MyIntegerSettingName")); + + //Get an int value or null if not provided + int? setting6 = (await _settingProvider + .GetOrNullAsync("MyIntegerSettingName"))?.To(); + } +} +```` + +**Example usage in a Razor Component** + +````csharp +@page "/" +@using Volo.Abp.Settings +@inject ISettingProvider SettingProvider +@code { + protected override async Task OnInitializedAsync() + { + bool settingValue = await SettingProvider.GetAsync("MyBoolSettingName"); + } +} +```` + +## See Also + +* [Settings](../../Settings.md) \ No newline at end of file diff --git a/docs/en/UI/Blazor/Theming.md b/docs/en/UI/Blazor/Theming.md new file mode 100644 index 0000000000..cbc6341dab --- /dev/null +++ b/docs/en/UI/Blazor/Theming.md @@ -0,0 +1,207 @@ +# Blazor UI: Theming + +## Introduction + +ABP Framework provides a complete **UI Theming** system with the following goals: + +* Reusable [application modules](../../Modules/Index.md) are developed **theme-independent**, so they can work with any UI theme. +* UI theme is **decided by the final application**. +* The theme is distributed via a NuGet package, so it is **easily upgradable**. +* The final application can **customize** the selected theme. + +In order to accomplish these goals, ABP Framework; + +* Determines a set of **base libraries** used and adapted by all the themes. So, module and application developers can depend on and use these libraries without depending on a particular theme. +* Provides a system that consists of layout parts (like [navigation menus](Navigation-Menu.md) and [toolbars](Toolbars.md)) that is implemented by all the themes. So, the modules and the application to contribute to the layout to compose a consistent application UI. + +### Current Themes + +Currently, two themes are **officially provided**: + +* The [Basic Theme](Basic-Theme.md) is the minimalist theme with the plain Bootstrap style. It is **open source and free**. +* The [Lepton Theme](https://commercial.abp.io/themes) is a **commercial** theme developed by the core ABP team and is a part of the [ABP Commercial](https://commercial.abp.io/) license. + +## Overall + +### The Base Libraries + +All the themes must depend on the [Volo.Abp.AspNetCore.Components.WebAssembly.Theming](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Components.WebAssembly.Theming) NuGet package, so they are indirectly depending on the following libraries: + +* [Twitter Bootstrap](https://getbootstrap.com/) as the fundamental HTML/CSS framework. +* [Blazorise](https://github.com/stsrki/Blazorise) as a component library that supports the Bootstrap and adds extra components like Data Grid and Tree. +* [FontAwesome](https://fontawesome.com/) as the fundamental CSS font library. +* [Flag Icon](https://github.com/lipis/flag-icon-css) as a library to show flags of countries. + +These libraries are selected as the base libraries and available to the applications and modules. + +> Bootstrap's JavaScript part is not used since the Blazorise library already provides the necessary functionalities to the Bootstrap components in a native way. + +### The Layout + +All themes must define a layout for the application. The following image shows the user management page in the [Basic Theme](Basic-Theme.md) application layout: + +![basic-theme-application-layout-blazor](../../images/basic-theme-application-layout-blazor.png) + +And the same page is shown below with the [Lepton Theme](https://commercial.abp.io/themes) application layout: + +![lepton-theme-application-layout](../../images/lepton-theme-blazor-layout.png) + +As you can see, the page is the same, but the look is completely different in the themes above. + +The application layout typically includes the following parts; + +* A [main menu](Navigation-Menu.md) +* Main [Toolbar](Toolbars.md) with the following components; + * User menu + * Language switch dropdown +* [Page alerts](Page-Alerts.md) +* The page content (aka `@Body`) + +## Implementing a Theme + +A theme is simply a Razor Class Library. + +### The Easy Way + +The easiest way to create a new theme is to copy the [Basic Theme Source Code](https://github.com/abpframework/abp/tree/dev/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme) and customize it. Once you get a copy of the theme in your solution, remove the `Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic` NuGet package and reference to the local project. + +### Global Styles / Scripts + +A theme generally needs to add a global style to the page. ABP provides a system to manage the [Global Styles and Scripts](Global-Scripts-Styles.md). A theme can implement the `IBundleContributor` to add global style or script files to the page. + +**Example: Adding a style to the page** + +````csharp +using Volo.Abp.Bundling; + +namespace MyTheme +{ + public class MyThemeBundleContributor : IBundleContributor + { + public void AddScripts(BundleContext context) + { + + } + + public void AddStyles(BundleContext context) + { + context.Add("_content/MyTheme/styles.css"); + } + } +} +```` + +`styles.css` file should be added into the `wwwroot` folder of the theme project for this example. When you use the `abp bundle` command, this class is automatically discovered and executed to add the style to the page. + +See the [Global Styles and Scripts](Global-Scripts-Styles.md) document for more. + +### Layout Parts + +A typical Layout consists of several parts. The theme should include the necessary parts in each layout. + +**Example: The Basic Theme has the following parts for the Application Layout** + +![basic-theme-application-layout-parts](../../images/basic-theme-application-layout-parts.png) + +The application code and the modules can only show contents in the Page Content part. If they need to change the other parts (to add a menu item, to add a toolbar item, to change the application name in the branding area...) they should use the ABP Framework APIs. + +The following sections explain the fundamental parts pre-defined by the ABP Framework and can be implemented by the themes. + +> It is a good practice to split the layout into components/partials, so the final application can override them partially for customization purpose. + +#### Branding + +`IBrandingProvider` service should be used to get the name and the logo URL of the application to render in the Branding part. + +The [Application Startup Template](../../Startup-Templates/Application.md) has an implementation of this interface to set the values by the application developer. + +#### Main Menu + +`IMenuManager` service is used to get the main menu items and render on the layout. + +**Example: Get the Main Menu to render in a razor component** + +```csharp +// Code behind file of a razor component +public partial class NavMenu +{ + private readonly IMenuManager _menuManager; + + public NavMenu(IMenuManager menuManager) + { + _menuManager = menuManager; + } + + protected override async Task OnInitializedAsync() + { + var menu = await _menuManager.GetAsync(StandardMenus.Main); + //... + } +} +``` + +See the [Navigation / Menus](Navigation-Menu.md) document to learn more about the navigation system. + +#### Main Toolbar + +`IToolbarManager` service is used to get the Main Toolbar items and render on the layout. Each item of this toolbar is a Razor Component, so it may include any type of UI elements. Inject the `IToolbarManager` and use the `GetAsync` to get the toolbar items: + +````csharp +var toolbar = await _toolbarManager.GetAsync(StandardToolbars.Main); +```` + +> See the [Toolbars](Toolbars.md) document to learn more on the toolbar system. + +The theme has a responsibility to add two pre-defined items to the main toolbar: Language Selection and User Menu. To do that, create a class implementing the `IToolbarContributor` interface and add it to the `AbpToolbarOptions` as shown below: + +```csharp +Configure(options => +{ + options.Contributors.Add(new BasicThemeMainTopToolbarContributor()); +}); +``` + +##### Language Selection + +Language Selection toolbar item is generally a dropdown that is used to switch between languages. `ILanguageProvider` is used to get the list of available languages and `CultureInfo.CurrentUICulture` is used to learn the current language. + +Local Storage is used to get and set the current language with the `Abp.SelectedLanguage` key. + +**Example: Get the currently selected language** + +````csharp +var selectedLanguageName = await JsRuntime.InvokeAsync( + "localStorage.getItem", + "Abp.SelectedLanguage" + ); +```` + +**Example: Set the selected language** + +````csharp +await JsRuntime.InvokeVoidAsync( + "localStorage.setItem", + "Abp.SelectedLanguage", + "en-US" + ); +```` + +The theme should reload the page after changing the language: + +````csharp +await JsRuntime.InvokeVoidAsync("location.reload"); +```` + +##### User Menu + +User menu includes links related to the user account. `IMenuManager` is used just like the Main Menu, but this time with `StandardMenus.User` parameter like shown below: + +````csharp +var menu = await _menuManager.GetAsync(StandardMenus.User); +```` + +[ICurrentUser](../../CurrentUser.md) and [ICurrentTenant](../../Multi-Tenancy.md) services can be used to obtain the current user and tenant names. + +#### Page Alerts + +`IAlertManager` service is used to get the current page alerts to render on the layout. See the [Page Alerts](Page-Alerts.md) document to learn more. \ No newline at end of file diff --git a/docs/en/UI/Blazor/Toolbars.md b/docs/en/UI/Blazor/Toolbars.md new file mode 100644 index 0000000000..b8cca6077a --- /dev/null +++ b/docs/en/UI/Blazor/Toolbars.md @@ -0,0 +1,75 @@ +# Blazor UI: Toolbars + +The Toolbar system is used to define **toolbars** on the user interface. Modules (or your application) can add **items** to a toolbar, then the [theme](Theming.md) renders the toolbar on the **layout**. + +There is only one **standard toolbar** named "Main" (defined as a constant: `StandardToolbars.Main`). The [Basic Theme](Basic-Theme) renders the main toolbar as shown below: + +![bookstore-toolbar-highlighted](../../images/bookstore-toolbar-highlighted.png) + +In the screenshot above, there are two items added to the main toolbar: Language switch component & user menu. You can add your own items here. + +## Example: Add a Notification Icon + +In this example, we will add a **notification (bell) icon** to the left of the language switch item. A item in the toolbar should be a **Razor Component**. So, first, create a new razor component in your project (the location of the component doesn't matter): + +![bookstore-notification-view-component](../../images/blazor-notification-bell-component.png) + +The content of the `Notification.razor` is shown below: + +````html +@inherits Volo.Abp.AspNetCore.Components.AbpComponentBase +
+ +
+@code { + private async Task ShowNotifications() + { + await Message.Info("TODO: Show notifications"); + } +} +```` + +This sample simply shows a message. In real life, you probably want to call an HTTP API to get notifications and show on the UI. + +Now, we can create a class implementing the `IToolbarContributor` interface: + +````csharp +using System.Threading.Tasks; +using MyCompanyName.MyProjectName.Blazor.Components; +using Volo.Abp.AspNetCore.Components.WebAssembly.Theming.Toolbars; + +namespace MyCompanyName.MyProjectName.Blazor +{ + public class MyToolbarContributor : IToolbarContributor + { + public Task ConfigureToolbarAsync(IToolbarConfigurationContext context) + { + if (context.Toolbar.Name == StandardToolbars.Main) + { + context.Toolbar.Items.Insert(0, new ToolbarItem(typeof(Notification))); + } + + return Task.CompletedTask; + } + } +} +```` + +This class adds the `NotificationViewComponent` as the first item in the `Main` toolbar. + +Finally, you need to add this contributor to the `AbpToolbarOptions`, in the `ConfigureServices` of your [module](../../Module-Development-Basics.md): + +````csharp +Configure(options => +{ + options.Contributors.Add(new MyToolbarContributor()); +}); +```` + +That's all, you will see the notification icon on the toolbar when you run the application: + +![bookstore-notification-icon-on-toolbar](../../images/bookstore-notification-icon-on-toolbar.png) + +## IToolbarManager + +`IToolbarManager` is used to render the toolbar. It returns the toolbar items by a toolbar name. This is generally used by the [themes](Theming.md) to render the toolbar on the layout. \ No newline at end of file diff --git a/docs/en/Upgrading.md b/docs/en/Upgrading.md index 1140c5d573..fcda081188 100644 --- a/docs/en/Upgrading.md +++ b/docs/en/Upgrading.md @@ -16,11 +16,26 @@ Run this command in the terminal while you are in the root folder of your soluti > If your solution has the Angular UI, you probably have `aspnet-core` and `angular` folders in the solution. Run this command in the parent folder of these two folders. -## The Blog Posts +### Database Migrations + +> Warning: Be careful if you are migrating your database since you may have data loss in some cases. Carefully check the generated migration code before executing it. It is suggested to take a backup of your current database. + +When you upgrade to a new version, it is good to check if there is a database schema change and upgrade your database schema if your database provider is **Entity Framework Core**; + +* Use `Add-Migration "Upgraded_To_Abp_4_1"` or a similar command in the Package Manager Console (PMC) to create a new migration (Set the `EntityFrameworkCore.DbMigrations` as the Default project in the PMC and `.DbMigrator` as the Startup Project in the Solution Explorer, in the Visual Studio). +* Run the `.DbMigrator` application to upgrade the database and seed the initial data. + +If `Add-Migration` generates an empty migration, you can use `Remove-Migration` to delete it before executing the `.DbMigrator`. + +## The Blog Posts & Guides Sometimes we introduce new features/changes that requires to make changes in the startup template. We already implement the changes in the startup template for new applications. However, in some cases you need to manually make some minor changes in your solution. -Whenever you upgrade your solution, it is strongly suggested to check the [ABP BLOG](https://blog.abp.io/?_ga=2.177248992.411298747.1597771169-1910388957.1594128976) to learn the new features and changes coming with the new version. We regularly publish posts and write these kind of changes. If the changes are not trivial, we also provide migration guides. +Whenever you upgrade your solution, it is strongly suggested to check the [ABP BLOG](https://blog.abp.io/) to learn the new features and changes coming with the new version. We regularly publish posts and write these kind of changes. + +### Migration Guides + +We prepare migration guides if the new version brings breaking changes for existing applications. See the [Migration Guides](Migration-Guides/Index.md) page for all the guides. ## Semantic Versioning & Breaking Changes diff --git a/docs/en/Validation.md b/docs/en/Validation.md index 15c3f13412..c4821adf65 100644 --- a/docs/en/Validation.md +++ b/docs/en/Validation.md @@ -112,6 +112,29 @@ namespace Acme.BookStore > ABP framework uses the [dynamic proxying / interception](Dynamic-Proxying-Interceptors.md) system to perform the validation. In order to make it working, your method should be **virtual** or your service should be injected and used over an **interface** (like `IMyService`). +#### Enabling/Disabling Validation + +You can use the `[DisableValidation]` to disable it for methods, classs and properties. + +````csharp +[DisableValidation] +public Void MyMethod() +{ +} + +[DisableValidation] +public class InputClass +{ + public string MyProperty { get; set; } +} + +public class InputClass +{ + [DisableValidation] + public string MyProperty { get; set; } +} +```` + ### AbpValidationException Once ABP determines a validation error, it throws an exception of type `AbpValidationException`. Your application code can throw `AbpValidationException`, but most of the times it is not needed. @@ -155,4 +178,4 @@ public class MyObjectValidationContributor ## FluentValidation Integration -Volo.Abp.FluentValidation package integrates the FluentValidation library to the validation system (by implementing the `IObjectValidationContributor`). See the [FluentValidation Integration document](FluentValidation.md) for more. \ No newline at end of file +Volo.Abp.FluentValidation package integrates the FluentValidation library to the validation system (by implementing the `IObjectValidationContributor`). See the [FluentValidation Integration document](FluentValidation.md) for more. diff --git a/docs/en/Value-Objects.md b/docs/en/Value-Objects.md index 0c6c8d4424..f61e32245b 100644 --- a/docs/en/Value-Objects.md +++ b/docs/en/Value-Objects.md @@ -1,3 +1,75 @@ -## Value Objects +# Value Objects -TODO \ No newline at end of file +> An object that represents a descriptive aspect of the domain with no conceptual identity is called a VALUE OBJECT. +> +> (Eric Evans) + +Two [Entities](Entities.md) with the same properties but with different `Id`s are considered as different entities. However, Value Objects have no `Id`s and they are considered as equals if they have the same property values. + +## The ValueObject Class + +`ValueObject` is an abstract class that can be inherited to create a Value Object class. + +**Example: An Address class** + +````csharp +public class Address : ValueObject +{ + public Guid CityId { get; private set; } + + public string Street { get; private set; } + + public int Number { get; private set; } + + private Address() + { + + } + + public Address( + Guid cityId, + string street, + int number) + { + CityId = cityId; + Street = street; + Number = number; + } + + protected override IEnumerable GetAtomicValues() + { + yield return Street; + yield return CityId; + yield return Number; + } +} +```` + +* A Value Object class must implement the `GetAtomicValues()` method to return the primitive values. + +### ValueEquals + +`ValueObject.ValueEquals(...)` method is used to check if two Value Objects are equals. + +**Example: Check if two addresses are equals** + +````csharp +Address address1 = ... +Address address2 = ... + +if (address1.ValueEquals(address2)) //Check equality +{ + ... +} +```` + +## Best Practices + +Here are some best practices when using Value Objects: + +- Design a value object as **immutable** (like the Address above) if there is not a good reason for designing it as mutable. +- The properties that make up a Value Object should form a conceptual whole. For example, CityId, Street and Number shouldn't be separate properties of a Person entity. This also makes the Person entity simpler. + +## See Also + +* [Entities](Entities.md) \ No newline at end of file diff --git a/docs/en/_resources/Diagrams.docx b/docs/en/_resources/Diagrams.docx index 424e281470..15cb38bab2 100644 Binary files a/docs/en/_resources/Diagrams.docx and b/docs/en/_resources/Diagrams.docx differ diff --git a/docs/en/_resources/ddd-microservice-simple.psd b/docs/en/_resources/ddd-microservice-simple.psd new file mode 100644 index 0000000000..ad0946f132 Binary files /dev/null and b/docs/en/_resources/ddd-microservice-simple.psd differ diff --git a/docs/en/_resources/ui-db-options.psd b/docs/en/_resources/ui-db-options.psd new file mode 100644 index 0000000000..2c98b76a07 Binary files /dev/null and b/docs/en/_resources/ui-db-options.psd differ diff --git a/docs/en/docs-nav.json b/docs/en/docs-nav.json index a9850e74ba..197bbaf988 100644 --- a/docs/en/docs-nav.json +++ b/docs/en/docs-nav.json @@ -11,12 +11,41 @@ "text": "Console Application", "path": "Startup-Templates/Console.md" }, + { + "text": "WPF Application", + "path": "Startup-Templates/WPF.md" + }, { "text": "Empty Web Project", "path": "Getting-Started-AspNetCore-Application.md" } ] }, + { + "text": "Startup Templates", + "items": [ + { + "text": "Overall", + "path": "Startup-Templates/Index.md" + }, + { + "text": "Application", + "path": "Startup-Templates/Application.md" + }, + { + "text": "Module", + "path": "Startup-Templates/Module.md" + }, + { + "text": "Console", + "path": "Startup-Templates/Console.md" + }, + { + "text": "WPF", + "path": "Startup-Templates/WPF.md" + } + ] + }, { "text": "Tutorials", "items": [ @@ -64,29 +93,10 @@ "path": "Tutorials/Part-10.md" } ] - } - ] - }, - { - "text": "Guides", - "items": [ + }, { - "text": "Customizing the Application Modules", - "path": "Customizing-Application-Modules-Guide.md", - "items": [ - { - "text": "Extending Entities", - "path": "Customizing-Application-Modules-Extending-Entities.md" - }, - { - "text": "Overriding Services", - "path": "Customizing-Application-Modules-Overriding-Services.md" - }, - { - "text": "Overriding the User Interface", - "path": "Customizing-Application-Modules-Overriding-User-Interface.md" - } - ] + "text": "Community Articles", + "path": "https://community.abp.io/articles" }, { "text": "Migrating from the ASP.NET Boilerplate", @@ -94,30 +104,9 @@ } ] }, - { - "text": "CLI", - "path": "CLI.md" - }, - { - "text": "Authentication", - "items": [ - { - "text": "Social/External Logins", - "path": "Authentication/Social-External-Logins.md" - } - ] - }, { "text": "Fundamentals", "items": [ - { - "text": "Configuration", - "path": "Configuration.md" - }, - { - "text": "Options", - "path": "Options.md" - }, { "text": "Dependency Injection", "path": "Dependency-Injection.md", @@ -129,16 +118,16 @@ ] }, { - "text": "Virtual File System", - "path": "Virtual-File-System.md" + "text": "Configuration", + "path": "Configuration.md" }, { - "text": "Localization", - "path": "Localization.md" + "text": "Options", + "path": "Options.md" }, { - "text": "Exception Handling", - "path": "Exception-Handling.md" + "text": "Authorization", + "path": "Authorization.md" }, { "text": "Validation", @@ -151,8 +140,8 @@ ] }, { - "text": "Authorization", - "path": "Authorization.md" + "text": "Localization", + "path": "Localization.md" }, { "text": "Caching", @@ -165,79 +154,59 @@ ] }, { - "text": "Logging", - "path": "Logging.md" - }, - { - "text": "Audit Logging", - "path": "Audit-Logging.md" + "text": "Exception Handling", + "path": "Exception-Handling.md" }, { "text": "Settings", "path": "Settings.md" }, { - "text": "Features", - "path": "Features.md" - }, - { - "text": "Data Filtering", - "path": "Data-Filtering.md" + "text": "Connection Strings", + "path": "Connection-Strings.md" }, { "text": "Object Extensions", "path": "Object-Extensions.md" + }, + { + "text": "Logging", + "path": "Logging.md" } ] }, { - "text": "Event Bus", + "text": "Infrastructure", "items": [ { - "text": "Overall", - "path": "Event-Bus.md" - }, - { - "text": "Local Event Bus", - "path": "Local-Event-Bus.md" + "text": "Audit Logging", + "path": "Audit-Logging.md" }, { - "text": "Distributed Event Bus", - "path": "Distributed-Event-Bus.md", + "text": "Background Jobs", + "path": "Background-Jobs.md", "items": [ + { + "text": "Hangfire Integration", + "path": "Background-Jobs-Hangfire.md" + }, { "text": "RabbitMQ Integration", - "path": "Distributed-Event-Bus-RabbitMQ-Integration.md" + "path": "Background-Jobs-RabbitMq.md" }, { - "text": "Kafka Integration", - "path": "Distributed-Event-Bus-Kafka-Integration.md" + "text": "Quartz Integration", + "path": "Background-Jobs-Quartz.md" } ] - } - ] - }, - { - "text": "Services", - "items": [ - { - "text": "Current User", - "path": "CurrentUser.md" - }, - { - "text": "Object to object mapping", - "path": "Object-To-Object-Mapping.md" }, { - "text": "Email Sending", + "text": "Background Workers", + "path": "Background-Workers.md", "items": [ { - "text": "Email Sending System", - "path": "Emailing.md" - }, - { - "text": "MailKit Integration", - "path": "MailKit.md" + "text": "Quartz Integration", + "path": "Background-Workers-Quartz.md" } ] }, @@ -284,85 +253,190 @@ ] }, { - "text": "Text Templating", - "path": "Text-Templating.md" + "text": "CSRF/XSRF & Anti Forgery", + "path": "CSRF-Anti-Forgery.md" + }, + { + "text": "Current User", + "path": "CurrentUser.md" + }, + { + "text": "Data Filtering", + "path": "Data-Filtering.md" + }, + { + "text": "Data Seeding", + "path": "Data-Seeding.md" + }, + { + "text": "Email Sending", + "items": [ + { + "text": "Email Sending System", + "path": "Emailing.md" + }, + { + "text": "MailKit Integration", + "path": "MailKit.md" + } + ] + }, + { + "text": "Event Bus", + "items": [ + { + "text": "Overall", + "path": "Event-Bus.md" + }, + { + "text": "Local Event Bus", + "path": "Local-Event-Bus.md" + }, + { + "text": "Distributed Event Bus", + "path": "Distributed-Event-Bus.md", + "items": [ + { + "text": "RabbitMQ Integration", + "path": "Distributed-Event-Bus-RabbitMQ-Integration.md" + }, + { + "text": "Kafka Integration", + "path": "Distributed-Event-Bus-Kafka-Integration.md" + }, + { + "text": "Rebus Integration", + "path": "Distributed-Event-Bus-Rebus-Integration.md" + } + ] + } + ] + }, + { + "text": "Features", + "path": "Features.md" }, { "text": "GUID Generation", "path": "Guid-Generation.md" }, { - "text": "Timing", - "path": "Timing.md" - } - ] - }, - { - "text": "Multi Tenancy", - "path": "Multi-Tenancy.md" - }, - { - "text": "Module Development", - "items": [ + "text": "Object to Object Mapping", + "path": "Object-To-Object-Mapping.md" + }, { - "text": "Basics", - "path": "Module-Development-Basics.md" + "text": "Text Templating", + "path": "Text-Templating.md" }, { - "text": "Plug-In Modules" + "text": "Timing", + "path": "Timing.md" }, { - "text": "Best Practices", - "path": "Best-Practices/Index.md" + "text": "Virtual File System", + "path": "Virtual-File-System.md" } ] }, { - "text": "Domain Driven Design", + "text": "Architecture", "items": [ { - "text": "Overall", - "path": "Domain-Driven-Design.md" - }, - { - "text": "Domain Layer", + "text": "Modularity", "items": [ { - "text": "Entities & Aggregate Roots", - "path": "Entities.md" + "text": "Basics", + "path": "Module-Development-Basics.md" }, { - "text": "Value Objects" + "text": "Plug-In Modules" }, { - "text": "Repositories", - "path": "Repositories.md" - }, - { - "text": "Domain Services" + "text": "Customizing the Application Modules", + "path": "Customizing-Application-Modules-Guide.md", + "items": [ + { + "text": "Extending Entities", + "path": "Customizing-Application-Modules-Extending-Entities.md" + }, + { + "text": "Overriding Services", + "path": "Customizing-Application-Modules-Overriding-Services.md" + }, + { + "text": "Overriding the User Interface", + "path": "Customizing-Application-Modules-Overriding-User-Interface.md" + } + ] }, { - "text": "Specifications", - "path": "Specifications.md" + "text": "Best Practices", + "path": "Best-Practices/Index.md" } ] }, { - "text": "Application Layer", + "text": "Domain Driven Design", "items": [ { - "text": "Application Services", - "path": "Application-Services.md" + "text": "Overall", + "path": "Domain-Driven-Design.md" }, { - "text": "Data Transfer Objects", - "path": "Data-Transfer-Objects.md" + "text": "Domain Layer", + "items": [ + { + "text": "Entities & Aggregate Roots", + "path": "Entities.md" + }, + { + "text": "Value Objects", + "path": "Value-Objects.md" + }, + { + "text": "Repositories", + "path": "Repositories.md" + }, + { + "text": "Domain Services", + "path": "Domain-Services.md" + }, + { + "text": "Specifications", + "path": "Specifications.md" + } + ] }, { - "text": "Unit Of Work", - "path": "Unit-Of-Work.md" + "text": "Application Layer", + "items": [ + { + "text": "Application Services", + "path": "Application-Services.md" + }, + { + "text": "Data Transfer Objects", + "path": "Data-Transfer-Objects.md" + }, + { + "text": "Unit Of Work", + "path": "Unit-Of-Work.md" + } + ] + }, + { + "text": "Guide: Implementing DDD", + "path": "Domain-Driven-Design-Implementation-Guide.md" } ] + }, + { + "text": "Multi Tenancy", + "path": "Multi-Tenancy.md" + }, + { + "text": "Microservices", + "path": "Microservice-Architecture.md" } ] }, @@ -392,20 +466,44 @@ "text": "User Interface", "items": [ { - "text": "ASP.NET Core MVC / Razor Pages", + "text": "MVC / Razor Pages", "items": [ { - "text": "Client Side Package Management", - "path": "UI/AspNetCore/Client-Side-Package-Management.md" + "text": "Overall", + "path": "UI/AspNetCore/Overall.md" }, { - "text": "Bundling & Minification", - "path": "UI/AspNetCore/Bundling-Minification.md" + "text": "Navigation / Menus", + "path": "UI/AspNetCore/Navigation-Menu.md" }, { "text": "Forms & Validation", "path": "UI/AspNetCore/Forms-Validation.md" }, + { + "text": "Modals", + "path": "UI/AspNetCore/Modals.md" + }, + { + "text": "Data Tables", + "path": "UI/AspNetCore/Data-Tables.md" + }, + { + "text": "Page Alerts", + "path": "UI/AspNetCore/Page-Alerts.md" + }, + { + "text": "Dynamic JavaScript API Client Proxies", + "path": "UI/AspNetCore/Dynamic-JavaScript-Proxies.md" + }, + { + "text": "Client Side Package Management", + "path": "UI/AspNetCore/Client-Side-Package-Management.md" + }, + { + "text": "Bundling & Minification", + "path": "UI/AspNetCore/Bundling-Minification.md" + }, { "text": "Tag Helpers", "path": "UI/AspNetCore/Tag-Helpers/Index.md", @@ -424,9 +522,96 @@ "text": "Widgets", "path": "UI/AspNetCore/Widgets.md" }, + { + "text": "Toolbars", + "path": "UI/AspNetCore/Toolbars.md" + }, + { + "text": "Page Header", + "path": "UI/AspNetCore/Page-Header.md" + }, + { + "text": "Branding", + "path": "UI/AspNetCore/Branding.md" + }, + { + "text": "Layout Hooks", + "path": "UI/AspNetCore/Layout-Hooks.md" + }, + { + "text": "Testing", + "path": "UI/AspNetCore/Testing.md" + }, { "text": "Theming", - "path": "UI/AspNetCore/Theming.md" + "path": "UI/AspNetCore/Theming.md", + "items": [ + { + "text": "The Basic Theme", + "path": "UI/AspNetCore/Basic-Theme.md" + } + ] + }, + { + "text": "JavaScript API", + "items": [ + { + "text": "Overall", + "path": "UI/AspNetCore/JavaScript-API/Index.md" + }, + { + "text": "Localization", + "path": "UI/AspNetCore/JavaScript-API/Localization.md" + }, + { + "text": "Auth", + "path": "UI/AspNetCore/JavaScript-API/Auth.md" + }, + { + "text": "Current User", + "path": "UI/AspNetCore/JavaScript-API/CurrentUser.md" + }, + { + "text": "Settings", + "path": "UI/AspNetCore/JavaScript-API/Settings.md" + }, + { + "text": "Features", + "path": "UI/AspNetCore/JavaScript-API/Features.md" + }, + { + "text": "AJAX", + "path": "UI/AspNetCore/JavaScript-API/Ajax.md" + }, + { + "text": "Message", + "path": "UI/AspNetCore/JavaScript-API/Message.md" + }, + { + "text": "Notify", + "path": "UI/AspNetCore/JavaScript-API/Notify.md" + }, + { + "text": "Block/Busy", + "path": "UI/AspNetCore/JavaScript-API/Block-Busy.md" + }, + { + "text": "Events", + "path": "UI/AspNetCore/JavaScript-API/Events.md" + }, + { + "text": "DOM", + "path": "UI/AspNetCore/JavaScript-API/DOM.md" + }, + { + "text": "Logging", + "path": "UI/AspNetCore/JavaScript-API/Logging.md" + }, + { + "text": "Resource Loader", + "path": "UI/AspNetCore/JavaScript-API/ResourceLoader.md" + } + ] }, { "text": "Customize/Extend the UI", @@ -442,23 +627,64 @@ "path": "UI/Blazor/Overall.md" }, { - "text": "Services", + "text": "Navigation / Menu", + "path": "UI/Blazor/Navigation-Menu.md" + }, + { + "text": "Localization", + "path": "UI/Blazor/Localization.md" + }, + { + "text": "Settings", + "path": "UI/Blazor/Settings.md" + }, + { + "text": "Notification", + "path": "UI/Blazor/Notification.md" + }, + { + "text": "Message", + "path": "UI/Blazor/Message.md" + }, + { + "text": "Theming", + "path": "UI/Blazor/Theming.md", "items": [ { - "text": "Overall", - "path": "UI/Blazor/Services/Notification.md" + "text": "The Basic Theme", + "path": "UI/Blazor/Basic-Theme.md" } ] + }, + { + "text": "Toolbars", + "path": "UI/Blazor/Toolbars.md" + }, + { + "text": "Page Alerts", + "path": "UI/Blazor/Page-Alerts.md" + }, + { + "text": "Branding", + "path": "UI/Blazor/Branding.md" + }, + { + "text": "Customization / Overriding Components", + "path": "UI/Blazor/Customization-Overriding-Components.md" + }, + { + "text": "Global Scripts & Styles", + "path": "UI/Blazor/Global-Scripts-Styles.md" + }, + { + "text": "Authentication", + "path": "UI/Blazor/Authentication.md" } ] }, { "text": "Angular", "items": [ - { - "text": "Migration Guide v2.x to v3", - "path": "UI/Angular/Migration-Guide-v3.md" - }, { "text": "Quick Start", "path": "UI/Angular/Quick-Start.md" @@ -488,8 +714,8 @@ "text": "Core Functionality", "items": [ { - "text": "Config State", - "path": "UI/Angular/Config-State.md" + "text": "Config State Service", + "path": "UI/Angular/Config-State-Service.md" }, { "text": "HTTP Requests", @@ -499,6 +725,18 @@ "text": "Localization", "path": "UI/Angular/Localization.md" }, + { + "text": "Form Validation", + "path": "UI/Angular/Form-Validation.md" + }, + { + "text": "Settings", + "path": "UI/Angular/Settings.md" + }, + { + "text": "Features", + "path": "UI/Angular/Features.md" + }, { "text": "Permission Management", "path": "UI/Angular/Permission-Management.md" @@ -598,57 +836,44 @@ "path": "Data-Access.md" }, { - "text": "Connection Strings", - "path": "Connection-Strings.md" - }, - { - "text": "Database Providers", + "text": "Entity Framework Core", + "path": "Entity-Framework-Core.md", "items": [ { - "text": "Entity Framework Core", - "path": "Entity-Framework-Core.md", + "text": "Database Migrations", + "path": "Entity-Framework-Core-Migrations.md" + }, + { + "text": "Switch DBMS", + "path": "Entity-Framework-Core-Other-DBMS.md", "items": [ { - "text": "Database Migrations", - "path": "Entity-Framework-Core-Migrations.md" - }, - { - "text": "Switch DBMS", - "path": "Entity-Framework-Core-Other-DBMS.md", - "items": [ - { - "text": "To MySQL", - "path": "Entity-Framework-Core-MySQL.md" - }, - { - "text": "To PostgreSQL", - "path": "Entity-Framework-Core-PostgreSQL.md" - }, - { - "text": "To Oracle", - "path": "Entity-Framework-Core-Oracle.md" - }, - { - "text": "To SQLite", - "path": "Entity-Framework-Core-SQLite.md" - } - ] + "text": "To MySQL", + "path": "Entity-Framework-Core-MySQL.md" + }, + { + "text": "To PostgreSQL", + "path": "Entity-Framework-Core-PostgreSQL.md" + }, + { + "text": "To Oracle", + "path": "Entity-Framework-Core-Oracle.md" + }, + { + "text": "To SQLite", + "path": "Entity-Framework-Core-SQLite.md" } ] - }, - { - "text": "MongoDB", - "path": "MongoDB.md" - }, - { - "text": "Dapper", - "path": "Dapper.md" } ] }, { - "text": "Data Seeding", - "path": "Data-Seeding.md" + "text": "MongoDB", + "path": "MongoDB.md" + }, + { + "text": "Dapper", + "path": "Dapper.md" } ] }, @@ -662,107 +887,136 @@ ] }, { - "text": "Background", + "text": "Testing", + "path": "Testing.md" + }, + { + "text": "Samples", "items": [ { - "text": "Background Jobs", - "path": "Background-Jobs.md", - "items": [ - { - "text": "Hangfire Integration", - "path": "Background-Jobs-Hangfire.md" - }, - { - "text": "RabbitMQ Integration", - "path": "Background-Jobs-RabbitMq.md" - }, - { - "text": "Quartz Integration", - "path": "Background-Jobs-Quartz.md" - } - ] + "text": "All Samples", + "path": "Samples/Index.md" }, { - "text": "Background Workers", - "path": "Background-Workers.md", - "items": [ - { - "text": "Quartz Integration", - "path": "Background-Workers-Quartz.md" - } - ] + "text": "Microservice Demo", + "path": "Samples/Microservice-Demo.md" } ] }, { - "text": "Startup Templates", + "text": "Application Modules", "items": [ { "text": "Overall", - "path": "Startup-Templates/Index.md" + "path": "Modules/Index.md" }, { - "text": "Application", - "path": "Startup-Templates/Application.md" + "text": "Account", + "path": "Modules/Account.md" }, { - "text": "Module", - "path": "Startup-Templates/Module.md" + "text": "Audit Logging", + "path": "Modules/Audit-Logging.md" }, { - "text": "Console", - "path": "Startup-Templates/Console.md" + "text": "Background Jobs", + "path": "Modules/Background-Jobs.md" + }, + { + "text": "Blogging", + "path": "Modules/Blogging.md" + }, + { + "text": "Client Simulation", + "path": "Modules/Client-Simulation.md" + }, + { + "text": "CMS Kit", + "path": "Modules/Cms-Kit.md" + }, + { + "text": "Docs", + "path": "Modules/Docs.md" + }, + { + "text": "Feature Management", + "path": "Modules/Feature-Management.md" + }, + { + "text": "Identity", + "path": "Modules/Identity.md" + }, + { + "text": "IdentityServer", + "path": "Modules/IdentityServer.md" + }, + { + "text": "Permission Management", + "path": "Modules/Permission-Management.md" + }, + { + "text": "Setting Management", + "path": "Modules/Setting-Management.md" + }, + { + "text": "Tenant Management", + "path": "Modules/Tenant-Management.md" + }, + { + "text": "Users", + "path": "Modules/Users.md" + }, + { + "text": "Virtual File Explorer", + "path": "Modules/Virtual-File-Explorer.md" } ] }, { - "text": "Samples", + "text": "Release Information", "items": [ { - "text": "All Samples", - "path": "Samples/Index.md" + "text": "Upgrading", + "path": "Upgrading.md" }, { - "text": "Microservice Demo", - "path": "Samples/Microservice-Demo.md" + "text": "Official Packages", + "path": "https://abp.io/packages" + }, + { + "text": "Preview Releases", + "path": "Previews.md" + }, + { + "text": "Nightly Builds", + "path": "Nightly-Builds.md" + }, + { + "text": "Road Map", + "path": "Road-Map.md" + }, + { + "text": "Migration Guides", + "path": "Migration-Guides/Index.md" } ] }, { - "text": "Application Modules", - "path": "Modules/Index.md" - }, - { - "text": "Microservice Architecture", - "path": "Microservice-Architecture.md" - }, - { - "text": "Preview Releases", - "path": "Previews.md" - }, - { - "text": "Nightly Builds", - "path": "Nightly-Builds.md" - }, - { - "text": "Road Map", - "path": "Road-Map.md" - }, - { - "text": "Upgrading", - "path": "Upgrading.md" + "text": "Reference", + "items": [ + { + "text": "CLI", + "path": "CLI.md" + }, + { + "text": "API Documentation", + "path": "{ApiDocumentationUrl}" + } + ] }, { "text": "Contribution Guide", "path": "Contribution/Index.md" - }, - { - "text": "API Documentation", - "path": "{ApiDocumentationUrl}" - }, - { - "text": "Official Packages", - "path": "https://abp.io/packages" } ] } diff --git a/docs/en/images/ajax-error.png b/docs/en/images/ajax-error.png new file mode 100644 index 0000000000..2b9bc2bb37 Binary files /dev/null and b/docs/en/images/ajax-error.png differ diff --git a/docs/en/images/aspnetcore-web-tests-in-solution.png b/docs/en/images/aspnetcore-web-tests-in-solution.png new file mode 100644 index 0000000000..12fca58139 Binary files /dev/null and b/docs/en/images/aspnetcore-web-tests-in-solution.png differ diff --git a/docs/en/images/basic-theme-account-layout.png b/docs/en/images/basic-theme-account-layout.png new file mode 100644 index 0000000000..bccd0e20cc Binary files /dev/null and b/docs/en/images/basic-theme-account-layout.png differ diff --git a/docs/en/images/basic-theme-application-layout-blazor.png b/docs/en/images/basic-theme-application-layout-blazor.png new file mode 100644 index 0000000000..f01becad07 Binary files /dev/null and b/docs/en/images/basic-theme-application-layout-blazor.png differ diff --git a/docs/en/images/basic-theme-application-layout-parts.png b/docs/en/images/basic-theme-application-layout-parts.png new file mode 100644 index 0000000000..5e8f9147a9 Binary files /dev/null and b/docs/en/images/basic-theme-application-layout-parts.png differ diff --git a/docs/en/images/basic-theme-application-layout.png b/docs/en/images/basic-theme-application-layout.png new file mode 100644 index 0000000000..353e294056 Binary files /dev/null and b/docs/en/images/basic-theme-application-layout.png differ diff --git a/docs/en/images/basic-wpf-application-solution.png b/docs/en/images/basic-wpf-application-solution.png new file mode 100644 index 0000000000..5943acd93f Binary files /dev/null and b/docs/en/images/basic-wpf-application-solution.png differ diff --git a/docs/en/images/blazor-message-confirm.png b/docs/en/images/blazor-message-confirm.png new file mode 100644 index 0000000000..fe03620283 Binary files /dev/null and b/docs/en/images/blazor-message-confirm.png differ diff --git a/docs/en/images/blazor-message-error.png b/docs/en/images/blazor-message-error.png new file mode 100644 index 0000000000..5192eae1e9 Binary files /dev/null and b/docs/en/images/blazor-message-error.png differ diff --git a/docs/en/images/blazor-message-success.png b/docs/en/images/blazor-message-success.png new file mode 100644 index 0000000000..592fac8b7d Binary files /dev/null and b/docs/en/images/blazor-message-success.png differ diff --git a/docs/en/images/blazor-notification-bell-component.png b/docs/en/images/blazor-notification-bell-component.png new file mode 100644 index 0000000000..65934ec24b Binary files /dev/null and b/docs/en/images/blazor-notification-bell-component.png differ diff --git a/docs/en/images/blazor-notification-success.png b/docs/en/images/blazor-notification-success.png new file mode 100644 index 0000000000..d68dcf47d8 Binary files /dev/null and b/docs/en/images/blazor-notification-success.png differ diff --git a/docs/en/images/blazor-page-alert-example.png b/docs/en/images/blazor-page-alert-example.png new file mode 100644 index 0000000000..799826e57f Binary files /dev/null and b/docs/en/images/blazor-page-alert-example.png differ diff --git a/docs/en/images/bookstore-branding-blazor.png b/docs/en/images/bookstore-branding-blazor.png new file mode 100644 index 0000000000..74ddf35f0f Binary files /dev/null and b/docs/en/images/bookstore-branding-blazor.png differ diff --git a/docs/en/images/bookstore-logo-blazor.png b/docs/en/images/bookstore-logo-blazor.png new file mode 100644 index 0000000000..4e01569813 Binary files /dev/null and b/docs/en/images/bookstore-logo-blazor.png differ diff --git a/docs/en/images/branding-appname.png b/docs/en/images/branding-appname.png new file mode 100644 index 0000000000..9300ad2c7f Binary files /dev/null and b/docs/en/images/branding-appname.png differ diff --git a/docs/en/images/branding-nobrand.png b/docs/en/images/branding-nobrand.png new file mode 100644 index 0000000000..1fdf78472b Binary files /dev/null and b/docs/en/images/branding-nobrand.png differ diff --git a/docs/en/images/breadcrumbs-example.png b/docs/en/images/breadcrumbs-example.png new file mode 100644 index 0000000000..17ae5f8ba5 Binary files /dev/null and b/docs/en/images/breadcrumbs-example.png differ diff --git a/docs/en/images/datatables-custom-render-date.png b/docs/en/images/datatables-custom-render-date.png new file mode 100644 index 0000000000..344237aea7 Binary files /dev/null and b/docs/en/images/datatables-custom-render-date.png differ diff --git a/docs/en/images/datatables-default-render-date.png b/docs/en/images/datatables-default-render-date.png new file mode 100644 index 0000000000..430c889d2f Binary files /dev/null and b/docs/en/images/datatables-default-render-date.png differ diff --git a/docs/en/images/datatables-example.png b/docs/en/images/datatables-example.png new file mode 100644 index 0000000000..ef3e74576b Binary files /dev/null and b/docs/en/images/datatables-example.png differ diff --git a/docs/en/images/datatables-row-actions-confirmation.png b/docs/en/images/datatables-row-actions-confirmation.png new file mode 100644 index 0000000000..9be8433f9c Binary files /dev/null and b/docs/en/images/datatables-row-actions-confirmation.png differ diff --git a/docs/en/images/datatables-row-actions-icon.png b/docs/en/images/datatables-row-actions-icon.png new file mode 100644 index 0000000000..70111fc1ac Binary files /dev/null and b/docs/en/images/datatables-row-actions-icon.png differ diff --git a/docs/en/images/datatables-row-actions.png b/docs/en/images/datatables-row-actions.png new file mode 100644 index 0000000000..4eae0f098a Binary files /dev/null and b/docs/en/images/datatables-row-actions.png differ diff --git a/docs/en/images/db-options.png b/docs/en/images/db-options.png new file mode 100644 index 0000000000..d9dc2ed0f4 Binary files /dev/null and b/docs/en/images/db-options.png differ diff --git a/docs/en/images/ddd-microservice-simple.png b/docs/en/images/ddd-microservice-simple.png new file mode 100644 index 0000000000..1217b243c8 Binary files /dev/null and b/docs/en/images/ddd-microservice-simple.png differ diff --git a/docs/en/images/domain-driven-design-aggregate-keep-small.png b/docs/en/images/domain-driven-design-aggregate-keep-small.png new file mode 100644 index 0000000000..56f805ebbe Binary files /dev/null and b/docs/en/images/domain-driven-design-aggregate-keep-small.png differ diff --git a/docs/en/images/domain-driven-design-clean-architecture.png b/docs/en/images/domain-driven-design-clean-architecture.png new file mode 100644 index 0000000000..4ab6d2c93b Binary files /dev/null and b/docs/en/images/domain-driven-design-clean-architecture.png differ diff --git a/docs/en/images/domain-driven-design-domain-vs-application-logic.png b/docs/en/images/domain-driven-design-domain-vs-application-logic.png new file mode 100644 index 0000000000..e370cba71e Binary files /dev/null and b/docs/en/images/domain-driven-design-domain-vs-application-logic.png differ diff --git a/docs/en/images/domain-driven-design-entity-primary-keys.png b/docs/en/images/domain-driven-design-entity-primary-keys.png new file mode 100644 index 0000000000..7ee0096222 Binary files /dev/null and b/docs/en/images/domain-driven-design-entity-primary-keys.png differ diff --git a/docs/en/images/domain-driven-design-example-domain-schema.png b/docs/en/images/domain-driven-design-example-domain-schema.png new file mode 100644 index 0000000000..fe3075b141 Binary files /dev/null and b/docs/en/images/domain-driven-design-example-domain-schema.png differ diff --git a/docs/en/images/domain-driven-design-issue-aggregate-diagram.png b/docs/en/images/domain-driven-design-issue-aggregate-diagram.png new file mode 100644 index 0000000000..244564126a Binary files /dev/null and b/docs/en/images/domain-driven-design-issue-aggregate-diagram.png differ diff --git a/docs/en/images/domain-driven-design-layers.png b/docs/en/images/domain-driven-design-layers.png new file mode 100644 index 0000000000..f2fc9af097 Binary files /dev/null and b/docs/en/images/domain-driven-design-layers.png differ diff --git a/docs/en/images/domain-driven-design-multiple-applications.png b/docs/en/images/domain-driven-design-multiple-applications.png new file mode 100644 index 0000000000..6db4fc6443 Binary files /dev/null and b/docs/en/images/domain-driven-design-multiple-applications.png differ diff --git a/docs/en/images/domain-driven-design-project-relations.png b/docs/en/images/domain-driven-design-project-relations.png new file mode 100644 index 0000000000..b7878d1385 Binary files /dev/null and b/docs/en/images/domain-driven-design-project-relations.png differ diff --git a/docs/en/images/domain-driven-design-reference-by-id-sample.png b/docs/en/images/domain-driven-design-reference-by-id-sample.png new file mode 100644 index 0000000000..48a1913654 Binary files /dev/null and b/docs/en/images/domain-driven-design-reference-by-id-sample.png differ diff --git a/docs/en/images/domain-driven-design-vs-solution.png b/docs/en/images/domain-driven-design-vs-solution.png new file mode 100644 index 0000000000..ef0f51a418 Binary files /dev/null and b/docs/en/images/domain-driven-design-vs-solution.png differ diff --git a/docs/en/images/domain-driven-design-web-request-flow.png b/docs/en/images/domain-driven-design-web-request-flow.png new file mode 100644 index 0000000000..a9cb98e01f Binary files /dev/null and b/docs/en/images/domain-driven-design-web-request-flow.png differ diff --git a/docs/en/images/example-global-styles.png b/docs/en/images/example-global-styles.png new file mode 100644 index 0000000000..04232aa62d Binary files /dev/null and b/docs/en/images/example-global-styles.png differ diff --git a/docs/en/images/issue-first-test.png b/docs/en/images/issue-first-test.png new file mode 100644 index 0000000000..b2be1aa8eb Binary files /dev/null and b/docs/en/images/issue-first-test.png differ diff --git a/docs/en/images/issue-list.png b/docs/en/images/issue-list.png new file mode 100644 index 0000000000..96e9010ed6 Binary files /dev/null and b/docs/en/images/issue-list.png differ diff --git a/docs/en/images/js-message-confirm.png b/docs/en/images/js-message-confirm.png new file mode 100644 index 0000000000..876ae8d98e Binary files /dev/null and b/docs/en/images/js-message-confirm.png differ diff --git a/docs/en/images/js-message-error.png b/docs/en/images/js-message-error.png new file mode 100644 index 0000000000..fd8abb1d7e Binary files /dev/null and b/docs/en/images/js-message-error.png differ diff --git a/docs/en/images/js-message-success.png b/docs/en/images/js-message-success.png new file mode 100644 index 0000000000..bbf418a37c Binary files /dev/null and b/docs/en/images/js-message-success.png differ diff --git a/docs/en/images/js-notify-success.png b/docs/en/images/js-notify-success.png new file mode 100644 index 0000000000..04489bc7ce Binary files /dev/null and b/docs/en/images/js-notify-success.png differ diff --git a/docs/en/images/lepton-theme-account-layout.png b/docs/en/images/lepton-theme-account-layout.png new file mode 100644 index 0000000000..e627ba3eae Binary files /dev/null and b/docs/en/images/lepton-theme-account-layout.png differ diff --git a/docs/en/images/lepton-theme-application-layout.png b/docs/en/images/lepton-theme-application-layout.png new file mode 100644 index 0000000000..3d89929abc Binary files /dev/null and b/docs/en/images/lepton-theme-application-layout.png differ diff --git a/docs/en/images/lepton-theme-blazor-layout.png b/docs/en/images/lepton-theme-blazor-layout.png new file mode 100644 index 0000000000..e4211b367e Binary files /dev/null and b/docs/en/images/lepton-theme-blazor-layout.png differ diff --git a/docs/en/images/modal-example-product-create.png b/docs/en/images/modal-example-product-create.png new file mode 100644 index 0000000000..89ea0226ef Binary files /dev/null and b/docs/en/images/modal-example-product-create.png differ diff --git a/docs/en/images/modal-example-product-info.png b/docs/en/images/modal-example-product-info.png new file mode 100644 index 0000000000..5d037c1125 Binary files /dev/null and b/docs/en/images/modal-example-product-info.png differ diff --git a/docs/en/images/modal-manager-cancel-warning.png b/docs/en/images/modal-manager-cancel-warning.png new file mode 100644 index 0000000000..fc00902e0f Binary files /dev/null and b/docs/en/images/modal-manager-cancel-warning.png differ diff --git a/docs/en/images/modal-manager-example-modal.png b/docs/en/images/modal-manager-example-modal.png new file mode 100644 index 0000000000..867c6d410e Binary files /dev/null and b/docs/en/images/modal-manager-example-modal.png differ diff --git a/docs/en/images/modal-manager-validation.png b/docs/en/images/modal-manager-validation.png new file mode 100644 index 0000000000..516a178e66 Binary files /dev/null and b/docs/en/images/modal-manager-validation.png differ diff --git a/docs/en/images/modal-page-on-rider.png b/docs/en/images/modal-page-on-rider.png new file mode 100644 index 0000000000..522885489d Binary files /dev/null and b/docs/en/images/modal-page-on-rider.png differ diff --git a/docs/en/images/nav-main-menu-administration.png b/docs/en/images/nav-main-menu-administration.png new file mode 100644 index 0000000000..21ad977264 Binary files /dev/null and b/docs/en/images/nav-main-menu-administration.png differ diff --git a/docs/en/images/nav-main-menu.png b/docs/en/images/nav-main-menu.png new file mode 100644 index 0000000000..2784c035c2 Binary files /dev/null and b/docs/en/images/nav-main-menu.png differ diff --git a/docs/en/images/page-alert-account-layout.png b/docs/en/images/page-alert-account-layout.png new file mode 100644 index 0000000000..2442cb5d14 Binary files /dev/null and b/docs/en/images/page-alert-account-layout.png differ diff --git a/docs/en/images/page-alert-example.png b/docs/en/images/page-alert-example.png new file mode 100644 index 0000000000..266671757a Binary files /dev/null and b/docs/en/images/page-alert-example.png differ diff --git a/docs/en/images/product-create-modal-page-on-rider.png b/docs/en/images/product-create-modal-page-on-rider.png new file mode 100644 index 0000000000..01cf93eaf0 Binary files /dev/null and b/docs/en/images/product-create-modal-page-on-rider.png differ diff --git a/docs/en/images/solution-test-projects.png b/docs/en/images/solution-test-projects.png new file mode 100644 index 0000000000..e51c368e9f Binary files /dev/null and b/docs/en/images/solution-test-projects.png differ diff --git a/docs/en/images/ui-busy.png b/docs/en/images/ui-busy.png new file mode 100644 index 0000000000..63a1d7d74a Binary files /dev/null and b/docs/en/images/ui-busy.png differ diff --git a/docs/en/images/ui-options.png b/docs/en/images/ui-options.png new file mode 100644 index 0000000000..bd211a8914 Binary files /dev/null and b/docs/en/images/ui-options.png differ diff --git a/docs/en/images/user-menu.png b/docs/en/images/user-menu.png new file mode 100644 index 0000000000..af0671dbdc Binary files /dev/null and b/docs/en/images/user-menu.png differ diff --git a/docs/en/images/vs-run-tests-in-parallel.png b/docs/en/images/vs-run-tests-in-parallel.png new file mode 100644 index 0000000000..765cba5100 Binary files /dev/null and b/docs/en/images/vs-run-tests-in-parallel.png differ diff --git a/docs/en/images/vs-startup-template-tests.png b/docs/en/images/vs-startup-template-tests.png new file mode 100644 index 0000000000..f16d79a4c7 Binary files /dev/null and b/docs/en/images/vs-startup-template-tests.png differ diff --git a/docs/en/images/vs-test-explorer.png b/docs/en/images/vs-test-explorer.png new file mode 100644 index 0000000000..e225ee5e92 Binary files /dev/null and b/docs/en/images/vs-test-explorer.png differ diff --git a/docs/zh-Hans/Application-Services.md b/docs/zh-Hans/Application-Services.md index 6bb18daa37..e68217a94d 100644 --- a/docs/zh-Hans/Application-Services.md +++ b/docs/zh-Hans/Application-Services.md @@ -353,12 +353,12 @@ public class DistrictAppService { } - protected override async Task DeleteByIdAsync(DistrictKey id) + protected async override Task DeleteByIdAsync(DistrictKey id) { await Repository.DeleteAsync(d => d.CityId == id.CityId && d.Name == id.Name); } - protected override async Task GetEntityByIdAsync(DistrictKey id) + protected async override Task GetEntityByIdAsync(DistrictKey id) { return await AsyncQueryableExecuter.FirstOrDefaultAsync( Repository.Where(d => d.CityId == id.CityId && d.Name == id.Name) diff --git a/docs/zh-Hans/Authentication/Social-External-Logins.md b/docs/zh-Hans/Authentication/Social-External-Logins.md index 55ab97374c..a1cdbb86ce 100644 --- a/docs/zh-Hans/Authentication/Social-External-Logins.md +++ b/docs/zh-Hans/Authentication/Social-External-Logins.md @@ -1,33 +1,3 @@ # 社交/外部登录 - -[帐户模块](../Modules/Account.md)已配置为开箱即用的处理社交或外部登录. 你可以按照ASP.NET Core文档向你的应用程序添加社交/外部登录提供程序. - -## 示例: Facebook 认证 - -按照[ASP.NET Core Facebook集成文档](https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/social/facebook-logins)向你应用程序添加Facebook登录. - -#### 添加NuGet包 - -添加[Microsoft.AspNetCore.Authentication.Facebook]包到你的项目. 基于你的架构,可能是 `.Web`,`.IdentityServer`(对于分层启动)或 `.Host` 项目. - -#### 配置提供程序 - -在你模块的 `ConfigureServices` 方法中使用 `.AddFacebook(...)` 扩展方法来配置客户端: - -````csharp -context.Services.AddAuthentication() - .AddFacebook(facebook => - { - facebook.AppId = "..."; - facebook.AppSecret = "..."; - facebook.Scope.Add("email"); - facebook.Scope.Add("public_profile"); - }); -```` - -> 最佳实践是使用 `appsettings.json` 或ASP.NET Core用户机密系统来存储你的凭据,而不是像这样硬编码值. 请参阅[微软](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins)文档了解如何使用用户机密. - -## Angular UI - -从v3.1开始,Angular UI使用授权码流程(作为最佳实践)通过重定向到MVC UI登录页面来对用户进行身份验证. 因此,即使你使用的是Angular UI,社交/外部登录集成也与上面说明的相同.并且可以开箱即用. \ No newline at end of file +> 文档已经移动其他位置. 参阅[账户模块](../Modules/Account.md)文档. \ No newline at end of file diff --git a/docs/zh-Hans/Authorization.md b/docs/zh-Hans/Authorization.md index 96caae1404..db0dfdb654 100644 --- a/docs/zh-Hans/Authorization.md +++ b/docs/zh-Hans/Authorization.md @@ -343,7 +343,7 @@ public class SystemAdminPermissionValueProvider : PermissionValueProvider public override string Name => "SystemAdmin"; - public override async Task + public async override Task CheckAsync(PermissionValueCheckContext context) { if (context.Principal?.FindFirst("User_Type")?.Value == "SystemAdmin") diff --git a/docs/zh-Hans/Background-Workers.md b/docs/zh-Hans/Background-Workers.md index 1daedde384..26bafed2da 100644 --- a/docs/zh-Hans/Background-Workers.md +++ b/docs/zh-Hans/Background-Workers.md @@ -54,7 +54,7 @@ public class PassiveUserCheckerWorker : AsyncPeriodicBackgroundWorkerBase Timer.Period = 600000; //10 minutes } - protected override async Task DoWorkAsync( + protected async override Task DoWorkAsync( PeriodicBackgroundWorkerContext workerContext) { Logger.LogInformation("Starting: Setting status of inactive users..."); diff --git a/docs/zh-Hans/Blob-Storing.md b/docs/zh-Hans/Blob-Storing.md index 99688ca47a..c233f3359e 100644 --- a/docs/zh-Hans/Blob-Storing.md +++ b/docs/zh-Hans/Blob-Storing.md @@ -21,7 +21,7 @@ ABP框架已经有以下存储提供程序的实现; * [Azure](Blob-Storing-Azure.md): 将BLOG存储在 [Azure BLOB storage](https://azure.microsoft.com/en-us/services/storage/blobs/)中. * [Aliyun](Blob-Storing-Aliyun.md): 将BLOB存储在[Aliyun Storage Service](https://help.aliyun.com/product/31815.html)中. * [Ninio](Blob-Storing-Minio.md): 将BLOB存储在[MinIO Object storage](https://min.io/)中. -* [Aws](Blob-Storing-Aws.md): 将BLOB存储在[Amazon Simple Storage Service](https://min.io/)中. +* [Aws](Blob-Storing-Aws.md): 将BLOB存储在[Amazon Simple Storage Service](https://aws.amazon.com/s3/)中. 以后会实现更多的提供程序,你可以为自己喜欢的提供程序创建[请求](https://github.com/abpframework/abp/issues/new),或者你也可以[自己实现](Blob-Storing-Custom-Provider.md)它并[贡献](Contribution/Index.md)到ABP框架. @@ -306,4 +306,4 @@ Configure(options => ## 另请参阅 -* [创建自定义BLOB存储提供程序](Blob-Storing-Custom-Provider.md) \ No newline at end of file +* [创建自定义BLOB存储提供程序](Blob-Storing-Custom-Provider.md) diff --git a/docs/zh-Hans/Blog-Posts/2020-05-08 v2_7_Release/Post.md b/docs/zh-Hans/Blog-Posts/2020-05-08 v2_7_Release/Post.md index 0f97391eb8..bc448179cc 100644 --- a/docs/zh-Hans/Blog-Posts/2020-05-08 v2_7_Release/Post.md +++ b/docs/zh-Hans/Blog-Posts/2020-05-08 v2_7_Release/Post.md @@ -121,7 +121,7 @@ ABP框架的[异常处理系统](https://docs.abp.io/en/abp/latest/Exception-Han ````csharp public class MyExceptionSubscriber : ExceptionSubscriber { - public override async Task HandleAsync(ExceptionNotificationContext context) + public async override Task HandleAsync(ExceptionNotificationContext context) { //TODO... } diff --git a/docs/zh-Hans/CLI.md b/docs/zh-Hans/CLI.md index 11f9964279..3390ce99b3 100644 --- a/docs/zh-Hans/CLI.md +++ b/docs/zh-Hans/CLI.md @@ -34,7 +34,7 @@ dotnet tool update -g Volo.Abp.Cli * **`generate-proxy`**: 生成客户端代理以使用HTTP API端点. * **`remove-proxy`**: 移除以前生成的客户端代理. * **`switch-to-preview`**: 切换到ABP框架的最新预览版本。 -* **`switch-to-preview`**: 切换解决方案所有ABP相关包为[夜间构建](Nightly-Builds.md)版本. +* **`switch-to-nightly`**: 切换解决方案所有ABP相关包为[夜间构建](Nightly-Builds.md)版本. * **`switch-to-stable`**: 切换解决方案所有ABP相关包为最新的稳定版本. * **`translate`**: 当源代码控制存储库中有多个JSON[本地化](Localization.md文件时,可简化翻译本地化文件的过程. * **`login`**: 使用你在[abp.io](https://abp.io/)的用户名和密码在你的计算机上认证. @@ -125,7 +125,7 @@ abp update [options] * `--nuget`: 仅更新的NuGet包 * `--solution-path` 或 `-sp`: 指定解决方案路径/目录. 默认使用当前目录 * `--solution-name` 或 `-sn`: 指定解决方案名称. 默认在目录中搜索`*.sln`文件. -*`--check-all`: 分别检查每个包的新版本. 默认是 `false`. +* `--check-all`: 分别检查每个包的新版本. 默认是 `false`. ### add-package diff --git a/docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md b/docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md index 21245cec16..b8abe99cdc 100644 --- a/docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md +++ b/docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md @@ -59,7 +59,6 @@ context.Services.Replace( ### 示例: 重写服务方法 ````csharp -//[RemoteService(IsEnabled = false)] // 如果你在使用动态控制器,为了避免为应用服务创建重复的控制器, 你可以禁用远程访问. [Dependency(ReplaceServices = true)] [ExposeServices(typeof(IIdentityUserAppService), typeof(IdentityUserAppService), typeof(MyIdentityUserAppService))] public class MyIdentityUserAppService : IdentityUserAppService @@ -76,7 +75,7 @@ public class MyIdentityUserAppService : IdentityUserAppService { } - public override async Task CreateAsync(IdentityUserCreateDto input) + public async override Task CreateAsync(IdentityUserCreateDto input) { if (input.PhoneNumber.IsNullOrWhiteSpace()) { @@ -109,33 +108,33 @@ public class MyIdentityUserManager : IdentityUserManager { public MyIdentityUserManager( IdentityUserStore store, - IIdentityRoleRepository roleRepository, + IIdentityRoleRepository roleRepository, IIdentityUserRepository userRepository, - IOptions optionsAccessor, + IOptions optionsAccessor, IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, + IEnumerable> userValidators, + IEnumerable> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, - ILogger logger, - ICancellationTokenProvider cancellationTokenProvider) : + ILogger logger, + ICancellationTokenProvider cancellationTokenProvider) : base(store, roleRepository, - userRepository, - optionsAccessor, - passwordHasher, - userValidators, + userRepository, + optionsAccessor, + passwordHasher, + userValidators, passwordValidators, - keyNormalizer, - errors, - services, - logger, + keyNormalizer, + errors, + services, + logger, cancellationTokenProvider) { } - public override async Task CreateAsync(IdentityUser user) + public async override Task CreateAsync(IdentityUser user) { if (user.PhoneNumber.IsNullOrWhiteSpace()) { @@ -251,8 +250,8 @@ ObjectExtensionManager.Instance .AddOrUpdateProperty( new[] { - typeof(IdentityUserDto), - typeof(IdentityUserCreateDto), + typeof(IdentityUserDto), + typeof(IdentityUserCreateDto), typeof(IdentityUserUpdateDto) }, "SocialSecurityNumber" diff --git a/docs/zh-Hans/Data-Access.md b/docs/zh-Hans/Data-Access.md index 68baa6dd87..bf3eb479c8 100644 --- a/docs/zh-Hans/Data-Access.md +++ b/docs/zh-Hans/Data-Access.md @@ -8,4 +8,8 @@ ABP框架被设计为与数据库无关, 它通过[仓储](Repositories.md)和[ * [MongoDB](MongoDB.md) * [Dapper](Dapper.md) -在以后的版本中可能会添加更多的提供程序. \ No newline at end of file +## 另请参阅 + +* [连接字符串](Connection-Strings.md) +* [种子数据](Data-Seeding.md) +* [数据过滤](Data-Filtering.md) \ No newline at end of file diff --git a/docs/zh-Hans/Data-Seeding.md b/docs/zh-Hans/Data-Seeding.md index 68f6fc1e73..97e7c7915c 100644 --- a/docs/zh-Hans/Data-Seeding.md +++ b/docs/zh-Hans/Data-Seeding.md @@ -38,31 +38,37 @@ namespace Acme.BookStore { private readonly IRepository _bookRepository; private readonly IGuidGenerator _guidGenerator; + private readonly ICurrentTenant _currentTenant; public BookStoreDataSeedContributor( IRepository bookRepository, - IGuidGenerator guidGenerator) + IGuidGenerator guidGenerator, + ICurrentTenant currentTenant) { _bookRepository = bookRepository; _guidGenerator = guidGenerator; + _currentTenant = currentTenant; } public async Task SeedAsync(DataSeedContext context) { - if (await _bookRepository.GetCountAsync() > 0) + using (_currentTenant.Change(context?.TenantId)) { - return; + if (await _bookRepository.GetCountAsync() > 0) + { + return; + } + + var book = new Book( + id: _guidGenerator.Create(), + name: "The Hitchhiker's Guide to the Galaxy", + type: BookType.ScienceFiction, + publishDate: new DateTime(1979, 10, 12), + price: 42 + ); + + await _bookRepository.InsertAsync(book); } - - var book = new Book( - id: _guidGenerator.Create(), - name: "The Hitchhiker's Guide to the Galaxy", - type: BookType.ScienceFiction, - publishDate: new DateTime(1979, 10, 12), - price: 42 - ); - - await _bookRepository.InsertAsync(book); } } } diff --git a/docs/zh-Hans/Distributed-Event-Bus-Rebus-Integration.md b/docs/zh-Hans/Distributed-Event-Bus-Rebus-Integration.md new file mode 100644 index 0000000000..409b935ace --- /dev/null +++ b/docs/zh-Hans/Distributed-Event-Bus-Rebus-Integration.md @@ -0,0 +1,63 @@ +# 分布式事件总线Rebus集成 + +> 本文解释了**如何配置[Rebus](http://mookid.dk/category/rebus/)**做为分布式总线提供程序. 参阅[分布式事件总线文档](Distributed-Event-Bus.md)了解如何使用分布式事件总线系统. + +## 安装 + +使用ABP CLI添加[Volo.Abp.EventBus.Rebus[Volo.Abp.EventBus.Rebus](https://www.nuget.org/packages/Volo.Abp.EventBus.Rebus)NuGet包到你的项目: + +* 安装[ABP CLI](https://docs.abp.io/en/abp/latest/CLI),如果你还没有安装. +* 在你想要安装 `Volo.Abp.EventBus.Rebus` 包的 `.csproj` 文件目录打开命令行(终端). +* 运行 `abp add-package Volo.Abp.EventBus.Rebus` 命令. + +如果你想要手动安装,安装[Volo.Abp.EventBus.Rebus](https://www.nuget.org/packages/Volo.Abp.EventBus.Rebus) NuGet 包到你的项目然后添加 `[DependsOn(typeof(AbpEventBusRebusModule))]` 到你的项目[模块](Module-Development-Basics.md)类. + +## 配置 + +可以使用配置使用标准的[配置系统](Configuration.md),如[选项](Options.md)类. + +`AbpRebusEventBusOptions` 类用于配置事件总线选项. + +你可以在你的[模块](Module-Development-Basics.md)的 `PreConfigureServices` 方法配置选项. + +**示例: 最小化配置** + +```csharp +PreConfigure(options => +{ + options.InputQueueName = "eventbus"; +}); +``` + +Rebus 有很多选项,你可以使用 `AbpRebusEventBusOptions` 的 `Configurer` 属性来配置. + +默认事件**存储在内存中**. 参阅[rebus文档](https://github.com/rebus-org/Rebus/wiki/Transport)了解更多信息. + +**示例: 配置存储** + +````csharp +PreConfigure(options => +{ + options.InputQueueName = "eventbus"; + options.Configurer = rebusConfigurer => + { + rebusConfigurer.Transport(t => t.UseMsmq("eventbus")); + rebusConfigurer.Subscriptions(s => s.UseJsonFile(@"subscriptions.json")); + }; +}); +```` + +你可以使用 `AbpRebusEventBusOptions` 的 `Publish` 属性来更改发布方法. + +**示例: 配置事件发布** + +````csharp +PreConfigure(options => +{ + options.InputQueueName = "eventbus"; + options.Publish = async (bus, type, data) => + { + await bus.Publish(data); + }; +}); +```` diff --git a/docs/zh-Hans/Distributed-Event-Bus.md b/docs/zh-Hans/Distributed-Event-Bus.md index 68b7466f8a..4b4203911b 100644 --- a/docs/zh-Hans/Distributed-Event-Bus.md +++ b/docs/zh-Hans/Distributed-Event-Bus.md @@ -9,6 +9,7 @@ * `LocalDistributedEventBus` 是默认实现,实现作为进程内工作的分布式事件总线. 是的!如果没有配置真正的分布式提供程序,**默认实现的工作方式与[本地事件总线](Local-Event-Bus.md)一样**. * `RabbitMqDistributedEventBus` 通过[RabbitMQ](https://www.rabbitmq.com/)实现分布式事件总线. 请参阅[RabbitMQ集成文档](Distributed-Event-Bus-RabbitMQ-Integration.md)了解如何配置它. * `KafkaDistributedEventBus` 通过[Kafka](https://kafka.apache.org/)实现分布式事件总线. 请参阅[Kafka集成文档](Distributed-Event-Bus-Kafka-Integration.md)了解如何配置它. +* `RebusDistributedEventBus` 通过[Rebus](http://mookid.dk/category/rebus/)实现分布式事件总线. 请参阅[Rebus集成文档](Distributed-Event-Bus-Rebus-Integration.md)了解如何配置它. 使用本地事件总线作为默认具有一些重要的优点. 最重要的是:它允许你编写与分布式体系结构兼容的代码. 您现在可以编写一个整体应用程序,以后可以拆分成微服务. 最好通过分布式事件而不是本地事件在边界上下文之间(或在应用程序模块之间)进行通信. diff --git a/docs/zh-Hans/Entity-Framework-Core-Migrations.md b/docs/zh-Hans/Entity-Framework-Core-Migrations.md index c6f1086540..266c0f46b0 100644 --- a/docs/zh-Hans/Entity-Framework-Core-Migrations.md +++ b/docs/zh-Hans/Entity-Framework-Core-Migrations.md @@ -235,7 +235,7 @@ public static class BackgroundJobsDbContextModelCreatingExtensions } ```` -此u还获取选项用于更改此模块的数据库表前缀和模式,但在这里并不重要. +此扩展方法还提供了选项用于更改此模块的数据库表前缀和模式,但在这里并不重要. 最终的应用程序在 `MigrationsDbContext` 类中调用扩展方法, 因此它可以确定此 `MigrationsDbContext` 维护的数据库中包含哪些模块. 如果要创建第二个数据库并将某些模块表移动到第二个数据库,则需要有第二个`MigrationsDbContext` 类,该类仅调用相关模块的扩展方法. 下一部分将详细介绍该主题. @@ -883,4 +883,4 @@ public class BookStoreDbMigratorModule : AbpModule ## 结论 -本文档说明了如何拆分数据库以及管理Entity Framework Core解决方案的数据库迁移. 简而言之,你需要为每个不同的数据库创建一个单独的迁移项目. \ No newline at end of file +本文档说明了如何拆分数据库以及管理Entity Framework Core解决方案的数据库迁移. 简而言之,你需要为每个不同的数据库创建一个单独的迁移项目. diff --git a/docs/zh-Hans/Entity-Framework-Core.md b/docs/zh-Hans/Entity-Framework-Core.md index 211ec4d65f..b5252b86c0 100644 --- a/docs/zh-Hans/Entity-Framework-Core.md +++ b/docs/zh-Hans/Entity-Framework-Core.md @@ -263,7 +263,7 @@ context.Services.AddAbpDbContext(options => 在你想要覆盖默认仓储方法对其自定义时,这一点非常需要. 例如你可能希望自定义`DeleteAsync`方法覆盖默认实现 ````csharp -public override async Task DeleteAsync( +public async override Task DeleteAsync( Guid id, bool autoSave = false, CancellationToken cancellationToken = default) @@ -365,7 +365,7 @@ public class MyRepositoryBase : EfCoreRepository where TEntity : class, IEntity { - public MyRepositoryBase(IDbContextProvider dbContextProvider) + public MyRepositoryBase(IDbContextProvider dbContextProvider) : base(dbContextProvider) { } @@ -447,4 +447,4 @@ context.Services.AddAbpDbContext(options => ## 另请参阅 -* [实体](Entities.md) \ No newline at end of file +* [实体](Entities.md) diff --git a/docs/zh-Hans/Getting-Started-AspNetCore-Application.md b/docs/zh-Hans/Getting-Started-AspNetCore-Application.md index 0334609bd3..be5e50c2bd 100644 --- a/docs/zh-Hans/Getting-Started-AspNetCore-Application.md +++ b/docs/zh-Hans/Getting-Started-AspNetCore-Application.md @@ -1,194 +1,160 @@ -## 在AspNet Core MVC Web Application中使用ABP - -本教程将介绍如何开始以最少的依赖关系开始使用ABP开发. - -通常情况下你需要下载一个 ***[启动模板](Getting-Started-AspNetCore-MVC-Template.md)*** - -### 创建一个新项目 - -1. 使用Visual Studio创建一个空的AspNet Core Web Application: - -![](images/create-new-aspnet-core-application.png) - -2. 选择空模板 - -![](images/select-empty-web-application.png) - -你可以选择其它模板,但是我想要从一个简洁的项目演示它. - -### 安装 Volo.Abp.AspNetCore.Mvc 包 - -Volo.Abp.AspNetCore.Mvc是ABP集成AspNet Core MVC的包,请安装它到你项目中: - -```` -Install-Package Volo.Abp.AspNetCore.Mvc -```` - -### 创建ABP模块 - -ABP是一个模块化框架,它需要一个**启动 (根) 模块**继承自``AbpModule``: - -````C# -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Hosting; -using Volo.Abp; -using Volo.Abp.AspNetCore.Mvc; -using Volo.Abp.Modularity; - -namespace BasicAspNetCoreApplication -{ - [DependsOn(typeof(AbpAspNetCoreMvcModule))] - public class AppModule : AbpModule - { - public override void OnApplicationInitialization( - ApplicationInitializationContext context) - { - var app = context.GetApplicationBuilder(); - var env = context.GetEnvironment(); - - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Error"); - } - - app.UseStaticFiles(); - app.UseRouting(); - app.UseConfiguredEndpoints(); - } - } -} -```` - -``AppModule`` 是应用程序启动模块的好名称(建议你的启动模块也使用这个命名). - -ABP的包定义了这个模块类,模块可以依赖其它模块.在上面的代码中 ``AppModule`` 依赖于 ``AbpAspNetCoreMvcModule`` (模块存在于Volo.Abp.AspNetCore.Mvc包中). 安装新的ABP的包后添加``DependsOn``是很常见的做法. - -我们在此模块类中配置ASP.NET Core管道,而不是Startup类中. - -### 启动类 - -接下来修改启动类集成ABP模块系统: - -````C# -using System; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace BasicAspNetCoreApplication -{ - public class Startup - { - public IServiceProvider ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - - return services.BuildServiceProviderFromFactory(); - } - - public void Configure(IApplicationBuilder app) - { - app.InitializeApplication(); - } - } -} - -```` - -修改``ConfigureServices``方法的返回值为``IServiceProvider``(默认是``void``).这个修改允许我们替换AspNet Core的依赖注入框架. (参阅下面的Autofac集成部分). ``services.AddApplication()``添加了所有模块中定义的全部服务. - -``app.InitializeApplication()`` 调用 ``Configure`` 方法初始化并启动应用程序 - -### Hello World! - -上面的应用程序没有什么功能,让我们创建一个MVC控制器实现一些功能: - -````C# -using Microsoft.AspNetCore.Mvc; -using Volo.Abp.AspNetCore.Mvc; - -namespace BasicAspNetCoreApplication.Controllers -{ - public class HomeController : AbpController - { - public IActionResult Index() - { - return Content("Hello World!"); - } - } -} - -```` - -如果运行这个应用程序你会在页面中看到"Hello World!". - -Derived ``HomeController`` from ``AbpController`` instead of standard ``Controller`` class. This is not required, but ``AbpController`` class has useful base properties and methods to make your development easier. - -从``AbpController``派生``HomeController`` 而不是继承自``Controller``类.虽然这不是强制要求,但是``AbpController``类有很多有用的有属性和方法,使你的开发更容易. - -### 使用 Autofac 依赖注入框架 - -虽然AspNet Core的依赖注入(DI)系统适用于基本要求,但Autofac提供了属性注入和方法拦截等高级功能,这些功能是ABP执行高级应用程序框架功能所必需的. - -用Autofac取代AspNet Core的DI系统并集成到ABP非常简单. - -1. 安装 Volo.Abp.Autofac 包 - -```` -Install-Package Volo.Abp.Autofac -```` - -2. 添加 ``AbpAutofacModule`` 依赖 - -````C# -[DependsOn(typeof(AbpAspNetCoreMvcModule))] -[DependsOn(typeof(AbpAutofacModule))] // 在模块上添加依赖AbpAutofacModule -public class AppModule : AbpModule -{ - ... -} -```` - -3. 修改在``Startup``类下的``services.AddApplication();``如下所示: - -````C# -services.AddApplication(options => -{ - options.UseAutofac(); // 集成 Autofac -}); -```` - -4. 更新 `Program.cs`代码, 不再使用`WebHost.CreateDefaultBuilder()`方法(因为它使用默认的DI容器): - - ````csharp -public class Program -{ - public static void Main(string[] args) - { - /* - https://github.com/aspnet/AspNetCore/issues/4206#issuecomment-445612167 - CurrentDirectoryHelpers 文件位于: \framework\src\Volo.Abp.AspNetCore.Mvc\Microsoft\AspNetCore\InProcess\CurrentDirectoryHelpers.cs - 当升级到ASP.NET Core 3.0的时候将会删除这个类. - */ - CurrentDirectoryHelpers.SetCurrentDirectory(); - - BuildWebHostInternal(args).Run(); - } - public static IWebHost BuildWebHostInternal(string[] args) => - new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIIS() - .UseIISIntegration() - .UseStartup() - .Build(); -} -```` - - -### 源码 - -从[此处](https://github.com/abpframework/abp-samples/tree/master/BasicAspNetCoreApplication)获取本教程中创建的示例项目的源代码. +# 在AspNet Core MVC Web Application中使用ABP + +本教程将介绍如何开始以最少的依赖关系开始使用ABP开发. + +通常情况下你需要下载一个 **[启动模板](Getting-Started-AspNetCore-MVC-Template.md)** + +## 创建一个新项目 + +1. 使用Visual Studio 2019 (16.4.0+)创建一个新的AspNet Core Web Application: + +![](images/create-new-aspnet-core-application-v2.png) + +2. 配置新的项目: + +![](images/select-empty-web-application-v2.png) + +3. 完成创建: + +![](images/create-aspnet-core-application.png) + + +## 安装 Volo.Abp.AspNetCore.Mvc 包 + +Volo.Abp.AspNetCore.Mvc是ABP集成AspNet Core MVC的包,请安装它到你项目中: + +```` +Install-Package Volo.Abp.AspNetCore.Mvc +```` + +## 创建ABP模块 + +ABP是一个模块化框架,它需要一个**启动 (根) 模块**继承自``AbpModule``: + +````C# +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Hosting; +using Volo.Abp; +using Volo.Abp.AspNetCore.Mvc; +using Volo.Abp.Modularity; + +namespace BasicAspNetCoreApplication +{ + [DependsOn(typeof(AbpAspNetCoreMvcModule))] + public class AppModule : AbpModule + { + public override void OnApplicationInitialization( + ApplicationInitializationContext context) + { + var app = context.GetApplicationBuilder(); + var env = context.GetEnvironment(); + + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseExceptionHandler("/Error"); + } + + app.UseStaticFiles(); + app.UseRouting(); + app.UseConfiguredEndpoints(); + } + } +} +```` + +``AppModule`` 是应用程序启动模块的好名称. + +ABP的包定义了这个模块类,模块可以依赖其它模块.在上面的代码中 ``AppModule`` 依赖于 ``AbpAspNetCoreMvcModule`` (模块存在于[Volo.Abp.AspNetCore.Mvc](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc)包中). 安装新的ABP的包后添加``DependsOn``是很常见的做法. + +我们在此模块类中配置ASP.NET Core管道,而不是Startup类中. + +### 启动类 + +接下来修改启动类集成ABP模块系统: + +````C# +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace BasicAspNetCoreApplication +{ + public class Startup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddApplication(); + } + + public void Configure(IApplicationBuilder app) + { + app.InitializeApplication(); + } + } +} + +```` + +``services.AddApplication()``添加了所有``AppModule``模块中定义的全部服务. + +``Configure``方法中的``app.InitializeApplication()``完成初始化并启动应用程序. + +## 运行应用程序! + +启动该应用,它将按预期运行. + +## 使用 Autofac 依赖注入框架 + +虽然AspNet Core的依赖注入(DI)系统适用于基本要求,但[Autofac](https://autofac.org/)提供了属性注入和方法拦截等高级功能,这些功能是ABP执行高级应用程序框架功能所必需的. + +用Autofac取代AspNet Core的DI系统并集成到ABP非常简单. + +1. 安装 [Volo.Abp.Autofac](https://www.nuget.org/packages/Volo.Abp.Autofac) 包 + +```` +Install-Package Volo.Abp.Autofac +```` + +2. 添加 ``AbpAutofacModule`` 依赖 + +````C# +[DependsOn(typeof(AbpAspNetCoreMvcModule))] +[DependsOn(typeof(AbpAutofacModule))] // 在模块上添加依赖AbpAutofacModule +public class AppModule : AbpModule +{ + ... +} +```` + +3. 修改``Program.cs``以使用Autofac: + +````C# +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace BasicAspNetCoreApplication +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }) + .UseAutofac(); // 添加这一行 + } +} +```` + +## 源码 + +从[此处](https://github.com/abpframework/abp-samples/tree/master/BasicAspNetCoreApplication)获取本教程中创建的示例项目的源代码. diff --git a/docs/zh-Hans/How-To/Customize-SignIn-Manager.md b/docs/zh-Hans/How-To/Customize-SignIn-Manager.md index 73cbcd2ce7..eea0364e6e 100644 --- a/docs/zh-Hans/How-To/Customize-SignIn-Manager.md +++ b/docs/zh-Hans/How-To/Customize-SignIn-Manager.md @@ -38,7 +38,7 @@ public class CustomSignInManager : Microsoft.AspNetCore.Identity.SignInManager GetExternalLoginInfoAsync(string expectedXsrf = null) +public async override Task GetExternalLoginInfoAsync(string expectedXsrf = null) { var auth = await Context.AuthenticateAsync(Microsoft.AspNetCore.Identity.IdentityConstants.ExternalScheme); var items = auth?.Properties?.Items; diff --git a/docs/zh-Hans/Modules/Account.md b/docs/zh-Hans/Modules/Account.md new file mode 100644 index 0000000000..2e1c838f50 --- /dev/null +++ b/docs/zh-Hans/Modules/Account.md @@ -0,0 +1,36 @@ +# 账户模块 + +该模块提供必要的UI页面与组件使用户登录和注册到应用程序. + +> 文档正在更新 + +## 社交/外部登录 + +### 示例: Facebook 认证 + +按照[ASP.NET Core Facebook集成文档](https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/social/facebook-logins)向你应用程序添加Facebook登录. + +#### 添加NuGet包 + +添加[Microsoft.AspNetCore.Authentication.Facebook]包到你的项目. 基于你的架构,可能是 `.Web`,`.IdentityServer`(对于分层启动)或 `.Host` 项目. + +#### 配置提供程序 + +在你模块的 `ConfigureServices` 方法中使用 `.AddFacebook(...)` 扩展方法来配置客户端: + +````csharp +context.Services.AddAuthentication() + .AddFacebook(facebook => + { + facebook.AppId = "..."; + facebook.AppSecret = "..."; + facebook.Scope.Add("email"); + facebook.Scope.Add("public_profile"); + }); +```` + +> 最佳实践是使用 `appsettings.json` 或ASP.NET Core用户机密系统来存储你的凭据,而不是像这样硬编码值. 请参阅[微软](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins)文档了解如何使用用户机密. + +### Angular UI + +从v3.1开始,Angular UI使用授权码流程(作为最佳实践)通过重定向到MVC UI登录页面来对用户进行身份验证. 因此,即使你使用的是Angular UI,社交/外部登录集成也与上面说明的相同.并且可以开箱即用. \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Blogging.md b/docs/zh-Hans/Modules/Blogging.md new file mode 100644 index 0000000000..cb82a640d5 --- /dev/null +++ b/docs/zh-Hans/Modules/Blogging.md @@ -0,0 +1 @@ +TODO... \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Client-Simulation.md b/docs/zh-Hans/Modules/Client-Simulation.md new file mode 100644 index 0000000000..bc5d38e814 --- /dev/null +++ b/docs/zh-Hans/Modules/Client-Simulation.md @@ -0,0 +1,3 @@ +# Client Simulation Module + +TODO \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Cms-Kit.md b/docs/zh-Hans/Modules/Cms-Kit.md new file mode 100644 index 0000000000..e13f1e585b --- /dev/null +++ b/docs/zh-Hans/Modules/Cms-Kit.md @@ -0,0 +1,3 @@ +# CMS Kit Module + +TODO \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Feature-Management.md b/docs/zh-Hans/Modules/Feature-Management.md new file mode 100644 index 0000000000..cb82a640d5 --- /dev/null +++ b/docs/zh-Hans/Modules/Feature-Management.md @@ -0,0 +1 @@ +TODO... \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Identity.md b/docs/zh-Hans/Modules/Identity.md index 5589fb367e..420b696a7c 100644 --- a/docs/zh-Hans/Modules/Identity.md +++ b/docs/zh-Hans/Modules/Identity.md @@ -2,7 +2,7 @@ 身份模块基于Microsoft Identity库用于管理[组织单元](Organization-Units.md), 角色, 用户和他们的权限. -参阅 [源码](https://github.com/abpframework/abp/tree/dev/modules/identity). 文档很快会被完善. +> 参阅 [源码](https://github.com/abpframework/abp/tree/dev/modules/identity). 文档很快会被完善. ## Identity安全日志 diff --git a/docs/zh-Hans/Modules/IdentityServer.md b/docs/zh-Hans/Modules/IdentityServer.md new file mode 100644 index 0000000000..cb82a640d5 --- /dev/null +++ b/docs/zh-Hans/Modules/IdentityServer.md @@ -0,0 +1 @@ +TODO... \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Index.md b/docs/zh-Hans/Modules/Index.md index dab2f838df..656e5db96f 100644 --- a/docs/zh-Hans/Modules/Index.md +++ b/docs/zh-Hans/Modules/Index.md @@ -1,6 +1,6 @@ # 应用程序模块 -ABP是一个 **模块化的应用程序框架** 由十多个 **nuget packages** 组成. 它提供了一个完整的基础设施来构建你自己的应用程序模块,这些模块包含实体,服务,数据库集成,API,UI组件等. +ABP是一个 **模块化的应用程序框架** 由十多个 **NuGet & NPM packages** 组成. 它提供了一个完整的基础设施来构建你自己的应用程序模块,这些模块包含实体,服务,数据库集成,API,UI组件等. **有两种类型的模块.** 它们没有任何结构上的差异,只是按照功能和目地分类: @@ -9,20 +9,20 @@ ABP是一个 **模块化的应用程序框架** 由十多个 **nuget packages** ## 开源的应用程序模块 -有一些由ABP社区开发和维护的 **开源免费** 的应用程序模块: +有一些由ABP框架开发和维护的 **开源免费** 的应用程序模块: -* **Account**: 提供账户管理UI,并允许用户登录/注册应用程序. +* [**Account**](Account.md): 提供账户管理UI,并允许用户登录/注册应用程序. * [**Audit Logging**](Audit-Logging.md): 用于将审计日志持久化到数据库. -* **Background Jobs**: 用于在使用默认后台作业管理器时保存后台作业. -* **Blogging**: 用于创建精美的博客. ABP的[博客](https://blog.abp.io/) 就使用了此模块. +* [**Background Jobs**](Background-Jobs.md): 用于在使用默认后台作业管理器时保存后台作业. +* [**Blogging**](Blogging.md): 用于创建精美的博客. ABP的[博客](https://blog.abp.io/) 就使用了此模块. * [**Docs**](Docs.md): 用于创建技术文档页面. ABP的[文档](https://abp.io/documents/) 就使用了此模块. -* **Feature Management**: 用于保存和管理功能. +* [**Feature Management**](Feature-Management.md): 用于保存和管理功能. * [**Identity**](Identity.md): 基于Microsoft Identity管理组织单元,角色,用户和他们的权限. -* **Identity Server**: 集成了IdentityServer4. -* **Permission Management**: 用于保存权限. -* **Setting Management**: 用于保存设置. -* **Tenant Management**: 管理[多租户](../Multi-Tenancy.md)应用程序的租户. -* **Users**: 抽象用户, 因此其他模块可以依赖此模块而不是Identity模块. +* [**Identity Server**](IdentityServer.md): 集成了IdentityServer4. +* [**Permission Management**](Permission-Management.md): 用于保存权限. +* [**Setting Management**](Setting-Management.md): 用于保存设置. +* [**Tenant Management**](Tenant-Management.md): 管理[多租户](../Multi-Tenancy.md)应用程序的租户. +* [**Users**](Users.md): 抽象用户, 因此其他模块可以依赖此模块而不是Identity模块. * [**Virtual File Explorer**](Virtual-File-Explorer.md): 提供简单的UI查看[虚拟文件系统](../Virtual-File-System.md)中的文件. 模块化文档正在编写中. 请参阅[这个仓库](https://github.com/abpframework/abp/tree/master/modules)获取所有模块的源代码. diff --git a/docs/zh-Hans/Modules/Users.md b/docs/zh-Hans/Modules/Users.md new file mode 100644 index 0000000000..cb82a640d5 --- /dev/null +++ b/docs/zh-Hans/Modules/Users.md @@ -0,0 +1 @@ +TODO... \ No newline at end of file diff --git a/docs/zh-Hans/MongoDB.md b/docs/zh-Hans/MongoDB.md index c90b9b5740..2ceeb1e00c 100644 --- a/docs/zh-Hans/MongoDB.md +++ b/docs/zh-Hans/MongoDB.md @@ -160,7 +160,7 @@ public interface IBookRepository : IRepository 实现`IBookRepository`接口的例子: ```csharp -public class BookRepository : +public class BookRepository : MongoDbRepository, IBookRepository { @@ -200,9 +200,9 @@ context.Services.AddMongoDbContext(options => 当你想**重写基础仓储方法**时,这一点尤为重要.例如,你想要重写`DeleteAsync`方法,以便更有效的删除实体: ```csharp -public override async Task DeleteAsync( - Guid id, - bool autoSave = false, +public async override Task DeleteAsync( + Guid id, + bool autoSave = false, CancellationToken cancellationToken = default) { //TODO: 自定义实现删除方法 @@ -338,4 +338,4 @@ context.Services.AddMongoDbContext(options => }); ``` -这个例子中,`OtherMongoDbContext`实现了`IBookStoreMongoDbContext`.这个特性允许你在发开的时候使用多个MongoDbContext(每个模块一个),但是运行的时候只能使有一个MongoDbContext(实现所有MongoDbContexts的所有接口) \ No newline at end of file +这个例子中,`OtherMongoDbContext`实现了`IBookStoreMongoDbContext`.这个特性允许你在发开的时候使用多个MongoDbContext(每个模块一个),但是运行的时候只能使有一个MongoDbContext(实现所有MongoDbContexts的所有接口) diff --git a/docs/zh-Hans/Multi-Tenancy.md b/docs/zh-Hans/Multi-Tenancy.md index 863e9cfb4b..8e92d10673 100644 --- a/docs/zh-Hans/Multi-Tenancy.md +++ b/docs/zh-Hans/Multi-Tenancy.md @@ -127,13 +127,14 @@ namespace MyCompany.MyProject `MyCustomTenantResolveContributor`必须像下面这样实现**ITenantResolveContributor**接口: ````C# +using System.Threading.Tasks; using Volo.Abp.MultiTenancy; namespace MyCompany.MyProject { public class MyCustomTenantResolveContributor : ITenantResolveContributor { - public void Resolve(ITenantResolveContext context) + public override Task ResolveAsync(ITenantResolveContext context) { context.TenantIdOrName = ... //从其他地方获取租户id或租户名字... } diff --git a/docs/zh-Hans/Samples/Microservice-Demo.md b/docs/zh-Hans/Samples/Microservice-Demo.md index 59977908a1..59fa98e057 100644 --- a/docs/zh-Hans/Samples/Microservice-Demo.md +++ b/docs/zh-Hans/Samples/Microservice-Demo.md @@ -1118,7 +1118,7 @@ internal Product( 默认(**无参数**)构造函数是私有的,不在应用程序代码中使用. 这是必需的,因为大多数ORM在从数据库获取时需要在反序列化实体时使用无参数构造函数. -第二个构造函数是**internal**,这意味着它只能在域层内使用. 这强制在创建新的`Product`时使用`ProductManager`. 因为``ProductManager`应该在新产品创建上实现业务规则. 此构造函数仅需要最少的必需参数来创建具有一些可选参数的新产品. 它会检查一些简单的业务规则,以确保将实体创建为有效产品. +第二个构造函数是**internal**,这意味着它只能在域层内使用. 这强制在创建新的`Product`时使用`ProductManager`. 因为`ProductManager`应该在新产品创建上实现业务规则. 此构造函数仅需要最少的必需参数来创建具有一些可选参数的新产品. 它会检查一些简单的业务规则,以确保将实体创建为有效产品. 该类的其余部分具有操纵实体属性的方法. 例: @@ -1418,4 +1418,4 @@ ABP提供自动审计日志记录,详细保存每个请求(当前用户,浏览 ### 多租户 -该解决方案已配置提供[多租户](../Multi-Tenancy.md)系统,其中每个租户可以拥有其隔离的用户,角色,权限和其他数据. \ No newline at end of file +该解决方案已配置提供[多租户](../Multi-Tenancy.md)系统,其中每个租户可以拥有其隔离的用户,角色,权限和其他数据. diff --git a/docs/zh-Hans/Startup-Templates/Application.md b/docs/zh-Hans/Startup-Templates/Application.md index 58287cef5a..534a26d8fb 100644 --- a/docs/zh-Hans/Startup-Templates/Application.md +++ b/docs/zh-Hans/Startup-Templates/Application.md @@ -59,20 +59,6 @@ abp new Acme.BookStore -d mongodb ### 指定移动应用程序框架 -此模板支持以下移动应用程序框架: - -- `react-native`: React Native - -使用 `-m` (或 `--mobile`) 选项指定移动应用程序框架: - -````bash -abp new Acme.BookStore -m react-native -```` - -如果未指定,不会创建移动应用程序. - -### 指定移动应用程序框架 - 该模板支持以下移动应用程序框架: - `react-native`: React Native diff --git a/docs/zh-Hans/Startup-Templates/Index.md b/docs/zh-Hans/Startup-Templates/Index.md index fbc91c7549..268f51e98b 100644 --- a/docs/zh-Hans/Startup-Templates/Index.md +++ b/docs/zh-Hans/Startup-Templates/Index.md @@ -6,4 +6,5 @@ * [**app**](Application.md): 应用程序模板. * [**module**](Module.md): 模块/服务模板. -* [**console**](Console.md): 控制台模板. \ No newline at end of file +* [**console**](Console.md): 控制台模板. +* [**WPF**](WPF.md): WPF模板. diff --git a/docs/zh-Hans/Startup-Templates/WPF.md b/docs/zh-Hans/Startup-Templates/WPF.md new file mode 100644 index 0000000000..31a76eaa60 --- /dev/null +++ b/docs/zh-Hans/Startup-Templates/WPF.md @@ -0,0 +1,27 @@ +# WPF应用程序启动模板 + +此模板用于创建一个最小的依赖关系的ABP WPF应用程序项目. + +## 如何开始? + +首先,如果你没有安装[ABP CLI](../CLI.md),请先安装它: + +````bash +dotnet tool install -g Volo.Abp.Cli +```` + +在一个空文件夹使用 `abp new` 命令创建新解决方案: + +````bash +abp new Acme.MyWpfApp -t wpf +```` + +`Acme.MyWpfApp` 是解决方案的名称, 如*YourCompany.YourProduct*. 你可以使用单级或多级名称. + +## 解决方案结构 + +使用以上命令创建解决方案后,你会得到如下所示的解决方案: + +![basic-wpf-application-solution](../images/basic-wpf-application-solution.png) + +* `HelloWorldService` 是一个实现了 `ITransientDependency` 接口的示例服务. 它会自动注册到[依赖注入](../Dependency-Injection.md)系统. \ No newline at end of file diff --git a/docs/zh-Hans/Tutorials/Part-1.md b/docs/zh-Hans/Tutorials/Part-1.md index 99a7e3d9fb..e459c8b960 100644 --- a/docs/zh-Hans/Tutorials/Part-1.md +++ b/docs/zh-Hans/Tutorials/Part-1.md @@ -84,7 +84,7 @@ namespace Acme.BookStore.Books } ```` -* ABP为实体提供了两个基本的基类: `AggregateRoot`和`Entity`. **Aggregate Root**是**[领域驱动设计](./Domain-Driven-Design.md)** 概念之一. 可以视为直接查询和处理的根实体(请参阅[实体文档](./Entities.md)). +* ABP为实体提供了两个基本的基类: `AggregateRoot`和`Entity`. **Aggregate Root**是[**领域驱动设计**](./Domain-Driven-Design.md) 概念之一. 可以视为直接查询和处理的根实体(请参阅[实体文档](./Entities.md)). * `Book`实体继承了`AuditedAggregateRoot`,`AuditedAggregateRoot`类在`AggregateRoot`类的基础上添加了一些审计属性(`CreationTime`, `CreatorId`, `LastModificationTime` 等). ABP框架自动为你管理这些属性. * `Guid`是`Book`实体的主键类型. @@ -185,7 +185,7 @@ namespace Acme.BookStore.EntityFrameworkCore ### 添加数据迁移 -启动模板使用[EF Core Code First Migrations](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/)创建和维护数据库架构. 打开菜单*工具 > NuGet包管理器*下的**程序包管理控制台 (PMC)**. +启动模板使用[EF Core Code First Migrations](https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/)创建和维护数据库架构. 打开菜单*工具 > NuGet包管理器*下的**程序包管理控制台 (PMC)**. ![Open Package Manager Console](images/bookstore-open-package-manager-console.png) @@ -201,7 +201,7 @@ Add-Migration "Created_Book_Entity" 在更新数据库之前,请阅读下面的部分了解如何将一些初始数据插入到数据库. -> 如果你使用其他IDE而不是Visual Studio, 你可以使用 [`dotnet-ef]`(https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli#create-a-migration) 工具. +> 如果你使用其他IDE而不是Visual Studio, 你可以使用 [`dotnet-ef`](https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli#create-a-migration) 工具. {{end}} @@ -262,7 +262,7 @@ namespace Acme.BookStore } ``` -* 如果数据库中当前没有图书,则此代码使用 `IRepository`(默认为[repository](../Repositories.md)将两本书插入数据库. +* 如果数据库中当前没有图书,则此代码使用 `IRepository`(默认为[repository](../Repositories.md))将两本书插入数据库. ### 更新数据库 @@ -276,7 +276,7 @@ namespace Acme.BookStore 应用程序层由两个分离的项目组成: -* `Acme.BookStore.Application.Contracts 包含你的[DTO](../Data-Transfer-Objects.md)和[应用服务](../Application-Services.md)接口. +* `Acme.BookStore.Application.Contracts` 包含你的[DTO](../Data-Transfer-Objects.md)和[应用服务](../Application-Services.md)接口. * `Acme.BookStore.Application` 包含你的应用服务实现. 在本部分中,你将创建一个应用程序服务,使用ABP Framework的 `CrudAppService` 基类来获取,创建,更新和删除书籍. diff --git a/docs/zh-Hans/UI/Angular/Component-Replacement.md b/docs/zh-Hans/UI/Angular/Component-Replacement.md index 221ac6775a..2c37a5a2e7 100644 --- a/docs/zh-Hans/UI/Angular/Component-Replacement.md +++ b/docs/zh-Hans/UI/Angular/Component-Replacement.md @@ -49,7 +49,7 @@ export class AppComponent { yarn ng generate component my-application-layout ``` -在你的布局模板(`my-layout.component.html`)中添加以下代码: +在你的布局模板(`my-application-layout.component.html`)中添加以下代码: ```html @@ -543,4 +543,4 @@ export class AppComponent implements OnInit { ## 下一步是什么? -- [自定义设置页面](./Custom-Setting-Page.md) \ No newline at end of file +- [自定义设置页面](./Custom-Setting-Page.md) diff --git a/docs/zh-Hans/UI/AspNetCore/Customization-User-Interface.md b/docs/zh-Hans/UI/AspNetCore/Customization-User-Interface.md index 7daf6c5d4b..44eb9b6e26 100644 --- a/docs/zh-Hans/UI/AspNetCore/Customization-User-Interface.md +++ b/docs/zh-Hans/UI/AspNetCore/Customization-User-Interface.md @@ -36,7 +36,7 @@ namespace Acme.BookStore.Web.Pages.Identity.Users { } - public override async Task OnPostAsync() + public async override Task OnPostAsync() { //TODO: Additional logic await base.OnPostAsync(); @@ -70,7 +70,7 @@ namespace Acme.BookStore.Web.Pages.Identity.Users 在这种情况下; -1. 像上面描述过的那术重写C#页面模型类,但不需要替换已存在的页面模型类. +1. 像上面描述过的那样重写C#页面模型类,但不需要替换已存在的页面模型类. 2. 像上面描述过的那样重写Razor页面,并且更改@model指向新的页面模型 #### 示例 @@ -83,10 +83,10 @@ namespace Acme.BookStore.Web.Pages.Identity.Users public class MyLoginModel : LoginModel { public MyLoginModel( - IAuthenticationSchemeProvider schemeProvider, + IAuthenticationSchemeProvider schemeProvider, IOptions accountOptions ) : base( - schemeProvider, + schemeProvider, accountOptions) { diff --git a/docs/zh-Hans/docs-nav.json b/docs/zh-Hans/docs-nav.json index 5df3376507..5ed50aebce 100644 --- a/docs/zh-Hans/docs-nav.json +++ b/docs/zh-Hans/docs-nav.json @@ -12,14 +12,42 @@ "path": "Startup-Templates/Console.md" }, { - "text": "空Web应用程序t", + "text": "WPF应用程序", + "path": "Startup-Templates/WPF.md" + }, + { + "text": "空Web应用程序", "path": "Getting-Started-AspNetCore-Application.md" } ] }, + { + "text": "启动模板", + "items": [ + { + "text": "概述", + "path": "Startup-Templates/Index.md" + }, + { + "text": "应用程序", + "path": "Startup-Templates/Application.md" + }, + { + "text": "模块", + "path": "Startup-Templates/Module.md" + }, + { + "text": "控制台", + "path": "Startup-Templates/Console.md" + }, + { + "text": "WPF", + "path": "Startup-Templates/WPF.md" + } + ] + }, { "text": "教程", - "path": "Tutorials/Index.md", "items": [ { "text": "应用开发", @@ -37,29 +65,10 @@ "path": "Tutorials/Part-3.md" } ] - } - ] - }, - { - "text": "指南", - "items": [ + }, { - "text": "自定义应用模块", - "path": "Customizing-Application-Modules-Guide.md", - "items": [ - { - "text": "扩展实体", - "path": "Customizing-Application-Modules-Extending-Entities.md" - }, - { - "text": "重写服务", - "path": "Customizing-Application-Modules-Overriding-Services.md" - }, - { - "text": "重写用户界面", - "path": "Customizing-Application-Modules-Overriding-User-Interface.md" - } - ] + "text": "社区文章", + "path": "https://community.abp.io/articles" }, { "text": "从ASP.NET Boilerplate迁移", @@ -67,19 +76,6 @@ } ] }, - { - "text": "CLI", - "path": "CLI.md" - }, - { - "text": "认证", - "items": [ - { - "text": "社交/外部登录", - "path": "Authentication/Social-External-Logins.md" - } - ] - }, { "text": "基础知识", "items": [ @@ -101,10 +97,6 @@ } ] }, - { - "text": "虚拟文件系统", - "path": "Virtual-File-System.md" - }, { "text": "本地化", "path": "Localization.md" @@ -135,17 +127,13 @@ "text": "日志", "path": "Logging.md" }, - { - "text": "审计日志", - "path": "Audit-Logging.md" - }, { "text": "设置管理", "path": "Settings.md" }, { - "text": "数据过滤", - "path": "Data-Filtering.md" + "text": "连接字符串", + "path": "Connection-Strings.md" }, { "text": "对象扩展", @@ -154,35 +142,88 @@ ] }, { - "text": "事件总线", - "items": [ - { - "text": "概述", - "path": "Event-Bus.md" - }, + "text": "基础设施", + "items":[ { - "text": "本地 Event Bus", - "path": "Local-Event-Bus.md" + "text": "后台服务", + "items": [ + { + "text": "后台作业", + "path": "Background-Jobs.md", + "items": [ + { + "text": "Hangfire 集成", + "path": "Background-Jobs-Hangfire.md" + }, + { + "text": "RabbitMQ 集成", + "path": "Background-Jobs-RabbitMq.md" + }, + { + "text": "Quartz 集成", + "path": "Background-Jobs-Quartz.md" + } + ] + }, + { + "text": "后台工作者", + "path": "Background-Workers.md", + "items": [ + { + "text": "Quartz 集成", + "path": "Background-Workers-Quartz.md" + } + ] + } + ] }, { - "text": "分布式 Event Bus", - "path": "Distributed-Event-Bus.md", + "text": "事件总线", "items": [ { - "text": "RabbitMQ 集成", - "path": "Distributed-Event-Bus-RabbitMQ-Integration.md" + "text": "概述", + "path": "Event-Bus.md" + }, + { + "text": "本地 Event Bus", + "path": "Local-Event-Bus.md" }, { - "text": "Kafka 集成", - "path": "Distributed-Event-Bus-Kafka-Integration.md" + "text": "分布式 Event Bus", + "path": "Distributed-Event-Bus.md", + "items": [ + { + "text": "RabbitMQ 集成", + "path": "Distributed-Event-Bus-RabbitMQ-Integration.md" + }, + { + "text": "Kafka 集成", + "path": "Distributed-Event-Bus-Kafka-Integration.md" + }, + { + "text": "Rebus 集成", + "path": "Distributed-Event-Bus-Rebus-Integration.md" + } + ] } ] - } - ] - }, - { - "text": "服务", - "items": [ + }, + { + "text": "种子数据", + "path": "Data-Seeding.md" + }, + { + "text": "虚拟文件系统", + "path": "Virtual-File-System.md" + }, + { + "text": "审计日志", + "path": "Audit-Logging.md" + }, + { + "text": "数据过滤", + "path": "Data-Filtering.md" + }, { "text": "当前用户", "path": "CurrentUser.md" @@ -262,22 +303,41 @@ ] }, { - "text": "多租户", - "path": "Multi-Tenancy.md" - }, - { - "text": "模块开发", - "items": [ + "text": "架构", + "items":[ { - "text": "基础", - "path": "Module-Development-Basics.md" - }, - { - "text": "模块插件" - }, - { - "text": "最佳实践", - "path": "Best-Practices/Index.md" + "text": "模块化", + "items": [ + { + "text": "基础", + "path": "Module-Development-Basics.md" + }, + { + "text": "模块插件" + }, + { + "text": "自定义应用模块", + "path": "Customizing-Application-Modules-Guide.md", + "items": [ + { + "text": "扩展实体", + "path": "Customizing-Application-Modules-Extending-Entities.md" + }, + { + "text": "重写服务", + "path": "Customizing-Application-Modules-Overriding-Services.md" + }, + { + "text": "重写用户界面", + "path": "Customizing-Application-Modules-Overriding-User-Interface.md" + } + ] + }, + { + "text": "最佳实践", + "path": "Best-Practices/Index.md" + } + ] } ] }, @@ -327,6 +387,14 @@ "path": "Unit-Of-Work.md" } ] + }, + { + "text": "多租户", + "path": "Multi-Tenancy.md" + }, + { + "text": "微服务架构", + "path": "Microservice-Architecture.md" } ] }, @@ -508,58 +576,45 @@ "path": "Data-Access.md" }, { - "text": "连接字符串", - "path": "Connection-Strings.md" - }, - { - "text": "数据库提供程序", + "text": "Entity Framework Core", + "path": "Entity-Framework-Core.md", "items": [ { - "text": "Entity Framework Core", - "path": "Entity-Framework-Core.md", - "items": [ + "text": "数据库迁移", + "path": "Entity-Framework-Core-Migrations.md" + }, + { + + "text": "切换DMBS", + "path": "Entity-Framework-Core-Other-DBMS.md", + "items":[ { - "text": "数据库迁移", - "path": "Entity-Framework-Core-Migrations.md" + "text": "到MySql", + "path": "Entity-Framework-Core-MySQL.md" }, { - - "text": "切换DMBS", - "path": "Entity-Framework-Core-Other-DBMS.md", - "items":[ - { - "text": "到MySql", - "path": "Entity-Framework-Core-MySQL.md" - }, - { - "text": "到PostgreSQL", - "path": "Entity-Framework-Core-PostgreSQL.md" - }, - { - "text": " Oracle", - "path": "Entity-Framework-Core-Oracle.md" - }, - { - "text": "到SQLite", - "path": "Entity-Framework-Core-SQLite.md" - } - ] + "text": "到PostgreSQL", + "path": "Entity-Framework-Core-PostgreSQL.md" + }, + { + "text": " Oracle", + "path": "Entity-Framework-Core-Oracle.md" + }, + { + "text": "到SQLite", + "path": "Entity-Framework-Core-SQLite.md" } ] - }, - { - "text": "MongoDB", - "path": "MongoDB.md" - }, - { - "text": "Dapper", - "path": "Dapper.md" } ] }, { - "text": "种子数据", - "path": "Data-Seeding.md" + "text": "MongoDB", + "path": "MongoDB.md" + }, + { + "text": "Dapper", + "path": "Dapper.md" } ] }, @@ -573,107 +628,128 @@ ] }, { - "text": "后台服务", + "text": "示例", "items": [ { - "text": "后台作业", - "path": "Background-Jobs.md", - "items": [ - { - "text": "Hangfire 集成", - "path": "Background-Jobs-Hangfire.md" - }, - { - "text": "RabbitMQ 集成", - "path": "Background-Jobs-RabbitMq.md" - }, - { - "text": "Quartz 集成", - "path": "Background-Jobs-Quartz.md" - } - ] + "text": "所有示例", + "path": "Samples/Index.md" }, { - "text": "后台工作者", - "path": "Background-Workers.md", - "items": [ - { - "text": "Quartz 集成", - "path": "Background-Workers-Quartz.md" - } - ] + "text": "微服务示例", + "path": "Samples/Microservice-Demo.md" } ] - }, + }, { - "text": "启动模板", - "items": [ + "text": "应用模块", + "items":[ { "text": "概述", - "path": "Startup-Templates/Index.md" + "path": "Modules/Index.md" }, { - "text": "应用程序", - "path": "Startup-Templates/Application.md" + "text": "账户", + "path": "Modules/Account.md" }, { - "text": "模块", - "path": "Startup-Templates/Module.md" + "text": "审计日志", + "path": "Modules/Audit-Logging.md" }, { - "text": "控制台", - "path": "Startup-Templates/Console.md" + "text": "后台作业", + "path": "Modules/Background-Jobs.md" + }, + { + "text": "博客", + "path": "Modules/Blogging.md" + }, + { + "text": "客户端模拟", + "path": "Modules/Client-Simulation.md" + }, + { + "text": "CMS Kit", + "path": "Modules/Cms-Kit.md" + }, + { + "text": "文档", + "path": "Modules/Docs.md" + }, + { + "text": "功能管理", + "path": "Modules/Feature-Management.md" + }, + { + "text": "Identity", + "path": "Modules/Identity.md" + }, + { + "text": "IdentityServer", + "path": "Modules/IdentityServer.md" + }, + { + "text": "权限管理", + "path": "Modules/Permission-Management.md" + }, + { + "text": "设置管理", + "path": "Modules/Setting-Management.md" + }, + { + "text": "租户管理", + "path": "Modules/Tenant-Management.md" + }, + { + "text": "用户", + "path": "Modules/Users.md" + }, + { + "text": "虚拟文件浏览器", + "path": "Modules/Virtual-File-Explorer.md" } ] }, { - "text": "示例", + "text": "发布信息", "items": [ { - "text": "所有示例", - "path": "Samples/Index.md" + "text": "升级", + "path": "Upgrading.md" }, { - "text": "微服务示例", - "path": "Samples/Microservice-Demo.md" + "text": "官方包", + "path": "https://abp.io/packages" + }, + { + "text": "预览版本", + "path": "Previews.md" + }, + { + "text": "每日构建", + "path": "Nightly-Builds.md" + }, + { + "text": "路线图", + "path": "Road-Map.md" } ] }, { - "text": "应用模块", - "path": "Modules/Index.md" - }, - { - "text": "微服务架构", - "path": "Microservice-Architecture.md" - }, - { - "text": "预览版本", - "path": "Previews.md" - }, - { - "text": "每日构建", - "path": "Nightly-Builds.md" - }, - { - "text": "路线图", - "path": "Road-Map.md" - }, - { - "text": "升级", - "path": "Upgrading.md" + "text": "参考", + "items": [ + { + "text": "CLI", + "path": "CLI.md" + }, + { + "text": "API文档", + "path": "{ApiDocumentationUrl}" + } + ] }, { "text": "贡献指南", "path": "Contribution/Index.md" - }, - { - "text": "API文档", - "path": "{ApiDocumentationUrl}" - }, - { - "text": "官方包", - "path": "https://abp.io/packages" } ] } diff --git a/docs/zh-Hans/images/basic-wpf-application-solution.png b/docs/zh-Hans/images/basic-wpf-application-solution.png new file mode 100644 index 0000000000..5943acd93f Binary files /dev/null and b/docs/zh-Hans/images/basic-wpf-application-solution.png differ diff --git a/framework/Volo.Abp.sln b/framework/Volo.Abp.sln index 503b42c7e1..963472ada8 100644 --- a/framework/Volo.Abp.sln +++ b/framework/Volo.Abp.sln @@ -319,33 +319,45 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.BlobStoring.Aliyun EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.BlobStoring.Aliyun.Tests", "test\Volo.Abp.BlobStoring.Aliyun.Tests\Volo.Abp.BlobStoring.Aliyun.Tests.csproj", "{8E49687A-E69F-49F2-8DB0-428D0883A937}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.BlobStoring.Aws", "src\Volo.Abp.BlobStoring.Aws\Volo.Abp.BlobStoring.Aws.csproj", "{50968CDE-1029-4051-B2E5-B69D0ECF2A18}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.BlobStoring.Aws", "src\Volo.Abp.BlobStoring.Aws\Volo.Abp.BlobStoring.Aws.csproj", "{50968CDE-1029-4051-B2E5-B69D0ECF2A18}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.BlobStoring.Aws.Tests", "test\Volo.Abp.BlobStoring.Aws.Tests\Volo.Abp.BlobStoring.Aws.Tests.csproj", "{2CD3B26A-CA81-4279-8D5D-6A594517BB3F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.BlobStoring.Aws.Tests", "test\Volo.Abp.BlobStoring.Aws.Tests\Volo.Abp.BlobStoring.Aws.Tests.csproj", "{2CD3B26A-CA81-4279-8D5D-6A594517BB3F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Kafka", "src\Volo.Abp.Kafka\Volo.Abp.Kafka.csproj", "{2A864049-9CD5-4493-8CDB-C408474D43D4}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.Kafka", "src\Volo.Abp.Kafka\Volo.Abp.Kafka.csproj", "{2A864049-9CD5-4493-8CDB-C408474D43D4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.EventBus.Kafka", "src\Volo.Abp.EventBus.Kafka\Volo.Abp.EventBus.Kafka.csproj", "{C1D891B0-AE83-42CB-987D-425A2787DE78}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.EventBus.Kafka", "src\Volo.Abp.EventBus.Kafka\Volo.Abp.EventBus.Kafka.csproj", "{C1D891B0-AE83-42CB-987D-425A2787DE78}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.GlobalFeatures", "src\Volo.Abp.GlobalFeatures\Volo.Abp.GlobalFeatures.csproj", "{04F44063-C952-403A-815F-EFB778BDA125}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.GlobalFeatures", "src\Volo.Abp.GlobalFeatures\Volo.Abp.GlobalFeatures.csproj", "{04F44063-C952-403A-815F-EFB778BDA125}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.GlobalFeatures.Tests", "test\Volo.Abp.GlobalFeatures.Tests\Volo.Abp.GlobalFeatures.Tests.csproj", "{231F1581-AA21-44C3-BF27-51EB3AD5355C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.GlobalFeatures.Tests", "test\Volo.Abp.GlobalFeatures.Tests\Volo.Abp.GlobalFeatures.Tests.csproj", "{231F1581-AA21-44C3-BF27-51EB3AD5355C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Http.Client.IdentityModel.WebAssembly", "src\Volo.Abp.Http.Client.IdentityModel.WebAssembly\Volo.Abp.Http.Client.IdentityModel.WebAssembly.csproj", "{3D35A1E0-A9A1-404F-9B55-5F1A7EB6D5B8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.Http.Client.IdentityModel.WebAssembly", "src\Volo.Abp.Http.Client.IdentityModel.WebAssembly\Volo.Abp.Http.Client.IdentityModel.WebAssembly.csproj", "{3D35A1E0-A9A1-404F-9B55-5F1A7EB6D5B8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.AspNetCore.Mvc.Client.Common", "src\Volo.Abp.AspNetCore.Mvc.Client.Common\Volo.Abp.AspNetCore.Mvc.Client.Common.csproj", "{8A22D962-016E-474A-8BB7-F831F0ABF3AC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Mvc.Client.Common", "src\Volo.Abp.AspNetCore.Mvc.Client.Common\Volo.Abp.AspNetCore.Mvc.Client.Common.csproj", "{8A22D962-016E-474A-8BB7-F831F0ABF3AC}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.AspNetCore.Components.WebAssembly", "src\Volo.Abp.AspNetCore.Components.WebAssembly\Volo.Abp.AspNetCore.Components.WebAssembly.csproj", "{E1A62D10-F2FB-4040-BD60-11A3934058DF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Components.WebAssembly", "src\Volo.Abp.AspNetCore.Components.WebAssembly\Volo.Abp.AspNetCore.Components.WebAssembly.csproj", "{E1A62D10-F2FB-4040-BD60-11A3934058DF}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.BlazoriseUI", "src\Volo.Abp.BlazoriseUI\Volo.Abp.BlazoriseUI.csproj", "{4EBDDB1B-D6C5-4FAE-B5A7-2171B18CDFA5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.BlazoriseUI", "src\Volo.Abp.BlazoriseUI\Volo.Abp.BlazoriseUI.csproj", "{4EBDDB1B-D6C5-4FAE-B5A7-2171B18CDFA5}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme", "src\Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme\Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.csproj", "{ABC27C10-C0FF-44CB-B4FF-A09C0B79F695}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme", "src\Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme\Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.csproj", "{ABC27C10-C0FF-44CB-B4FF-A09C0B79F695}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.AspNetCore.Components.WebAssembly.Theming", "src\Volo.Abp.AspNetCore.Components.WebAssembly.Theming\Volo.Abp.AspNetCore.Components.WebAssembly.Theming.csproj", "{29CA7471-4E3E-4E75-8B33-001DDF682F01}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Components.WebAssembly.Theming", "src\Volo.Abp.AspNetCore.Components.WebAssembly.Theming\Volo.Abp.AspNetCore.Components.WebAssembly.Theming.csproj", "{29CA7471-4E3E-4E75-8B33-001DDF682F01}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Autofac.WebAssembly", "src\Volo.Abp.Autofac.WebAssembly\Volo.Abp.Autofac.WebAssembly.csproj", "{37F89B0B-1C6B-426F-A5EE-676D1956D9E9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.Autofac.WebAssembly", "src\Volo.Abp.Autofac.WebAssembly\Volo.Abp.Autofac.WebAssembly.csproj", "{37F89B0B-1C6B-426F-A5EE-676D1956D9E9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.AspNetCore.Authentication.OpenIdConnect", "src\Volo.Abp.AspNetCore.Authentication.OpenIdConnect\Volo.Abp.AspNetCore.Authentication.OpenIdConnect.csproj", "{DEFE3DB2-EA4F-4F90-87FC-B25D64427BC5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Authentication.OpenIdConnect", "src\Volo.Abp.AspNetCore.Authentication.OpenIdConnect\Volo.Abp.AspNetCore.Authentication.OpenIdConnect.csproj", "{DEFE3DB2-EA4F-4F90-87FC-B25D64427BC5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.EventBus.Rebus", "src\Volo.Abp.EventBus.Rebus\Volo.Abp.EventBus.Rebus.csproj", "{F689967F-1EF1-4D75-8BA4-2F2F3506B1F3}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.ExceptionHandling", "src\Volo.Abp.ExceptionHandling\Volo.Abp.ExceptionHandling.csproj", "{B9D1ADCB-D552-4626-A1F1-78FF72C1E822}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Components", "src\Volo.Abp.AspNetCore.Components\Volo.Abp.AspNetCore.Components.csproj", "{89840441-5A3A-4FD7-9CB4-E5B52FAEF72A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Swashbuckle", "src\Volo.Abp.Swashbuckle\Volo.Abp.Swashbuckle.csproj", "{DD9519E0-5A68-48DC-A051-7BF2AC922F3E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Json.Tests", "test\Volo.Abp.Json.Tests\Volo.Abp.Json.Tests.csproj", "{00D07595-993C-40FC-BD90-0DD6331414D3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Http.Tests", "test\Volo.Abp.Http.Tests\Volo.Abp.Http.Tests.csproj", "{A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -1033,6 +1045,30 @@ Global {DEFE3DB2-EA4F-4F90-87FC-B25D64427BC5}.Debug|Any CPU.Build.0 = Debug|Any CPU {DEFE3DB2-EA4F-4F90-87FC-B25D64427BC5}.Release|Any CPU.ActiveCfg = Release|Any CPU {DEFE3DB2-EA4F-4F90-87FC-B25D64427BC5}.Release|Any CPU.Build.0 = Release|Any CPU + {F689967F-1EF1-4D75-8BA4-2F2F3506B1F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F689967F-1EF1-4D75-8BA4-2F2F3506B1F3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F689967F-1EF1-4D75-8BA4-2F2F3506B1F3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F689967F-1EF1-4D75-8BA4-2F2F3506B1F3}.Release|Any CPU.Build.0 = Release|Any CPU + {B9D1ADCB-D552-4626-A1F1-78FF72C1E822}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9D1ADCB-D552-4626-A1F1-78FF72C1E822}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9D1ADCB-D552-4626-A1F1-78FF72C1E822}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9D1ADCB-D552-4626-A1F1-78FF72C1E822}.Release|Any CPU.Build.0 = Release|Any CPU + {89840441-5A3A-4FD7-9CB4-E5B52FAEF72A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89840441-5A3A-4FD7-9CB4-E5B52FAEF72A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {89840441-5A3A-4FD7-9CB4-E5B52FAEF72A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {89840441-5A3A-4FD7-9CB4-E5B52FAEF72A}.Release|Any CPU.Build.0 = Release|Any CPU + {DD9519E0-5A68-48DC-A051-7BF2AC922F3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DD9519E0-5A68-48DC-A051-7BF2AC922F3E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DD9519E0-5A68-48DC-A051-7BF2AC922F3E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DD9519E0-5A68-48DC-A051-7BF2AC922F3E}.Release|Any CPU.Build.0 = Release|Any CPU + {00D07595-993C-40FC-BD90-0DD6331414D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {00D07595-993C-40FC-BD90-0DD6331414D3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {00D07595-993C-40FC-BD90-0DD6331414D3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {00D07595-993C-40FC-BD90-0DD6331414D3}.Release|Any CPU.Build.0 = Release|Any CPU + {A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1208,6 +1244,12 @@ Global {29CA7471-4E3E-4E75-8B33-001DDF682F01} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} {37F89B0B-1C6B-426F-A5EE-676D1956D9E9} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} {DEFE3DB2-EA4F-4F90-87FC-B25D64427BC5} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} + {F689967F-1EF1-4D75-8BA4-2F2F3506B1F3} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} + {B9D1ADCB-D552-4626-A1F1-78FF72C1E822} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} + {89840441-5A3A-4FD7-9CB4-E5B52FAEF72A} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} + {DD9519E0-5A68-48DC-A051-7BF2AC922F3E} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} + {00D07595-993C-40FC-BD90-0DD6331414D3} = {447C8A77-E5F0-4538-8687-7383196D04EA} + {A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1} = {447C8A77-E5F0-4538-8687-7383196D04EA} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {BB97ECF4-9A84-433F-A80B-2A3285BDD1D5} diff --git a/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo.Abp.AspNetCore.Authentication.JwtBearer.csproj b/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo.Abp.AspNetCore.Authentication.JwtBearer.csproj index 1d30366e67..64f2ef9f99 100644 --- a/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo.Abp.AspNetCore.Authentication.JwtBearer.csproj +++ b/framework/src/Volo.Abp.AspNetCore.Authentication.JwtBearer/Volo.Abp.AspNetCore.Authentication.JwtBearer.csproj @@ -4,7 +4,7 @@ - netcoreapp3.1 + net5.0 Volo.Abp.AspNetCore.Authentication.JwtBearer Volo.Abp.AspNetCore.Authentication.JwtBearer $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; @@ -19,7 +19,7 @@ - + diff --git a/framework/src/Volo.Abp.AspNetCore.Authentication.OAuth/Volo.Abp.AspNetCore.Authentication.OAuth.csproj b/framework/src/Volo.Abp.AspNetCore.Authentication.OAuth/Volo.Abp.AspNetCore.Authentication.OAuth.csproj index ae032e5b9e..18e9a271dc 100644 --- a/framework/src/Volo.Abp.AspNetCore.Authentication.OAuth/Volo.Abp.AspNetCore.Authentication.OAuth.csproj +++ b/framework/src/Volo.Abp.AspNetCore.Authentication.OAuth/Volo.Abp.AspNetCore.Authentication.OAuth.csproj @@ -4,7 +4,7 @@ - netcoreapp3.1 + net5.0 Volo.Abp.AspNetCore.Authentication.OAuth Volo.Abp.AspNetCore.Authentication.OAuth $(AssetTargetFallback);portable-net45+win8+wp8+wpa81; diff --git a/framework/src/Volo.Abp.AspNetCore.Authentication.OpenIdConnect/Volo.Abp.AspNetCore.Authentication.OpenIdConnect.csproj b/framework/src/Volo.Abp.AspNetCore.Authentication.OpenIdConnect/Volo.Abp.AspNetCore.Authentication.OpenIdConnect.csproj index 30f56491c5..b0aa11f206 100644 --- a/framework/src/Volo.Abp.AspNetCore.Authentication.OpenIdConnect/Volo.Abp.AspNetCore.Authentication.OpenIdConnect.csproj +++ b/framework/src/Volo.Abp.AspNetCore.Authentication.OpenIdConnect/Volo.Abp.AspNetCore.Authentication.OpenIdConnect.csproj @@ -4,12 +4,12 @@ - netcoreapp3.1 + net5.0 - + diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/BasicThemeBundleContributor.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/BasicThemeBundleContributor.cs new file mode 100644 index 0000000000..edef97eb52 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/BasicThemeBundleContributor.cs @@ -0,0 +1,17 @@ +using Volo.Abp.Bundling; + +namespace Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme +{ + public class BasicThemeBundleContributor : IBundleContributor + { + public void AddScripts(BundleContext context) + { + + } + + public void AddStyles(BundleContext context) + { + context.Add("_content/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/libs/abp/css/theme.css"); + } + } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/Branding.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/Branding.razor new file mode 100644 index 0000000000..4810320664 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/Branding.razor @@ -0,0 +1,3 @@ +@using Volo.Abp.Ui.Branding +@inject IBrandingProvider BrandingProvider +@BrandingProvider.AppName diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/FirstLevelNavMenuItem.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/FirstLevelNavMenuItem.razor new file mode 100644 index 0000000000..31090ac092 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/FirstLevelNavMenuItem.razor @@ -0,0 +1,48 @@ +@using Volo.Abp.UI.Navigation +@{ + var elementId = MenuItem.ElementId ?? "MenuItem_" + MenuItem.Name.Replace(".", "_"); + var cssClass = string.IsNullOrEmpty(MenuItem.CssClass) ? string.Empty : MenuItem.CssClass; + var disabled = MenuItem.IsDisabled ? "disabled" : string.Empty; + var url = string.IsNullOrEmpty(MenuItem.Url) ? "#" : MenuItem.Url; +} +@if (MenuItem.IsLeaf) +{ + if (MenuItem.Url != null) + { + + } +} +else +{ + +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/FirstLevelNavMenuItem.razor.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/FirstLevelNavMenuItem.razor.cs new file mode 100644 index 0000000000..d0ff42879c --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/FirstLevelNavMenuItem.razor.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Routing; +using Volo.Abp.UI.Navigation; + +namespace Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic +{ + public partial class FirstLevelNavMenuItem : IDisposable + { + [Inject] private NavigationManager NavigationManager { get; set; } + + [Parameter] + public ApplicationMenuItem MenuItem { get; set; } + + public bool IsSubMenuOpen { get; set; } + + protected override void OnInitialized() + { + NavigationManager.LocationChanged += OnLocationChanged; + } + + private void ToggleSubMenu() + { + IsSubMenuOpen = !IsSubMenuOpen; + } + + public void Dispose() + { + NavigationManager.LocationChanged -= OnLocationChanged; + } + + private void OnLocationChanged(object sender, LocationChangedEventArgs e) + { + IsSubMenuOpen = false; + StateHasChanged(); + } + } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LanguageSwitch.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LanguageSwitch.razor index 8c7b348f7d..6b93618f44 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LanguageSwitch.razor +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LanguageSwitch.razor @@ -5,23 +5,23 @@ @inject IJSRuntime JsRuntime @if (_otherLanguages != null && _otherLanguages.Any()) { - - + + @_currentLanguage.DisplayName - - + + @foreach (var language in _otherLanguages) { - @language.DisplayName + @language.DisplayName } - - + + } @code { private IReadOnlyList _otherLanguages; private LanguageInfo _currentLanguage; - protected override async Task OnInitializedAsync() + protected async override Task OnInitializedAsync() { var selectedLanguageName = await JsRuntime.InvokeAsync( "localStorage.getItem", diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor index 3d3dd26fae..58d4d5753e 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor @@ -1,13 +1,22 @@ @using Microsoft.AspNetCore.Components.WebAssembly.Authentication @using Volo.Abp.Users +@using Volo.Abp.MultiTenancy @inject ICurrentUser CurrentUser +@inject ICurrentTenant CurrentTenant @inject NavigationManager Navigation @inject SignOutSessionStateManager SignOutManager - @CurrentUser.UserName + @if (CurrentTenant.Name != null) + { + @CurrentTenant.Name\@CurrentUser.UserName + } + else + { + @CurrentUser.UserName + } @if (Menu != null) @@ -17,9 +26,6 @@ @menuItem.DisplayName } } - - @UiLocalizer["ManageYourAccount"] - Logout diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor.cs index 17718dbcfb..494eca34ab 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/LoginDisplay.razor.cs @@ -1,50 +1,33 @@ using System; using System.Threading.Tasks; -using Localization.Resources.AbpUi; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Routing; -using Microsoft.Extensions.Localization; -using Microsoft.Extensions.Options; -using Volo.Abp.Http.Client; using Volo.Abp.UI.Navigation; namespace Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic { public partial class LoginDisplay : IDisposable { - [Inject] - protected IMenuManager MenuManager { get; set; } - - [Inject] - protected IStringLocalizer UiLocalizer { get; set; } - [Inject] - protected IOptions RemoteServiceOptions { get; set; } - - protected ApplicationMenu Menu { get; set; } + protected IMenuManager MenuManager { get; set; } - protected string ServerUrl { get; set; } - protected string ServerAccountUrl { get; set; } + protected ApplicationMenu Menu { get; set; } - protected override async Task OnInitializedAsync() + protected async override Task OnInitializedAsync() { Menu = await MenuManager.GetAsync(StandardMenus.User); - - ServerUrl = RemoteServiceOptions.Value.RemoteServices.Default?.BaseUrl?.TrimEnd('/'); - ServerAccountUrl = ServerUrl + "/Account/Manage?returnUrl=" + Navigation.Uri; - + Navigation.LocationChanged += OnLocationChanged; } protected virtual void OnLocationChanged(object sender, LocationChangedEventArgs e) { - ServerAccountUrl = ServerUrl + "/Account/Manage?returnUrl=" + Navigation.Uri; StateHasChanged(); } - + public void Dispose() { Navigation.LocationChanged -= OnLocationChanged; } } -} \ No newline at end of file +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor index 8e64b32022..e85e899123 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor @@ -1,22 +1,24 @@ @inherits LayoutComponentBase -@using Volo.Abp.Ui.Branding -@inject IBrandingProvider BrandingProvider
+ @Body + + +
diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor.cs new file mode 100644 index 0000000000..2464275c2c --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/MainLayout.razor.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Routing; + +namespace Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic +{ + public partial class MainLayout : IDisposable + { + [Inject] private NavigationManager NavigationManager { get; set; } + + private bool IsCollapseShown { get; set; } + + protected override void OnInitialized() + { + NavigationManager.LocationChanged += OnLocationChanged; + } + + private void ToggleCollapse() + { + IsCollapseShown = !IsCollapseShown; + } + + public void Dispose() + { + NavigationManager.LocationChanged -= OnLocationChanged; + } + + private void OnLocationChanged(object sender, LocationChangedEventArgs e) + { + IsCollapseShown = false; + StateHasChanged(); + } + } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor index c3ada520dc..b35ec8ba2e 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor @@ -2,50 +2,6 @@ { foreach (var menuItem in Menu.Items) { - var elementId = menuItem.ElementId ?? "MenuItem_" + menuItem.Name.Replace(".", "_"); - var cssClass = string.IsNullOrEmpty(menuItem.CssClass) ? string.Empty : menuItem.CssClass; - var disabled = menuItem.IsDisabled ? "disabled" : string.Empty; - var url = string.IsNullOrEmpty(menuItem.Url) ? "#" : menuItem.Url; - if (menuItem.IsLeaf) - { - if (menuItem.Url != null) - { - - } - } - else - { - - } + } } diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor.cs index e47603e163..1779d73d28 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenu.razor.cs @@ -6,22 +6,14 @@ namespace Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic { public partial class NavMenu { - [Inject] protected IMenuManager MenuManager { get; set; } + [Inject] + protected IMenuManager MenuManager { get; set; } protected ApplicationMenu Menu { get; set; } - private bool collapseNavMenu = true; - - private string NavMenuCssClass => collapseNavMenu ? "collapse" : null; - - protected override async Task OnInitializedAsync() + protected async override Task OnInitializedAsync() { Menu = await MenuManager.GetAsync(StandardMenus.Main); } - - private void ToggleNavMenu() - { - collapseNavMenu = !collapseNavMenu; - } } } diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor index 5eea07ea8f..ede8a54415 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor @@ -1,8 +1,8 @@  diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor.cs index 6fddf263b3..33044282f9 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavToolbar.razor.cs @@ -12,7 +12,7 @@ namespace Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme.Themes.Basic private List ToolbarItemRenders { get; set; } = new List(); - protected override async Task OnInitializedAsync() + protected async override Task OnInitializedAsync() { var toolbar = await ToolbarManager.GetAsync(StandardToolbars.Main); diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenuItem.razor b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/SecondLevelNavMenuItem.razor similarity index 82% rename from framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenuItem.razor rename to framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/SecondLevelNavMenuItem.razor index 338ce7b464..4e75e26b50 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/NavMenuItem.razor +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/SecondLevelNavMenuItem.razor @@ -24,7 +24,7 @@ else {