diff --git a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json index 7bb8f4d109..9720354d99 100644 --- a/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json +++ b/abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json @@ -193,7 +193,7 @@ "WhatHappensWhenLicenseEnds": "What happens when my license period ends?", "WhatHappensWhenLicenseEndsExplanation1": "ABP Commercial license type is perpetual license. After your license expires, you can continue developing your project. And you are not obliged to renew your license. Your license comes with a one-year Updates and Support plan out of the box. To continue to receive new features, performance enhancements, bug fixes, support and continue to use ABP Suite, make sure to renew your plan each year. When your license expires, you will not be able to get more of the following benefits;", "WhatHappensWhenLicenseEndsExplanation2": "You can not create new solutions using the ABP Commercial, but you can continue to develop your existing applications forever.", - "WhatHappensWhenLicenseEndsExplanation3": "You will be able to get updates for the modules and themes within your MAJOR version. For example; if you are using v3.2.0 of a module, you can still get updates for v3.x.x (v3.3.0, v3.5.2... etc.) of that module. But you cannot get updates for the next major version (like v4.x, v5.x)", + "WhatHappensWhenLicenseEndsExplanation3": "You will be able to get updates for the modules and themes within your MAJOR version (except RC or Preview versions). For example; if you are using v3.2.0 of a module, you can still get updates for v3.x.x (v3.3.0, v3.5.2... etc.) of that module. But you cannot get updates for the next major version (like v4.x, v5.x). Let's say, when your license expired, the latest release was v4.4.3 and the latest preview version was v5.0.0-rc.2, you can only access the v4.X.X but you cannot access the v5.X.X.", "WhatHappensWhenLicenseEndsExplanation4": "You can not install new modules and themes added to the ABP Commercial platform after your license ends.", "WhatHappensWhenLicenseEndsExplanation5": "You can not use the ABP Suite.", "WhatHappensWhenLicenseEndsExplanation6": "You can not get the premium support anymore.", diff --git a/docs/en/CLI.md b/docs/en/CLI.md index b8f69b1ee4..7db562a66e 100644 --- a/docs/en/CLI.md +++ b/docs/en/CLI.md @@ -29,6 +29,7 @@ Here, the list of all available commands before explaining their details: * **`help`**: Shows help on the usage of the ABP CLI. * **`new`**: Generates a new solution based on the ABP [startup templates](Startup-Templates/Index.md). * **`update`**: Automatically updates all ABP related NuGet and NPM packages in a solution. +* **`clean`**: Deletes all `BIN` and `OBJ` folders in the current folder. * **`add-package`**: Adds an ABP package to a project. * **`add-module`**: Adds a [multi-package application module](https://docs.abp.io/en/abp/latest/Modules/Index) to a solution. * **`list-modules`**: Lists names of open-source application modules. @@ -145,6 +146,17 @@ abp update [options] * `--check-all`: Check the new version of each package separately. Default is `false`. * `--version` or `-v`: Specifies the version to use for update. If not specified, latest version is used. +### clean + +Deletes all `BIN` and `OBJ` folders in the current folder. + +Usage: + +````bash +abp clean +```` + + ### add-package Adds an ABP package to a project by, diff --git a/docs/en/Community-Articles/2020-09-16-How-to-Setup-Azure-Active-Directory-and-Integrate-Abp-Angular-Application/POST.md b/docs/en/Community-Articles/2020-09-16-How-to-Setup-Azure-Active-Directory-and-Integrate-Abp-Angular-Application/POST.md index a1c63529a2..c82365efee 100644 --- a/docs/en/Community-Articles/2020-09-16-How-to-Setup-Azure-Active-Directory-and-Integrate-Abp-Angular-Application/POST.md +++ b/docs/en/Community-Articles/2020-09-16-How-to-Setup-Azure-Active-Directory-and-Integrate-Abp-Angular-Application/POST.md @@ -12,7 +12,7 @@ The most common question is; The answer is, **you don't**. ABP Angular application is integrated with the backend (HttpApi.Host project) where it loads the configurations, **permissions** etc. For none-tiered angular applications, **HttpApi.Host** project also has IdentityServer4 embedded; also serving as **Authorization Server**. Angular application authentication flow is shown below. -auth-diagram +![auth-diagram](auth-diagram.jpeg) > What if I want Azure AD as my authorization server and not IdentityServer? @@ -80,7 +80,7 @@ Navigate to Manage Azure Active Directory in [azure portal](https://portal.azure Enter a name for your application and **App.SelfUrl** + **AzureAd.CallbackPath** as redirect uri then register. -azure-app-register +![azure-app-register](azure-app-register.JPG) Now navigate to **Authentication** on the left menu and enable **ID tokens**. diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/POST.md b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/POST.md new file mode 100644 index 0000000000..edaeaf46db --- /dev/null +++ b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/POST.md @@ -0,0 +1,321 @@ +# Integrating the Syncfusion MVC Components to the ABP MVC UI + +## Introduction + +In this article we will see how we can integrate the Syncfusion MVC Components into our ABP application. + +## Source Code + +You can find the source code of the application at https://github.com/EngincanV/ABP-Syncfusion-Components-Demo. + +## Prerequisites + +* [.NET 6](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) + + * In this article, we will create a new startup template in v5.0.0-rc.2 and if you follow this article from top to bottom and create a new startup template with me, you need to install the [.NET 6 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) before starting. + +**NOTE:** ABP v5.X stable version has been released. You can replace v5.0.0-rc.2 with the latest stable version in your steps. + +Also, you need to update your ABP CLI to the v5.0.0-rc.2, you can use the command below to update your CLI version: + +```bash +dotnet tool update Volo.Abp.Cli -g --version 5.0.0-rc.2 +``` + +or install it if you haven't installed it before: + +```bash +dotnet tool install Volo.Abp.Cli -g --version 5.0.0-rc.2 +``` + +## Creating the Solution + +In this article, we will create a new startup template with EF Core as a database provider and MVC for the UI framework. But if you already have a project with MVC UI, you don't need to create a new startup template, you can directly implement the following steps to your existing project. + +> If you already have a project with MVC/Razor Pages UI, you can skip this section. + +We can create a new startup template by using the [ABP CLI](https://docs.abp.io/en/abp/latest/CLI): + +```bash +abp new SyncfusionComponentsDemo -t app --preview +``` + +Our project boilerplate will be ready after the download is finished. Then, we can open the solution and start developing. + +## Starting the Development + +### Pre-requisite + +> If you've already had a license from Syncfusion, you can skip this section. + +* The first thing we need to do is create an account to be able to get a license from Syncfusion. + +* So, let's navigate to https://www.syncfusion.com/aspnet-core-ui-controls and click the "Download Free Trial" button. + +* Then fill the form and start your 30-day free trial. + +* After that, navigate to https://www.syncfusion.com/account/manage-trials/downloads to get our license key that will be used in our application. + +![](./manage-trial-1.png) + +Click the "Get License Key" link for "ASP.NET Core (Essential JS 2)". + +![](./manage-trial-2.png) + +Then a modal will be opened like in the above image, select a version and click the "Get License Key" button. + +![](./copy-license-key.png) + +Lastly, copy the generated license key value. + +In order to use the relevant components, Syncfusion needs to check this license key to know that our license is valid. + +### Configurations + +After providing a license key from Syncfusion, we can start with the configuration that needs to be done in our application. + +#### 1-) Install the Syncfusion.EJ2.AspNet.Core package + +We need to install the `Syncfusion.EJ2.AspNet.Core` Nuget package to our Web project (*.Web). + +We can install it via **Visual Studio's Nuget Package Manager**: + +![](./syncfusion-package.png) + +or via dotnet cli: + +```bash +dotnet add package Syncfusion.EJ2.AspNet.Core --version 19.3.0.57 +``` + +> In this article, I've used the package in version 19.3.0.57. + +#### 2-) Register the License Key + +* After installing the package, we need to register our license key to be able to use the Syncfusion Components. + +* To register the license key, open your web module class and update the `ConfigureServices` method as follows: + +```csharp +public override void ConfigureServices(ServiceConfigurationContext context) +{ + var hostingEnvironment = context.Services.GetHostingEnvironment(); + var configuration = context.Services.GetConfiguration(); + + //Register Syncfusion license + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(licenseKey: configuration["Syncfusion:LicenseKey"].ToString()); + + ConfigureUrls(configuration); + ConfigureBundles(); + ConfigureAuthentication(context, configuration); + ConfigureAutoMapper(); + ConfigureVirtualFileSystem(hostingEnvironment); + ConfigureLocalizationServices(); + ConfigureNavigationServices(); + ConfigureAutoApiControllers(); + ConfigureSwaggerServices(context.Services); +} +``` + +Instead of writing the license key directly in here we can define it in the **appsettings.json** file and use it here by using the Configuration system of .NET. + + +* Open your **appsettings.json** file and add a new section named "Syncfusion" as below: + +```json +{ + //... + + "Syncfusion": { + "LicenseKey": "" + } +} +``` + +> Replace the ` part with your license key that we've obtained in the previous section.` + +* To be able to use the Syncfusion Components we need to define them in our **_ViewImports.cshtml** file. By doing that we can use the Syncfusion components everywhere in our application. + +* Open your **/Pages/_ViewImports.cshtml** file and add a new tag helper: + +```cshtml +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers +@addTagHelper *, Volo.Abp.AspNetCore.Mvc.UI +@addTagHelper *, Volo.Abp.AspNetCore.Mvc.UI.Bootstrap +@addTagHelper *, Volo.Abp.AspNetCore.Mvc.UI.Bundling +@addTagHelper *, Syncfusion.EJ2 //use Syncfusion components +``` + +#### 3-) Adding Syncfusion styles and scripts to our application + +Firstly, let's install the `@syncfusion/ej2` package from **npm**. + +* Open your **package.json** file and add the `@syncfusion/ej2` package with version **19.3.57**: + +```json +{ + "version": "1.0.0", + "name": "my-app", + "private": true, + "dependencies": { + "@abp/aspnetcore.mvc.ui.theme.basic": "^5.0.0-rc.2", + "@syncfusion/ej2": "^19.3.57" + } +} +``` + +* Then, open the **abp.resourcemapping.js** file and update the **mappings** section: + +```js +module.exports = { + aliases: { + + }, + mappings: { + "@node_modules/@syncfusion/ej2/dist/ej2.min.js": "@libs/syncfusion/", + "@node_modules/@syncfusion/ej2/material.css": "@libs/syncfusion/" + } +}; +``` + +> ABP copies related packages from **node_modules** folder to the **libs** folder by examining this file. You can read this [document](docs.abp.io/en/abp/latest/UI/AspNetCore/Client-Side-Package-Management#mapping-the-library-resources) for more info. + +* Then run the `abp install-libs` to install the dependencies and copy them into the libs folder by your mappings configuration. After running this command, in your **libs** folder it should be a folder named **syncfusion** folder. + +![](./syncfusion-libs.png) + +The last thing we need to do is, add some style and script files provided by Syncfusion, between our head-body tags. + +* We can do this by creating two view components (one for Styles and the other for Scripts). Let's do that. + +First, create a folder structure as shown below under the **Components** folder. + +![](./component-folder-structure.png) + +Then open the related files and add the following codes to each of these files. + +* **Default.cshtml** (/Components/Syncfusion/Script/Default.cshtml) + +```cshtml +@addTagHelper *, Syncfusion.EJ2 //add this line + + + + + + +``` + +* **SyncfusionScriptComponent.cs** + +```csharp +using Microsoft.AspNetCore.Mvc; +using Volo.Abp.AspNetCore.Mvc; + +namespace SyncfusionComponentsDemo.Web.Components.Syncfusion.Script +{ + public class SyncfusionScriptComponent : AbpViewComponent + { + public IViewComponentResult Invoke() + { + return View("~/Components/Syncfusion/Script/Default.cshtml"); + } + } +} +``` + +* **Default.cshtml** (/Components/Syncfusion/Style/Default.cshtml) + +```cshtml + + +``` + +* SyncfusionStyleComponent.cs + +```csharp +using Microsoft.AspNetCore.Mvc; +using Volo.Abp.AspNetCore.Mvc; + +namespace SyncfusionComponentsDemo.Web.Components.Syncfusion.Style +{ + public class SyncfusionStyleComponent : AbpViewComponent + { + public IViewComponentResult Invoke() + { + return View("~/Components/Syncfusion/Style/Default.cshtml"); + } + } +} +``` + +After creating these two components, we can use the [**Layout Hooks**](https://docs.abp.io/en/abp/latest/UI/AspNetCore/Layout-Hooks) system of ABP to inject these two components between head and script tags. + +To do this, open your web module class and update the `ConfigureServices` method as below: + + +```csharp +public override void ConfigureServices(ServiceConfigurationContext context) +{ + var hostingEnvironment = context.Services.GetHostingEnvironment(); + var configuration = context.Services.GetConfiguration(); + + //Register Syncfusion license + var licenseKey = configuration["Syncfusion:LicenseKey"].ToString(); + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(licenseKey: licenseKey); + + Configure(options => + { + //Now, the SyncfusionStyleComponent code will be inserted in the head of the page as the last item. + options.Add(LayoutHooks.Head.Last, typeof(SyncfusionStyleComponent)); + + //the SyncfusionScriptComponent will be inserted in the body of the page as the last item. + options.Add(LayoutHooks.Body.Last, typeof(SyncfusionScriptComponent)); + }); + + ConfigureUrls(configuration); + ConfigureBundles(); + ConfigureAuthentication(context, configuration); + ConfigureAutoMapper(); + ConfigureVirtualFileSystem(hostingEnvironment); + ConfigureLocalizationServices(); + ConfigureNavigationServices(); + ConfigureAutoApiControllers(); + ConfigureSwaggerServices(context.Services); +} +``` + +After injecting the Syncfusion style and script into our application, our configurations have been completed. We can try with a simple component to see if it works as we expected. + +* Let's try with the [Calendar](https://www.syncfusion.com/aspnet-core-ui-controls/calendar) component. Open your **Index.cshtml** file and update with the below content: + +```cshtml +@page +@using Microsoft.AspNetCore.Mvc.Localization +@using SyncfusionComponentsDemo.Localization +@using Volo.Abp.Users +@model SyncfusionComponentsDemo.Web.Pages.IndexModel + +@section styles { + +} + +@section scripts { + +} + +
+

Syncfusion - Calendar Component

+ +
+``` + +* Then when we run the application, we need to see the relevant calendar component as below. + +![](./calendar-component.png) + +### Conclusion + +In this article, we've explained how to integrate the **Syncfusion Components** into our applications. After following this article, you can use the Syncfusion components in your application. + +Thanks for reading the article, I hope you've found it useful :) diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/calendar-component.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/calendar-component.png new file mode 100644 index 0000000000..8e7f36367a Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/calendar-component.png differ diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/component-folder-structure.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/component-folder-structure.png new file mode 100644 index 0000000000..0dabbe0a06 Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/component-folder-structure.png differ diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/copy-license-key.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/copy-license-key.png new file mode 100644 index 0000000000..847be0363d Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/copy-license-key.png differ diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/manage-trial-1.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/manage-trial-1.png new file mode 100644 index 0000000000..8e84229549 Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/manage-trial-1.png differ diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/manage-trial-2.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/manage-trial-2.png new file mode 100644 index 0000000000..57ef370bdb Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/manage-trial-2.png differ diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/syncfusion-libs.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/syncfusion-libs.png new file mode 100644 index 0000000000..d75935d8fd Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/syncfusion-libs.png differ diff --git a/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/syncfusion-package.png b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/syncfusion-package.png new file mode 100644 index 0000000000..6792ea0c32 Binary files /dev/null and b/docs/en/Community-Articles/2021-12-13-Integrating-the-Syncfusion-MVC-Components-to-the-ABP-MVC-UI/syncfusion-package.png differ diff --git a/docs/en/Index.md b/docs/en/Index.md index 84e1155b9c..3f5c3dbf44 100644 --- a/docs/en/Index.md +++ b/docs/en/Index.md @@ -1,6 +1,6 @@ # ABP 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**. +ABP Framework offers an **opinionated architecture** to build enterprise software solutions with **best practices** on top of the **.NET** and the **ASP.NET Core** platforms. It provides the fundamental infrastructure, production-ready startup templates, modules, themes, tooling, guides and documentation to implement that architecture properly and **automate the details** and repetitive works as much as possible. ## Getting Started @@ -56,13 +56,23 @@ See the [Application Modules](Modules/Index.md) document for all pre-built modul 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**. -## Free E-Book: Implementing Domain Driven Design +## Books + +### Mastering ABP Framework + +![abp-book](images/abp-book.png) + +*Mastering ABP Framework* is an ultimate guide to get started and expertise with the ABP Framework. It is authored by Halil İbrahim Kalkan, the creator and the lead developer of the ABP Framework. + +**[You can order it from Amazon now](https://www.amazon.com/Mastering-ABP-Framework-maintainable-implementing-dp-1801079242/dp/1801079242)!** + +### Free E-Book: Implementing Domain Driven Design ![Implementing Domain Driven Design](images/implementing-domain-driven-design-book.png) A **practical guide** for implementing Domain Driven Design (DDD). While the implementation details are **based on the ABP Framework** infrastructure, the basic concepts, principles and models can be applied to any solution, even if it is not a .NET solution. -[Click here to get your free copy](https://abp.io/books/implementing-domain-driven-design?ref=doc). +**[Click here to get your free copy](https://abp.io/books/implementing-domain-driven-design?ref=doc).** ## ABP Community diff --git a/docs/en/Migration-Guides/Abp-5-0-Blazor.md b/docs/en/Migration-Guides/Abp-5-0-Blazor.md index f0c69b679a..326bac55d5 100644 --- a/docs/en/Migration-Guides/Abp-5-0-Blazor.md +++ b/docs/en/Migration-Guides/Abp-5-0-Blazor.md @@ -4,4 +4,16 @@ ## Upgrading to the latest Blazorise -ABP 5.0 uses the latest version of the [Blazorise](https://blazorise.com/) library. Please upgrade the Blazorise NuGet packages in your solution. \ No newline at end of file +ABP 5.0 uses the latest version of the [Blazorise](https://blazorise.com/) library. Please upgrade the Blazorise NuGet packages in your solution. + +## Bootstrap 5 + +ABP 5.0 now works with Bootstrap 5. For details, please refer to the official [migration guide](https://getbootstrap.com/docs/5.0/migration/) provided by Bootstrap. + +Replace `Blazorise.Bootstrap` with `Blazorise.Bootstrap5` package. + +Replace `AddBootstrapProviders()` with `AddBootstrap5Providers()`. + +## Update Bundle + +Use `abp bundle` command to update bundles if you are using Blazor WebAssembly. \ No newline at end of file diff --git a/docs/en/Tutorials/Part-10.md b/docs/en/Tutorials/Part-10.md index 5d5ea9618b..563de95d68 100644 --- a/docs/en/Tutorials/Part-10.md +++ b/docs/en/Tutorials/Part-10.md @@ -948,7 +948,7 @@ Since the HTTP APIs have been changed, you need to update Angular client side [s Run the following command in the `angular` folder (you may need to stop the angular application): ```bash -abp generate-proxy +abp generate-proxy -t ng ``` This command will update the service proxy files under the `/src/app/proxy/` folder. diff --git a/docs/en/Tutorials/Part-2.md b/docs/en/Tutorials/Part-2.md index b84ece9e97..4b29231164 100644 --- a/docs/en/Tutorials/Part-2.md +++ b/docs/en/Tutorials/Part-2.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; @@ -80,13 +80,13 @@ You can see the **book list** returned from the server. You can also check the * Let's **create a new book** using the `create` function: ````js -acme.bookStore.books.book.create({ - name: 'Foundation', - type: 7, - publishDate: '1951-05-24', - price: 21.5 - }).then(function (result) { - console.log('successfully created the book with id: ' + result.id); +acme.bookStore.books.book.create({ + name: 'Foundation', + type: 7, + publishDate: '1951-05-24', + price: 21.5 + }).then(function (result) { + console.log('successfully created the book with id: ' + result.id); }); ```` @@ -187,7 +187,7 @@ namespace Acme.BookStore.Web.Pages.Books { public void OnGet() { - + } } } @@ -461,7 +461,7 @@ For more information, see the [RoutesService document](../UI/Angular/Modifying-t Once the host application is running, execute the following command in the `angular` folder: ```bash -abp generate-proxy +abp generate-proxy -t ng ``` This command will create the following files under the `/src/app/proxy/books` folder: @@ -654,7 +654,7 @@ Open the `Books.razor` and replace the content as the following: > 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 `AbpCrudPageBase` which implements all the CRUD details for us. -* `Entities`, `TotalCount`, `PageSize`, `OnDataGridReadAsync` are defined in the base blass. +* `Entities`, `TotalCount`, `PageSize`, `OnDataGridReadAsync` are defined in the base class. * 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. diff --git a/docs/en/Tutorials/Part-9.md b/docs/en/Tutorials/Part-9.md index d6fa004596..0e271a5e4e 100644 --- a/docs/en/Tutorials/Part-9.md +++ b/docs/en/Tutorials/Part-9.md @@ -605,7 +605,7 @@ function configureRoutes(routes: RoutesService) { Run the following command in the `angular` folder: ```bash -abp generate-proxy +abp generate-proxy -t ng ``` This command generates the service proxy for the author service and the related model (DTO) classes: diff --git a/docs/en/UI/Angular/Service-Proxies.md b/docs/en/UI/Angular/Service-Proxies.md index 18e5a3a0cc..dc8433f7de 100644 --- a/docs/en/UI/Angular/Service-Proxies.md +++ b/docs/en/UI/Angular/Service-Proxies.md @@ -15,7 +15,7 @@ ABP introduces an endpoint that exposes server-side method contracts. When the ` Run the following command in the **root folder** of the angular application: ```bash -abp generate-proxy +abp generate-proxy -t ng ``` The command without any parameters creates proxies only for your own application's services and places them in your default Angular application. There are several parameters you may use to modify this behavior. See the [CLI documentation](../../CLI) for details. diff --git a/docs/en/images/abp-book.png b/docs/en/images/abp-book.png new file mode 100644 index 0000000000..7fd6c34c90 Binary files /dev/null and b/docs/en/images/abp-book.png differ diff --git a/docs/zh-Hans/CLI.md b/docs/zh-Hans/CLI.md index b310f96b2c..b2f3825c64 100644 --- a/docs/zh-Hans/CLI.md +++ b/docs/zh-Hans/CLI.md @@ -29,6 +29,7 @@ dotnet tool update -g Volo.Abp.Cli * **`help`**: 展示ABP CLI的用法帮助信息. * **`new`**:生成基于ABP的[启动模板](Startup-Templates/Index.md). * **`update`**:自动更新的ABP解决方案ABP相关的NuGet和NPM包. +* **`clean`**: 删除当前目录下所有的 `BIN` 和 `OBJ` 子目录. * **`add-package`**: 添加ABP包到项目. * **`add-module`**: 添加[应用模块](https://docs.abp.io/en/abp/latest/Modules/Index)到解决方案. * **`generate-proxy`**: 生成客户端代理以使用HTTP API端点. @@ -129,6 +130,16 @@ abp update [options] * `--check-all`: 分别检查每个包的新版本. 默认是 `false`. * `--version` or `-v`: 指定用于升级的版本. 如果没有指定,则使用最新版本. +### clean + +删除当前目录下所有的 `BIN` 和 `OBJ` 子目录. + +用法: + +````bash +abp clean +```` + ### add-package 通过以下方式将ABP包添加到项目中 diff --git a/docs/zh-Hans/Distributed-Event-Bus.md b/docs/zh-Hans/Distributed-Event-Bus.md index 720560b4be..f16aa0610f 100644 --- a/docs/zh-Hans/Distributed-Event-Bus.md +++ b/docs/zh-Hans/Distributed-Event-Bus.md @@ -45,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 @@ -299,4 +299,4 @@ namespace AbpDemo } ```` -此示例使用AutoMapper的 `AutoMap` 属性配置的映射. 你可以创建一个配置文件类代替. 请参阅AutoMapper文档了解更多选项. \ No newline at end of file +此示例使用AutoMapper的 `AutoMap` 属性配置的映射. 你可以创建一个配置文件类代替. 请参阅AutoMapper文档了解更多选项. diff --git a/docs/zh-Hans/Modules/IdentityServer.md b/docs/zh-Hans/Modules/IdentityServer.md index cb82a640d5..838cdfe3ed 100644 --- a/docs/zh-Hans/Modules/IdentityServer.md +++ b/docs/zh-Hans/Modules/IdentityServer.md @@ -1 +1,173 @@ -TODO... \ No newline at end of file +# 身份服务器模块 + +身份服务器模块提供了一个 [IdentityServer](https://github.com/IdentityServer/IdentityServer4) (IDS) 的完全集成,该框架提供高级身份验证功能,如单点登录和API访问控制.此模块将客户端,资源以及其他 IDS 相关的对象保存到数据库中. + +## 如何安装 + +当你使用 ABP 框架 [创建一个新的解决方案](https://abp.io/get-started) 时,此模块将被预安装(作为 NuGet/NPM 包).你可以继续用其作为包并轻松地获取更新,也可以将其源代码包含在解决方案中(请参阅 `get-source` [CLI](../CLI.md))以开发自定义模块. + +### 源代码 + +可以 [在此处](https://github.com/abpframework/abp/tree/dev/modules/identityserver) 访问源代码.源代码使用 [MIT](https://choosealicense.com/licenses/mit/) 许可,所以你可以免费使用和自定义它. + +## 用户界面 + +此模块使用了领域逻辑和数据库集成,但没有提供任何 UI.如果你需要动态添加客户端和资源, 管理 UI 是非常有用的.在这种情况下,你可以自己构建管理 UI,或者考虑购买为此模块提供了管理 UI 的 [ABP 商业版](https://commercial.abp.io/). + +## 与其他模块的关系 + +此模块基于 [身份模块](Identity.md) 并且[账户模块](Account.md) 有一个 [集成包](https://www.nuget.org/packages/Volo.Abp.Account.Web.IdentityServer). + +## 选项 + +### AbpIdentityServerBuilderOptions + +`AbpIdentityServerBuilderOptions` 在你的身份服务器 [模块](https://docs.abp.io/en/abp/latest/Module-Development-Basics) 中的 `PreConfigureServices` 方法中配置.例如: + +````csharp +public override void PreConfigureServices(ServiceConfigurationContext context) +{ + PreConfigure(builder => + { + //Set options here... + }); +} +```` + +`AbpIdentityServerBuilderOptions` 属性: + +* `UpdateJwtSecurityTokenHandlerDefaultInboundClaimTypeMap` (默认值:true):更新 `JwtSecurityTokenHandler.DefaultInboundClaimTypeMap` 使其与身份服务器声明兼容. +* `UpdateAbpClaimTypes` (默认值:true):更新 `AbpClaimTypes` 与身份服务器声明兼容. +* `IntegrateToAspNetIdentity` (默认值:true):集成到 ASP.NET Identity. +* `AddDeveloperSigningCredential` (默认值:true):设置为 false 禁止调用 IIdentityServerBuilder 中的 `AddDeveloperSigningCredential()`. + +`IIdentityServerBuilder` 可以在你的身份服务器 [模块](https://docs.abp.io/en/abp/latest/Module-Development-Basics) 中的 `PreConfigureServices` 方法中配置.例如: + +````csharp +public override void PreConfigureServices(ServiceConfigurationContext context) +{ + PreConfigure(builder => + { + builder.AddSigningCredential(...); + }); +} +```` + +## 内部结构 + +### 领域层 + +#### 聚合 + +##### API 资源 + +需要 API 资源来允许客户端请求访问令牌. + +* `ApiResource` (聚合根):表示系统中的 API 资源. + * `ApiSecret` (集合):API 资源的密钥. + * `ApiScope` (集合):API 资源的作用域. + * `ApiResourceClaim` (集合):API 资源的声明. + +##### 客户端 + +客户端表示可以从你的身份服务器请求令牌的应用程序. + +* `Client` (聚合根):表示一个身份服务器的客户端应用程序. + * `ClientScope` (集合):客户端的作用域. + * `ClientSecret` (集合):客户端的密钥. + * `ClientGrantType` (集合):客户端的授权类型. + * `ClientCorsOrigin` (集合):客户端的 CORS 源. + * `ClientRedirectUri` (集合):客户端的重定向 URIs. + * `ClientPostLogoutRedirectUri` (集合):客户端的登出重定向 URIs. + * `ClientIdPRestriction` (集合):客户端的提供程序约束. + * `ClientClaim` (集合):客户端的声明. + * `ClientProperty` (集合):客户端的自定义属性. + +##### 持续化授权 + +持续化授权存储了授权码,刷新令牌和用户准许. + +* `PersistedGrant` (聚合根):表示为身份服务器持续化授权. + +##### 身份资源 + +身份资源是用户的用户 ID ,名称或邮件地址等数据. + +* `IdentityResource` (聚合根):表示与身份服务器的身份资源. + * `IdentityClaim` (集合):身份资源的声明. + +#### 仓储 + +为此模块定义了以下自定义仓储: + +* `IApiResourceRepository` +* `IClientRepository` +* `IPersistentGrantRepository` +* `IIdentityResourceRepository` + +#### 领域服务 + +此模块不包含任何领域服务,但重写了下面的服务; + +* `AbpProfileService` (当 `AbpIdentityServerBuilderOptions.IntegrateToAspNetIdentity` 为 true 时使用) +* `AbpClaimsService` +* `AbpCorsPolicyService` + +### 设置 + +此模块未定义任何设置. + +### 应用层 + +#### 应用服务 + +* `ApiResourceAppService` (实现 `IApiResourceAppService`):实现了 API 资源管理 UI 的用例. +* `IdentityServerClaimTypeAppService` (实现 `IIdentityServerClaimTypeAppService`):用于获取声明列表. +* `ApiResourceAppService` (实现 `IApiResourceAppService`):实现了 API 管理资源 UI 的用例. +* `IdentityResourceAppService` (实现 `IIdentityResourceAppService`):实现了身份资源管理 UI 的用例. + +### 数据库提供程序 + +#### 公共 + +##### 表/集合 前缀 & 架构 + +所有表/集合都使用 `IdentityServer` 作为默认前缀.如果你需要改变表的前缀或设置一个架构名称(如果你的数据库提供程序支持),请设置 `AbpIdentityServerDbProperties` 类的静态属性. + +##### 连接字符串 + +此模块使用 `AbpIdentityServer` 作为连接字符串的名称.如果你没有用这个名称定义连接字符串,它将回退到 `Default` 连接字符串. + +有关详细信息,请参阅 [连接字符串](https://docs.abp.io/en/abp/latest/Connection-Strings) 文档. + +#### EF Core + +##### 表 + +* **IdentityServerApiResources** + * IdentityServerApiSecrets + * IdentityServerApiScopes + * IdentityServerApiScopeClaims + * IdentityServerApiClaims +* **IdentityServerClients** + * IdentityServerClientScopes + * IdentityServerClientSecrets + * IdentityServerClientGrantTypes + * IdentityServerClientCorsOrigins + * IdentityServerClientRedirectUris + * IdentityServerClientPostLogoutRedirectUris + * IdentityServerClientIdPRestrictions + * IdentityServerClientClaims + * IdentityServerClientProperties +* **IdentityServerPersistedGrants** +* **IdentityServerIdentityResources** + * IdentityServerIdentityClaims + +#### MongoDB + +##### 集合 + +* **IdentityServerApiResources** +* **IdentityServerClients** +* **IdentityServerPersistedGrants** +* **IdentityServerIdentityResources** diff --git a/docs/zh-Hans/Tutorials/Part-2.md b/docs/zh-Hans/Tutorials/Part-2.md index decddfebff..fe0dd84c45 100644 --- a/docs/zh-Hans/Tutorials/Part-2.md +++ b/docs/zh-Hans/Tutorials/Part-2.md @@ -2,26 +2,10 @@ ````json //[doc-params] { - "UI": ["MVC","NG"], + "UI": ["MVC","Blazor","BlazorServer","NG"], "DB": ["EF","Mongo"] } ```` - -{{ -if UI == "MVC" - DB="ef" - DB_Text="Entity Framework Core" - UI_Text="mvc" -else if UI == "NG" - DB="mongodb" - DB_Text="MongoDB" - UI_Text="angular" -else - DB ="?" - UI_Text="?" -end -}} - ## 关于本教程 在本系列教程中, 你将构建一个名为 `Acme.BookStore` 的用于管理书籍及其作者列表的基于ABP的应用程序. 它是使用以下技术开发的: @@ -44,16 +28,30 @@ end ## 下载源码 -本教程根据你的**UI** 和 **Database**偏好有多个版,我们准备了两种可供下载的源码组合: +本教程根据你的**UI** 和 **数据库**偏好有多个版本,我们准备了几种可供下载的源码组合: * [MVC (Razor Pages) UI 与 EF Core](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore) +* [Blazor UI 与 EF Core](https://github.com/abpframework/abp-samples/tree/master/BookStore-Blazor-EfCore) * [Angular UI 与 MongoDB](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb) +> 如果你在Windows中遇到 "文件名太长" or "解压错误", 很可能与Windows最大文件路径限制有关. Windows文件路径的最大长度为250字符. 为了解决这个问题,参阅 [在Windows 10中启用长路径](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later). + +> 如果你遇到与Git相关的长路径错误, 尝试使用下面的命令在Windows中启用长路径. 参阅 https://github.com/msysgit/msysgit/wiki/Git-cannot-create-a-file-or-directory-with-a-long-path +> `git config --system core.longpaths true` + +{{if UI == "MVC" && DB == "EF"}} + +### 视频教程 + +本章也被录制为视频教程 **发布在YouTube**. + +{{end}} + {{if UI == "MVC"}} ## 动态JavaScript代理 -通常在 **JavaScript** 端通过AJAX调用HTTP API端点. 你可以使用 `$.ajax` 或其他工具来调用端点. 但是ABP提供了更好的方法. +在 **JavaScript** 端通过AJAX调用HTTP API端点是常见的做法. 你可以使用 `$.ajax` 或其他工具来调用端点. 但是ABP提供了更好的方法. ABP**动态**为所有API端点创建 **[JavaScript代理](../UI/AspNetCore/Dynamic-JavaScript-Proxies.md)**. 所以你可以像调用**Javascript本地方法**一样使用任何**端点**. @@ -79,21 +77,21 @@ acme.bookStore.books.book.getList({}).done(function (result) { console.log(resul ![bookstore-getlist-result-network](images/bookstore-getlist-result-network.png) -Let's **create a new book** using the `create` function: - 让我们使用 `create` 函数**创建一本书**: ````js -acme.bookStore.books.book.create({ - name: 'Foundation', - type: 7, - publishDate: '1951-05-24', - price: 21.5 - }).then(function (result) { - console.log('successfully created the book with id: ' + result.id); +acme.bookStore.books.book.create({ + name: 'Foundation', + type: 7, + publishDate: '1951-05-24', + price: 21.5 + }).then(function (result) { + console.log('successfully created the book with id: ' + result.id); }); ```` +> 如果你下载了本教程的源代码并按照示例中的步骤操作,你需要传递`authorId`参数给创建方法以**创建一本新书**. + 您应该在控制台中看到类似以下的消息: ````text @@ -102,7 +100,7 @@ successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246 检查数据库中的 `Books` 表你会看到新的一行. 你可以自己尝试使用 `get`, `update` 和 `delete` 函数. -我们将利用这些动态代理功能在接下来的章节来与服务器通信. +在接下来的章节,我们将利用这些动态代理函数与服务器通信. {{end}} @@ -112,7 +110,7 @@ successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246 本地化文本位于 `Acme.BookStore.Domain.Shared` 项目的 `Localization/BookStore` 文件夹下: -![bookstore-localization-files](./images/bookstore-localization-files-v2.png) +![bookstore-localization-files](images/bookstore-localization-files-v2.png) 打开 `en.json` (*英文翻译*)文件并更改内容,如下所示: @@ -154,7 +152,7 @@ successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246 * 为按钮项添加 `Menu:` 前缀. * 使用 `Enum::` 命名约定来本地化枚举成员. 当您这样做时ABP可以在某些适当的情况下自动将枚举本地化. -如果未在本地化文件中定义文本,则文本将**回退**到本地化键(作为ASP.NET Core的标准行为). +如果未在本地化文件中定义文本,则文本将**回退**到本地化键(ASP.NET Core的标准行为). > ABP本地化系统建立在[ASP.NET Core标准本地化](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization)系统之上,并以多种方式进行了扩展. 有关详细信息请参见[本地化文档](../Localization.md). @@ -162,7 +160,7 @@ successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246 ## 创建图书页面 -是时候创建可见的和可用的东西了! 代替经典的MVC,我们将使用微软推荐的[Razor Pages UI](https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/razor-pages/razor-pages-start). +是时候创建可见的和可用的东西了! 我们将使用微软推荐的[Razor Pages UI](https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/razor-pages/razor-pages-start),而不是经典的MVC. 在 `Acme.BookStore.Web` 项目的 `Pages` 文件夹下创建一个名为新的 `Books` 的文件夹. 然后在文件夹右键选择 **添加 > Razor Page** 菜单. 输入名称 `Index`: @@ -189,13 +187,13 @@ namespace Acme.BookStore.Web.Pages.Books { public void OnGet() { - + } } } ``` -### 将Book页面添加到主菜单 +### 将图书页面添加到主菜单 打开 `Menus` 文件夹中的 `BookStoreMenuContributor` 类,在 `ConfigureMainMenuAsync` 方法的底部添加如下代码: @@ -223,9 +221,7 @@ context.Menu.AddItem( ### 图书列表 -We will use the [Datatables.net](https://datatables.net/) jQuery library to show the book list. Datatables library completely work via AJAX, it is fast, popular and provides a good user experience. - -我们将使用[Datatables.net](https://datatables.net/)JQuery插件来显示页面上的表格列表. [Datatables](https://datatables.net/)可以完全通过AJAX工作,速度快,并提供良好的用户体验. +我们将使用[Datatables.net](https://datatables.net/)JQuery插件来显示图书列表. [Datatables](https://datatables.net/)可以完全通过AJAX工作,速度快,并提供良好的用户体验. > Datatables插件在启动模板中配置,因此你可以直接在任何页面中使用它,无需在页面中引用样式和脚本文件. @@ -261,7 +257,7 @@ We will use the [Datatables.net](https://datatables.net/) jQuery library to show 在 `Pages/Books/` 文件夹中创建 `index.js`文件 -![bookstore-index-js-file](./images/bookstore-index-js-file-v3.png) +![bookstore-index-js-file](images/bookstore-index-js-file-v3.png) `index.js` 的内容如下: @@ -321,8 +317,8 @@ $(function () { ```` * `abp.localization.getResource` 获取一个函数,该函数用于使用服务器端定义的相同JSON文件对文本进行本地化. 通过这种方式你可以与客户端共享本地化值. -* `abp.libs.datatables.normalizeConfiguration`是另一个辅助方法.不是必须的, 但是它通过为缺少的选项提供常规值来简化数据表配置. -* `abp.libs.datatables.createAjax`是帮助ABP的动态JavaScript API代理跟[Datatable](https://datatables.net/)的格式相适应的辅助方法. +* `abp.libs.datatables.normalizeConfiguration`是一个辅助方法.不是必须的, 但是它通过为缺省的选项提供约定的值来简化[Datatables](https://datatables.net/)配置. +* `abp.libs.datatables.createAjax`是另一个辅助方法,用来适配ABP的动态JavaScript API代理和[Datatable](https://datatables.net/)期望的参数格式. * `acme.bookStore.books.book.getList` 是动态JavaScript代理函数(上面已经介绍过了) * [luxon](https://moment.github.io/luxon/) 库也是该解决方案中预先配置的标准库,你可以轻松地执行日期/时间操作. @@ -334,15 +330,13 @@ $(function () { ![Book list](images/bookstore-book-list-3.png) -这是一个完全正常工作的服务端分页,排序和本地化的图书列表. - -{{end}} +这是一个可以正常工作的,服务端分页,排序和本地化的图书列表. {{if UI == "NG"}} ## 安装NPM包 ->注意: 本教程基于ABP Framework v3.0.3+. 如果你的项目版本较旧,请升级您的解决方案. 如果要升级现有的v2.x项目,请参阅[迁移指南](../UI/Angular/Migration-Guide-v3.md). +>注意: 本教程基于ABP Framework v3.1.0+. 如果你的项目版本较旧,请升级您的解决方案. 如果要升级现有的v2.x项目,请参阅[迁移指南](../UI/Angular/Migration-Guide-v3.md). 在 `angular` 目录下打开命令行窗口,选择 `yarn` 命令安装NPM包: @@ -357,9 +351,7 @@ yarn - [Ng Bootstrap](https://ng-bootstrap.github.io/#/home) 用做UI组件库. - [ngx-datatable](https://swimlane.gitbook.io/ngx-datatable/) 用做 datatable 类库. -### BookModule - -运行以下命令创建一个名为 `BookModule` 的新模块: +运行以下命令在angular应用程序根目录创建一个名为 `BookModule` 的新模块: ```bash yarn ng generate module book --module app --routing --route books @@ -417,7 +409,7 @@ const routes: Routes = [ ]; ```` -现在打开 `src/app/route.provider.ts` 以下替换 `configureRoutes` 函数: +现在打开 `src/app/route.provider.ts` 替换 `configureRoutes` 函数为以下代码: ```js function configureRoutes(routes: RoutesService) { @@ -450,27 +442,31 @@ function configureRoutes(routes: RoutesService) { `RoutesService` 是ABP框架提供的用于配置主菜单和路由的服务. -* `path` 路由的URL. +* `path` 路由的URL. * `name` 菜单项的名称(参阅[本地化文档](../UI/Angular/Localization.md)了解更多). -* `iconClass` 菜单项的图标(你可以使用默认的[Font Awesome](https://fontawesome.com/)图标). -* `order` 菜单项的排序.我们定义了101,它显示在 "Administration" 项的后面. -* `layout` BooksModule路由的布局. 可以定义 `eLayoutType.application`, `eLayoutType.account` 或 `eLayoutType.empty`. +* `iconClass` 菜单项的图标(你可以使用默认的[Font Awesome](https://fontawesome.com/)图标). +* `order` 菜单项的排序. +* `layout` BooksModule路由的布局. (有三个预定义的布局类型: `eLayoutType.application`, `eLayoutType.account` 或 `eLayoutType.empty`). + +更多信息请参阅[RoutesService 文档](../UI/Angular/Modifying-the-Menu.md#via-routesservice). -更多信息请参阅[RoutesService 文档](https://docs.abp.io/en/abp/latest/UI/Angular/Modifying-the-Menu.md#via-routesservice). +### 生成服务代理 -### 生成代理 +[ABP CLI](../CLI.md) 提供 `generate-proxy` 命令为HTTP APIs生成客户端代理.有了这些代理,在客户端使用HTTP APIs变得更加方便. 运行 `generate-proxy` 命令前, 你的 host 必须正在运行. -ABP CLI提供了 `generate-proxy` 命令为你的服务HTTP API生成客户端代理简化客户端使用服务的成本. 运行 `generate-proxy` 命令前你的host必须正在运行. 参阅 [CLI 文档](../CLI.md). +> **警告**: 使用IIS Express时有一个问题; 它不允许从另一个进程连接应用程序. 如果你使用Visual Studio, 在运行按钮的下拉框中选择`Acme.BookStore.HttpApi.Host`,不要选择IIS Express, 如下图: -在 `angular` 文件夹下运行以下命令: +![vs-run-without-iisexpress](images/vs-run-without-iisexpress.png) + +启动host应用程序后,在 `angular` 文件夹下运行以下命令: ```bash -abp generate-proxy +abp generate-proxy -t ng ``` -生成的文件如下: +这个命令将在`/src/app/proxy/books`文件夹下产生以下文件: -![Generated files](./images/generated-proxies-2.png) +![Generated files](images/generated-proxies-3.png) ### BookComponent @@ -479,8 +475,7 @@ abp generate-proxy ```js import { ListService, PagedResultDto } from '@abp/ng.core'; import { Component, OnInit } from '@angular/core'; -import { BookDto } from './models'; -import { BookService } from './services'; +import { BookService, BookDto } from '@proxy/books'; @Component({ selector: 'app-book', @@ -494,7 +489,7 @@ export class BookComponent implements OnInit { constructor(public readonly list: ListService, private bookService: BookService) {} ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); + const bookStreamCreator = (query) => this.bookService.getList(query); this.list.hookToQuery(bookStreamCreator).subscribe((response) => { this.book = response; @@ -503,8 +498,8 @@ export class BookComponent implements OnInit { } ``` -* 我们注入了生成的 `BookService`. -* 我们实现了 [ListService](https://docs.abp.io/en/abp/latest/UI/Angular/List-Service),它是一个公用服务,提供了简单的分页,排序和搜索. +* 我们引入并注入了生成的 `BookService`. +* 我们使用 [ListService](../UI/Angular/List-Service.md),它是一个工具服务,提供了易用的分页,排序和搜索. 打开 `/src/app/book/book.component.html` 用以下内容替换它: @@ -545,9 +540,138 @@ export class BookComponent implements OnInit { 现在你可以在浏览器看到最终结果: -![Book list final result](./images/bookstore-book-list.png) +![图书列表最终结果](images/bookstore-book-list.png) -{{end}} +{{else if UI == "Blazor" || UI == "BlazorServer"}} + +## 创建图书页面 + +是时候创建可见和可用的东西了! 右击`Acme.BookStore.Blazor`项目下的`Pages`文件夹,新建一个名为`Books.razor`的**razor组件**. + +![blazor-add-books-component](images/blazor-add-books-component.png) + +用以下内容替换这个组件的内容: + +````html +@page "/books" + +

Books

+ +@code { + +} +```` + +### 将图书页面添加到主菜单 + +打开`Blazor`项目中的`BookStoreMenuContributor`类,在 `ConfigureMainMenuAsync` 方法的底部添加如下代码: + +````csharp +context.Menu.AddItem( + new ApplicationMenuItem( + "BooksStore", + l["Menu:BookStore"], + icon: "fa fa-book" + ).AddItem( + new ApplicationMenuItem( + "BooksStore.Books", + l["Menu:Books"], + url: "/books" + ) + ) +); +```` + +运行项目,使用用户名 `admin` 和密码 `1q2w3E*` 登录到应用程序. 看到新菜单项已添加到顶部栏: + +![blazor-menu-bookstore](images/blazor-menu-bookstore.png) + +点击BookStore下的Books子菜单项就会跳转到空的图书页面. + +### 图书列表 + +我们将使用[Blazorise library](https://blazorise.com/)作为UI组件.它是一个强大的库,支持主要的HTML/CSS框架,包括Bootstrap. + +ABP提供了一个通用的基类,`AbpCrudPageBase<...>`,用来创建CRUD风格的页面.这个基类兼容用来构建`IBookAppService`的`ICrudAppService`.所以我们从`AbpCrudPageBase`继承,获得标准CRUD的默认实现. + +打开`Books.razor` 并把内容修改成下面这样: + +````xml +@page "/books" +@using Volo.Abp.Application.Dtos +@using Acme.BookStore.Books +@using Acme.BookStore.Localization +@using Microsoft.Extensions.Localization +@inject IStringLocalizer L +@inherits AbpCrudPageBase + + + +

@L["Books"]

+
+ + + + + + + @L[$"Enum:BookType:{(int)context.Type}"] + + + + + @context.PublishDate.ToShortDateString() + + + + + + + @context.CreationTime.ToLongDateString() + + + + + +
+```` + +> 如果你可以编译并运行成功,但看到一些语法错误.你可以忽略这些错误,因为Visual Studio处理Blazor还有一些bug. + +* `AbpCrudPageBase`实现了所有的CRUD细节,我们从它继承. +* `Entities`, `TotalCount`, `PageSize`, `OnDataGridReadAsync`定义在基类中. +* 注入`IStringLocalizer` (作为`L`对象),用于本地化. + +虽然上面的代码非常容易理解,你仍然可以查看Blazorise [Card](https://blazorise.com/docs/components/card/)和[DataGrid](https://blazorise.com/docs/extensions/datagrid/)文档以更好地理解它们. + +#### 关于AbpCrudPageBase + +对于图书页面,我们将持续从`AbpCrudPageBase`获得益处. 你可以只注入`IBookAppService`并自己执行所有的服务端调用(感谢ABP的[动态C# HTTP API客户端代理](../API/Dynamic-CSharp-API-Clients.md)系统). + +## 运行最终应用程序 + +你可以运行应用程序!该部分的最终用户界面如下所示: + +![blazor-bookstore-book-list](images/blazor-bookstore-book-list.png) + +这是一个可以正常工作的,服务端分页,排序和本地化的图书列表. + +{{end # UI }} ## 下一章 diff --git a/docs/zh-Hans/Tutorials/Part-3.md b/docs/zh-Hans/Tutorials/Part-3.md index 90dd1326c3..6a9740730d 100644 --- a/docs/zh-Hans/Tutorials/Part-3.md +++ b/docs/zh-Hans/Tutorials/Part-3.md @@ -2,27 +2,10 @@ ````json //[doc-params] { - "UI": ["MVC","NG"], + "UI": ["MVC","Blazor","BlazorServer","NG"], "DB": ["EF","Mongo"] } ```` -{{ -if UI == "MVC" - UI_Text="mvc" -else if UI == "NG" - UI_Text="angular" -else - UI_Text="?" -end -if DB == "EF" - DB_Text="Entity Framework Core" -else if DB == "Mongo" - DB_Text="MongoDB" -else - DB_Text="?" -end -}} - ## 关于本教程 在本系列教程中, 你将构建一个名为 `Acme.BookStore` 的用于管理书籍及其作者列表的基于ABP的应用程序. 它是使用以下技术开发的: @@ -45,16 +28,30 @@ end ## 下载源码 -本教程根据你的**UI** 和 **Database**偏好有多个版,我们准备了两种可供下载的源码组合: +本教程根据你的**UI** 和 **数据库**偏好有多个版本,我们准备了几种可供下载的源码组合: * [MVC (Razor Pages) UI 与 EF Core](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore) +* [Blazor UI 与 EF Core](https://github.com/abpframework/abp-samples/tree/master/BookStore-Blazor-EfCore) * [Angular UI 与 MongoDB](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb) +> 如果你在Windows中遇到 "文件名太长" or "解压错误", 很可能与Windows最大文件路径限制有关. Windows文件路径的最大长度为250字符. 为了解决这个问题,参阅 [在Windows 10中启用长路径](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later). + +> 如果你遇到与Git相关的长路径错误, 尝试使用下面的命令在Windows中启用长路径. 参阅 https://github.com/msysgit/msysgit/wiki/Git-cannot-create-a-file-or-directory-with-a-long-path +> `git config --system core.longpaths true` + +{{if UI == "MVC" && DB == "EF"}} + +### 视频教程 + +本章也被录制为视频教程 **发布在YouTube**. + +{{end}} + {{if UI == "MVC"}} ## 创建新书籍 -通过本节, 你将会了解如何创建一个 modal form 来实现新增书籍的功能. 最终成果如下图所示: +通过本节, 你将会了解如何创建一个 modal form 实现新增书籍的功能. model dialog将如下图所示: ![bookstore-create-dialog](./images/bookstore-create-dialog-2.png) @@ -66,7 +63,7 @@ end #### CreateModal.cshtml.cs -打开 `CreateModal.cshtml.cs` 代码文件,用如下代码替换 `CreateModalModel` 类的实现: +打开 `CreateModal.cshtml.cs` 代码文件(`CreateModalModel` 类),替换成以下代码: ````C# using System.Threading.Tasks; @@ -101,10 +98,10 @@ namespace Acme.BookStore.Web.Pages.Books } ```` -* 该类派生于 `BookStorePageModel` 而非默认的 `PageModel`. `BookStorePageModel` 继承了 `PageModel` 并且添加了一些可以被你的page model类使用的通用属性和方法. +* 该类派生于 `BookStorePageModel` 而非默认的 `PageModel`. `BookStorePageModel` 间接继承了 `PageModel` 并且添加了一些可以被你的page model类使用的通用属性和方法. * `Book` 属性上的 `[BindProperty]` 特性将post请求提交上来的数据绑定到该属性上. * 该类通过构造函数注入了 `IBookAppService` 应用服务,并且在 `OnPostAsync` 处理程序中调用了服务的 `CreateAsync` 方法. -* 它在 `OnGet` 方法中创建一个新的 `CreateUpdateBookDto` 对象。 ASP.NET Core不需要像这样创建一个新实例就可以正常工作. 但是它不会为你创建实例,并且如果你的类在类构造函数中具有一些默认值分配或代码执行,它们将无法工作. 对于这种情况,我们为某些 `CreateUpdateBookDto` 属性设置了默认值. +* 它在 `OnGet` 方法中创建一个新的 `CreateUpdateBookDto` 对象。 ASP.NET Core不需要像这样创建一个新实例就可以正常工作. 但是它不会为你创建实例,并且如果你的类在类构造函数中赋值一些默认值或执行一些代码,它们将无法工作. 对于这种情况,我们为某些 `CreateUpdateBookDto` 属性设置了默认值. #### CreateModal.cshtml @@ -134,10 +131,9 @@ namespace Acme.BookStore.Web.Pages.Books * 这个 modal 使用 `abp-dynamic-form` [tag Helper](../UI/AspNetCore/Tag-Helpers/Dynamic-Forms.md) 根据 `CreateBookViewModel` 类自动构建了表单. * `abp-model` 指定了 `Book` 属性为模型对象. -* `data-ajaxForm` 设置了表单通过AJAX提交,而不是经典的页面回发. * `abp-form-content` tag helper 作为表单控件渲染位置的占位符 (这是可选的,只有你在 `abp-dynamic-form` 中像本示例这样添加了其他内容才需要). -> 提示: 就像在本示例中一样,`Layout` 应该为 `null`,因为当通过AJAX加载模态时,我们不希望包括所有布局. +> 提示: 就像在本示例中一样,`Layout` 应该为 `null`,因为当通过AJAX加载模态窗口时,我们不希望包括所有布局. ### 添加 "New book" 按钮 @@ -195,9 +191,9 @@ namespace Acme.BookStore.Web.Pages.Books 如下图所示,只是在表格 **右上方** 添加了 **New book** 按钮: -![bookstore-new-book-button](./images/bookstore-new-book-button-2.png) +![bookstore-new-book-button](images/bookstore-new-book-button-2.png) -打开 `Pages/book/index.js` 在 `datatable` 配置代码后面添加如下代码: +打开 `Pages/Book/Index.js` 在 `datatable` 配置代码后面添加如下代码: ````js var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal'); @@ -212,9 +208,9 @@ $('#NewBookButton').click(function (e) { }); ```` -* `abp.ModalManager` 是一个在客户端打开和管理modal的辅助类.它基于Twitter Bootstrap的标准modal组件通过简化的API抽象隐藏了许多细节. +* `abp.ModalManager` 是一个在客户端管理modal的辅助类.它内部使用了Twitter Bootstrap的标准modal组件,但通过简化的API抽象了许多细节. * `createModal.onResult(...)` 用于在创建书籍后刷新数据表格. -* `createModal.open();` 用于打开模态创建新书籍. +* `createModal.open();` 用于打开modal创建新书籍. `Index.js` 的内容最终如下所示: @@ -335,8 +331,8 @@ namespace Acme.BookStore.Web.Pages.Books } ```` -* `[HiddenInput]` 和 `[BindProperty]` 是标准的 ASP.NET Core MVC 特性.这里启用 `SupportsGet` 从Http请求的查询字符串中获取Id的值. -* 在 `OnGetAsync` 方法中,将 `BookAppService.GetAsync` 方法返回的 `BookDto` 映射成 `CreateUpdateBookDto` 并赋值给Book属性. +* `[HiddenInput]` 和 `[BindProperty]` 是标准的 ASP.NET Core MVC 特性.这里启用 `SupportsGet` 从Http请求的查询字符串参数中获取Id的值. +* 在 `OnGetAsync` 方法中, 我们从 `BookAppService` 获得 `BookDto` ,并将它映射成DTO对象 `CreateUpdateBookDto`. * `OnPostAsync` 方法直接使用 `BookAppService.UpdateAsync` 来更新实体. ### BookDto 到 CreateUpdateBookDto 对象映射 @@ -391,10 +387,10 @@ namespace Acme.BookStore.Web 这个页面内容和 `CreateModal.cshtml` 非常相似,除了以下几点: -* 它包含`id`属性的`abp-input`, 用于存储编辑书的 `id` (它是隐藏的Input) +* 它包含`id`属性的`abp-input`, 用于存储被编辑书籍的 `id` (它是隐藏的Input) * 此页面指定的post地址是`Books/EditModal`. -### 为表格添加 "操作(Actions)" 下拉菜单 +### 为表格添加 "操作(Actions)" 下拉菜单 我们将为表格每行添加下拉按钮 ("Actions"): @@ -516,9 +512,9 @@ $(function () { } ```` -* `confirmMessage` 用来在实际执行 `action` 之前向用户进行确认. -* 通过javascript代理方法 `acme.bookStore.books.book.delete(...)` 执行一个AJAX请求来删除一个book实体. -* `abp.notify.info` 用来在执行删除操作后显示一个toastr通知信息. +* `confirmMessage` 执行 `action` 前向用户进行确认. +* `acme.bookStore.books.book.delete(...)` 执行一个AJAX请求删除一个book. +* `abp.notify.info` 执行删除操作后显示一个通知信息. 由于我们使用了两个新的本地化文本(`BookDeletionConfirmationMessage`和`SuccesslyDeleted`),因此你需要将它们添加到本地化文件(`Acme.BookStore.Domain.Shared`项目的`Localization/BookStore`文件夹下的`en.json`): @@ -640,7 +636,7 @@ $(function () { ## 创建新书籍 -下面的章节中,你将学习到如何创建一个新的模态对话框来新增书籍. +下面的章节中,你将学习到如何创建一个新的模态窗口新增书籍. ### BookComponent @@ -649,8 +645,7 @@ $(function () { ```js import { ListService, PagedResultDto } from '@abp/ng.core'; import { Component, OnInit } from '@angular/core'; -import { BookDto } from './models'; -import { BookService } from './services'; +import { BookService, BookDto } from '@proxy/books'; @Component({ selector: 'app-book', @@ -666,7 +661,7 @@ export class BookComponent implements OnInit { constructor(public readonly list: ListService, private bookService: BookService) {} ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); + const bookStreamCreator = (query) => this.bookService.getList(query); this.list.hookToQuery(bookStreamCreator).subscribe((response) => { this.book = response; @@ -680,7 +675,8 @@ export class BookComponent implements OnInit { } ``` -* 我们定义了一个名为 `isModalOpen` 的变量和 `createBook` 方法. +* 我们定义了一个名为 `isModalOpen` 的属性和 `createBook` 方法. + 打开 `/src/app/book/book.component.html` 做以下更改: @@ -690,9 +686,9 @@ export class BookComponent implements OnInit {
{%{{{ '::Menu:Books' | abpLocalization }}}%}
-
+
- +
- +
@@ -726,11 +722,11 @@ export class BookComponent implements OnInit { ``` * 添加了 `New book` 按钮到卡片头部. -* 添加了 `abp-modal` 渲染模态框,允许用户创建新书. `abp-modal` 是显示模态框的预构建组件. 你也可以使用其它方法显示模态框,但 `abp-modal` 提供了一些附加的好处. +* 添加了 `abp-modal` 渲染模态框,允许用户创建新书. `abp-modal` 是显示模态框的预构建组件. 你也可以使用其它方法显示模态框,但 `abp-modal` 提供了一些额外的好处. 你可以打开浏览器,点击**New book**按钮看到模态框. -![Empty modal for new book](./images/bookstore-empty-new-book-modal.png) +![Empty modal for new book](images/bookstore-empty-new-book-modal.png) ### 添加响应式表单 @@ -741,8 +737,7 @@ export class BookComponent implements OnInit { ```js import { ListService, PagedResultDto } from '@abp/ng.core'; import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from './models'; // add BookType -import { BookService } from './services'; +import { BookService, BookDto, bookTypeOptions } from '@proxy/books'; // add bookTypeOptions import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // add this @Component({ @@ -756,12 +751,8 @@ export class BookComponent implements OnInit { form: FormGroup; // add this line - bookType = BookType; // add this line - // add bookTypes as a list of BookType enum members - bookTypes = Object.keys(this.bookType).filter( - (key) => typeof this.bookType[key] === 'number' - ); + bookTypes = bookTypeOptions; isModalOpen = false; @@ -772,7 +763,7 @@ export class BookComponent implements OnInit { ) {} ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); + const bookStreamCreator = (query) => this.bookService.getList(query); this.list.hookToQuery(bookStreamCreator).subscribe((response) => { this.book = response; @@ -800,7 +791,7 @@ export class BookComponent implements OnInit { return; } - this.bookService.createByInput(this.form.value).subscribe(() => { + this.bookService.create(this.form.value).subscribe(() => { this.isModalOpen = false; this.form.reset(); this.list.get(); @@ -809,12 +800,11 @@ export class BookComponent implements OnInit { } ``` -* 导入了 `FormGroup, FormBuilder and Validators`. +* 从` @angular/forms `导入了 `FormGroup, FormBuilder and Validators`. * 添加了 `form: FormGroup` 变量. -* 添加了 `bookType` 属性,你可以从模板中获取 `BookType` 枚举成员. * 添加了 `bookTypes` 属性作为 `BookType` 枚举成员列表. 将在表单选项中使用. -* 我们注入了 `fb: FormBuilder` 服务到构造函数. [FormBuilder](https://angular.io/api/forms/FormBuilder) 服务为生成控件提供了方便的方法. 它减少了构建复杂表单所需的样板文件的数量. -* 我们添加了 `buildForm` 方法到文件末尾, 在 `createBook` 方法调用 `buildForm()` 方法. 该方法创建一个响应式表单去创建新书. +* 我们注入了 `FormBuilder` 到构造函数. [FormBuilder](https://angular.io/api/forms/FormBuilder) 提供了简便的方法生成表单控件. 它减少了构建复杂表单所需的样板文件的数量. +* 我们添加了 `buildForm` 方法到文件末尾, 在 `createBook` 方法调用 `buildForm()` 方法. * 添加了`save` 方法. 打开 `/src/app/book/book.component.html`,使用以下内容替换 ` `: @@ -836,7 +826,7 @@ export class BookComponent implements OnInit { * @@ -897,13 +887,12 @@ export class BookModule { } * 我们导入了 `NgbDatepickerModule` 来使用日期选择器. -打开 `/src/app/book/book.component.ts` 使用以内内容替换: +打开 `/src/app/book/book.component.ts` 使用以下内容替换: ```js import { ListService, PagedResultDto } from '@abp/ng.core'; import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType } from './models'; -import { BookService } from './services'; +import { BookService, BookDto, bookTypeOptions } from '@proxy/books'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; // added this line @@ -923,11 +912,7 @@ export class BookComponent implements OnInit { form: FormGroup; - bookType = BookType; - - bookTypes = Object.keys(this.bookType).filter( - (key) => typeof this.bookType[key] === 'number' - ); + bookTypes = bookTypeOptions; isModalOpen = false; @@ -938,7 +923,7 @@ export class BookComponent implements OnInit { ) {} ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); + const bookStreamCreator = (query) => this.bookService.getList(query); this.list.hookToQuery(bookStreamCreator).subscribe((response) => { this.book = response; @@ -964,7 +949,7 @@ export class BookComponent implements OnInit { return; } - this.bookService.createByInput(this.form.value).subscribe(() => { + this.bookService.create(this.form.value).subscribe(() => { this.isModalOpen = false; this.form.reset(); this.list.get(); @@ -974,11 +959,11 @@ export class BookComponent implements OnInit { ``` * 导入了 `NgbDateNativeAdapter` 和 `NgbDateAdapter`. -* 我们添加了一个新的 `NgbDateAdapter` 提供程序,它将Datepicker值转换为 `Date` 类型. 有关更多详细信息,请参见[datepicker adapters](https://ng-bootstrap.github.io/#/components/datepicker/overview). +* 我们添加了一个新的 `NgbDateAdapter` 提供程序,它将Datepicker值转换为 `Date` 类型. 更多详细信息,请参见[datepicker adapters](https://ng-bootstrap.github.io/#/components/datepicker/overview). 现在你可以打开浏览器看到以下变化: -![Save button to the modal](./images/bookstore-new-book-form-v2.png) +![Save button to the modal](images/bookstore-new-book-form-v2.png) ## 更新书籍 @@ -987,8 +972,7 @@ export class BookComponent implements OnInit { ```js import { ListService, PagedResultDto } from '@abp/ng.core'; import { Component, OnInit } from '@angular/core'; -import { BookDto, BookType, CreateUpdateBookDto } from './models'; -import { BookService } from './services'; +import { BookService, BookDto, bookTypeOptions } from '@proxy/books'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap'; @@ -1001,15 +985,11 @@ import { NgbDateNativeAdapter, NgbDateAdapter } from '@ng-bootstrap/ng-bootstrap export class BookComponent implements OnInit { book = { items: [], totalCount: 0 } as PagedResultDto; - selectedBook = new BookDto(); // declare selectedBook + selectedBook = {} as BookDto; // declare selectedBook form: FormGroup; - bookType = BookType; - - bookTypes = Object.keys(this.bookType).filter( - (key) => typeof this.bookType[key] === 'number' - ); + bookTypes = bookTypeOptions; isModalOpen = false; @@ -1020,7 +1000,7 @@ export class BookComponent implements OnInit { ) {} ngOnInit() { - const bookStreamCreator = (query) => this.bookService.getListByInput(query); + const bookStreamCreator = (query) => this.bookService.getList(query); this.list.hookToQuery(bookStreamCreator).subscribe((response) => { this.book = response; @@ -1028,14 +1008,14 @@ export class BookComponent implements OnInit { } createBook() { - this.selectedBook = new BookDto(); // reset the selected book + this.selectedBook = {} as BookDto; // reset the selected book this.buildForm(); this.isModalOpen = true; } // Add editBook method editBook(id: string) { - this.bookService.getById(id).subscribe((book) => { + this.bookService.get(id).subscribe((book) => { this.selectedBook = book; this.buildForm(); this.isModalOpen = true; @@ -1061,8 +1041,8 @@ export class BookComponent implements OnInit { } const request = this.selectedBook.id - ? this.bookService.updateByIdAndInput(this.form.value, this.selectedBook.id) - : this.bookService.createByInput(this.form.value); + ? this.bookService.update(this.selectedBook.id, this.form.value) + : this.bookService.create(this.form.value); request.subscribe(() => { this.isModalOpen = false; @@ -1074,10 +1054,10 @@ export class BookComponent implements OnInit { ``` * 我们声明了类型为 `BookDto` 的 `selectedBook` 变量. -* 我们添加了 `editBook` 方法, 根据给定图书 `Id` 设置 `selectedBook` 对象. +* 我们添加了 `editBook` 方法, 根据给定书籍 `Id` 设置 `selectedBook` 对象. * 我们替换了 `buildForm` 方法使用 `selectedBook` 数据创建表单. * 我们替换了 `createBook` 方法,设置 `selectedBook` 为空对象. -* 我们替换了 `save` 方法. +* 我们修改了 `save` 方法,同时处理新建和更新操作. ### 添加 "Actions" 下拉框到表格 @@ -1111,7 +1091,7 @@ export class BookComponent implements OnInit { 在表格的第一列添加了一个 "Actions" 下拉菜单,如下图所示: -![Action buttons](./images/bookstore-actions-buttons.png) +![Action buttons](images/bookstore-actions-buttons.png) 同时如下所示更改 `ng-template #abpHeader` 部分: @@ -1147,13 +1127,13 @@ constructor( delete(id: string) { this.confirmation.warn('::AreYouSureToDelete', '::AreYouSure').subscribe((status) => { if (status === Confirmation.Status.confirm) { - this.bookService.deleteById(id).subscribe(() => this.list.get()); + this.bookService.delete(id).subscribe(() => this.list.get()); } }); } ``` -* 我们注入了 `ConfirmationService`. +* 我们引入了 `ConfirmationService`. * 我们注入了 `ConfirmationService` 到构造函数. * 添加了 `delete` 方法. @@ -1161,6 +1141,7 @@ delete(id: string) { ### 添加删除按钮: + 打开 `/src/app/book/book.component.html` 修改 `ngbDropdownMenu` 添加删除按钮: ```html @@ -1174,14 +1155,445 @@ delete(id: string) { 最终操作下拉框UI看起来如下: -![bookstore-final-actions-dropdown](./images/bookstore-final-actions-dropdown.png) +![bookstore-final-actions-dropdown](images/bookstore-final-actions-dropdown.png) + +点击 `delete` 操作调用 `delete` 方法,然后显示一个确认弹层如下图所示. + +![bookstore-confirmation-popup](images/bookstore-confirmation-popup.png) + +{{end}} + +{{if UI == "Blazor" || UI == "BlazorServer"}} + +## 创建新书籍 + +通过本节, 你将会了解如何创建一个模态窗口实现新增书籍的功能. 因为我们已经从 `AbpCrudPageBase` 继承, 所以只需要开发视图部分. + +### 添加 "New Button" 按钮 + +打开 `Books.razor` 替换 `` 部分为以下代码: + +````xml + + + +

@L["Books"]

+
+ + + +
+
+```` + +如下图所示,卡片头 **右侧** 添加了 **New book** 按钮: + +![blazor-add-book-button](images/blazor-add-book-button.png) + +现在, 我们可以添加点击按钮后打开的模态窗口了. + +### 书籍创建模态窗口 + +打开 `Books.razor`, 添加以下代码到页面底部: + +````xml + + + +
+ + @L["NewBook"] + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
+
+
+```` + +这段代码需要一个服务; 在文件顶部, `@inherits...` 行前, 注入 `AbpBlazorMessageLocalizerHelper`: + +````csharp +@inject AbpBlazorMessageLocalizerHelper LH +```` + +* 表单实现了验证功能, `AbpBlazorMessageLocalizerHelper` 用于本地化验证消息. +* `CreateModal` 对象, `CloseCreateModalAsync` 和 `CreateEntityAsync` 方法定义在基类中. 参阅 [Blazorise文档](https://blazorise.com/docs/) 以深入理解 `Modal` 和其它组件. + +这就是全部了. 运行应用程序, 尝试添加一本新书. + +![blazor-new-book-modal](images/blazor-new-book-modal.png) + +## 更新书籍 + +编辑书籍与新建书籍很类似. -点击 `delete` 动作调用 `delete` 方法,然后无法显示一个确认弹层如下图所示. +### 操作下拉菜单 -![bookstore-confirmation-popup](./images/bookstore-confirmation-popup.png) +打开 `Books.razor` , 在 `DataGridColumns` 中添加以下 `DataGridEntityActionsColumn` 作为第一项: + +````xml + + + + + + + +```` + +* `OpenEditModalAsync` 定义在基类中, 它接收实体(书籍)参数, 编辑这个实体. + +`DataGridEntityActionsColumn` 组件用于显示 `DataGrid` 每一行中的"操作" 下拉菜单. 如果其中只有唯一的操作, `DataGridEntityActionsColumn` 显示 **唯一按钮**, 而不是下拉菜单. + +![blazor-edit-book-action](images/blazor-edit-book-action-2.png) + +### 编辑模态窗口 + +我们现在可以定义一个模态窗口编辑书籍. 加入下面的代码到 `Books.razor` 页面的底部: + +````xml + + + +
+ + @EditingEntity.Name + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
+
+
+```` + +### AutoMapper 配置 + +基类 `AbpCrudPageBase` 使用 [对象到对象映射](../Object-To-Object-Mapping.md) 系统将 `BookDto` 对象转化为`CreateUpdateBookDto` 对象. 因此, 我们需要定义映射. + +打开 `Acme.BookStore.Blazor` 项目中的 `BookStoreBlazorAutoMapperProfile `, 替换成以下内容: + +````csharp +using Acme.BookStore.Books; +using AutoMapper; + +namespace Acme.BookStore.Blazor +{ + public class BookStoreBlazorAutoMapperProfile : Profile + { + public BookStoreBlazorAutoMapperProfile() + { + CreateMap(); + } + } +} +```` + +* `CreateMap();` 行用于定义映射. + +### 测试编辑模态窗口 + +你可以运行程序并尝试编辑一本书. + +![blazor-edit-book-modal](images/blazor-edit-book-modal.png) + +> 提示: 尝试保留 *Name* 字段为空并提交表单, 将显示验证错误消息. + +## 删除书籍 + +打开 `Books.razor` 页面, 在 `EntityActions` 中的"编辑" 操作下面加入以下的 `EntityAction`: + +````xml + +```` + +* `DeleteEntityAsync` 定义在基类中. 通过向服务器发起请求删除实体. +* `ConfirmationMessage` 执行操作前显示确认消息的回调函数. +* `GetDeleteConfirmationMessage` 定义在基类中. 你可以覆写这个方法 (或传递其它值给 `ConfirmationMessage` 参数) 以定制本地化消息. + +因为"操作" 按钮现在有了两个操作, 变成了下拉菜单: + +![blazor-edit-book-action](images/blazor-delete-book-action.png) + +运行程序并尝试删除一本书. + +## 完整的 CRUD UI 代码 + +下面是完整的创建图书管理CRUD页面的代码, 这些代码在上面是分成两部分开发的: + +````xml +@page "/books" +@using Volo.Abp.Application.Dtos +@using Acme.BookStore.Books +@using Acme.BookStore.Localization +@using Microsoft.Extensions.Localization +@using Volo.Abp.AspNetCore.Components.Web +@inject IStringLocalizer L +@inject AbpBlazorMessageLocalizerHelper LH +@inherits AbpCrudPageBase + + + + + +

@L["Books"]

+
+ + + +
+
+ + + + + + + + + + + + + + + @L[$"Enum:BookType:{(int) context.Type}"] + + + + + @context.PublishDate.ToShortDateString() + + + + + + + @context.CreationTime.ToLongDateString() + + + + + +
+ + + + +
+ + @L["NewBook"] + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
+
+
+ + + + +
+ + @EditingEntity.Name + + + + + + + @L["Name"] + + + + + + + + + @L["Type"] + + + + @L["PublishDate"] + + + + @L["Price"] + + + + + + + + +
+
+
+```` {{end}} ## 下一章 -查看本教程的[下一章](Part-4.md). +查看本教程的[下一章](Part-4.md). \ No newline at end of file diff --git a/docs/zh-Hans/Tutorials/Part-4.md b/docs/zh-Hans/Tutorials/Part-4.md index 151c7aab90..e570880a22 100644 --- a/docs/zh-Hans/Tutorials/Part-4.md +++ b/docs/zh-Hans/Tutorials/Part-4.md @@ -2,27 +2,10 @@ ````json //[doc-params] { - "UI": ["MVC","NG"], + "UI": ["MVC","Blazor","BlazorServer","NG"], "DB": ["EF","Mongo"] } ```` -{{ -if UI == "MVC" - UI_Text="mvc" -else if UI == "NG" - UI_Text="angular" -else - UI_Text="?" -end -if DB == "EF" - DB_Text="Entity Framework Core" -else if DB == "Mongo" - DB_Text="MongoDB" -else - DB_Text="?" -end -}} - ## 关于本教程 在本系列教程中, 你将构建一个名为 `Acme.BookStore` 的用于管理书籍及其作者列表的基于ABP的应用程序. 它是使用以下技术开发的: @@ -45,16 +28,32 @@ end ## 下载源码 -本教程根据你的**UI** 和 **Database**偏好有多个版,我们准备了两种可供下载的源码组合: +本教程根据你的**UI** 和 **数据库**偏好有多个版本,我们准备了几种可供下载的源码组合: * [MVC (Razor Pages) UI 与 EF Core](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore) +* [Blazor UI 与 EF Core](https://github.com/abpframework/abp-samples/tree/master/BookStore-Blazor-EfCore) * [Angular UI 与 MongoDB](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb) +> 如果你在Windows中遇到 "文件名太长" or "解压错误", 很可能与Windows最大文件路径限制有关. Windows文件路径的最大长度为250字符. 为了解决这个问题,参阅 [在Windows 10中启用长路径](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later). + +> 如果你遇到与Git相关的长路径错误, 尝试使用下面的命令在Windows中启用长路径. 参阅 https://github.com/msysgit/msysgit/wiki/Git-cannot-create-a-file-or-directory-with-a-long-path +> `git config --system core.longpaths true` + +{{if UI == "MVC" && DB == "EF"}} + +### 视频教程 + +本章也被录制为视频教程 **发布在YouTube**. + +{{end}} + ## 解决方案中的测试项目 这一部分涵盖了 **服务器端** 测试. 解决方案中有多个测试项目: -![bookstore-test-projects-v2](./images/bookstore-test-projects-{{UI_Text}}.png) +![bookstore-test-projects-v2](./images/bookstore-test-projects-mvc.png) + +> 根据你选择的UI和数据库, 测试项目略微有所不同. 例如, 如果选择MongoDB, 那么 `Acme.BookStore.EntityFrameworkCore.Tests` 会变为 `Acme.BookStore.MongoDB.Tests`. 每个项目用于测试相关的应用程序项目.测试项目使用以下库进行测试: @@ -64,11 +63,11 @@ end {{if DB=="EF"}} -> 测试项目配置为使用 **SQLite内存** 作为数据库. 创建一个单独的数据库实例并使用数据种子系统进行初始化种子数据,为每个测试准备一个新的数据库. +> 测试项目配置为使用 **SQLite内存** 作为数据库. 创建一个单独的数据库实例并使用[数据种子系统](../Data-Seeding.md)初始化种子数据,为每个测试准备一个新的数据库. {{else if DB=="Mongo"}} -> **[Mongo2Go](https://github.com/Mongo2Go/Mongo2Go)**库用于模拟MongoDB数据库. 创建一个单独的数据库实例并使用数据种子系统进行初始化种子数据,为每个测试准备一个新的数据库. +> **[Mongo2Go](https://github.com/Mongo2Go/Mongo2Go)**库用于模拟MongoDB数据库. 创建一个单独的数据库实例并使用[数据种子系统](../Data-Seeding.md)初始化种子数据,为每个测试准备一个新的数据库. {{end}} @@ -78,12 +77,15 @@ end ## 测试 BookAppService -在 `Acme.BookStore.Application.Tests` 项目中创建一个名叫 `BookAppService_Tests` 的测试类: +在 `Acme.BookStore.Application.Tests` 项目的 `Books` 命名空间(文件夹)中创建一个名叫 `BookAppService_Tests` 的测试类: ````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 @@ -129,7 +131,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 } ); @@ -201,7 +203,7 @@ namespace Acme.BookStore.Books result.TotalCount.ShouldBeGreaterThan(0); result.Items.ShouldContain(b => b.Name == "1984"); } - + [Fact] public async Task Should_Create_A_Valid_Book() { @@ -211,7 +213,7 @@ namespace Acme.BookStore.Books { Name = "New test book 42", Price = 10, - PublishDate = System.DateTime.Now, + PublishDate = DateTime.Now, Type = BookType.ScienceFiction } ); @@ -220,7 +222,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() { @@ -244,7 +246,7 @@ namespace Acme.BookStore.Books } ```` -打开**测试资源管理器**(测试 -> Windows -> 测试资源管理器)并**执行**所有测试: +打开**测试资源管理器**(测试 -> Windows -> 测试资源管理器)并**执行所有**测试: ![bookstore-appservice-tests](./images/bookstore-appservice-tests.png) @@ -252,4 +254,4 @@ namespace Acme.BookStore.Books ## 下一章 -查看本教程的[下一章](Part-5.md). \ No newline at end of file +查看本教程的[下一章](Part-5.md). diff --git a/docs/zh-Hans/Tutorials/Todo/Index.md b/docs/zh-Hans/Tutorials/Todo/Index.md index d940957c18..2200bf23e6 100644 --- a/docs/zh-Hans/Tutorials/Todo/Index.md +++ b/docs/zh-Hans/Tutorials/Todo/Index.md @@ -682,7 +682,7 @@ ABP提供了一个便捷的功能来自动创建客户端服务, 以方便地使 当启动 `TodoApp.HttpApi.Host` 项目后, 在`angular`文件夹中打开一个命令行终端并输入以下命令: ````bash -abp generate-proxy +abp generate-proxy -t ng ```` 如果一切顺利, 它应该生成如下输出: diff --git a/docs/zh-Hans/Tutorials/images/blazor-add-book-button.png b/docs/zh-Hans/Tutorials/images/blazor-add-book-button.png new file mode 100644 index 0000000000..58a607d3b1 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-add-book-button.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-add-books-component.png b/docs/zh-Hans/Tutorials/images/blazor-add-books-component.png new file mode 100644 index 0000000000..ec0412d31e Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-add-books-component.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-bookstore-book-list.png b/docs/zh-Hans/Tutorials/images/blazor-bookstore-book-list.png new file mode 100644 index 0000000000..18bb26ccb1 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-bookstore-book-list.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-delete-book-action.png b/docs/zh-Hans/Tutorials/images/blazor-delete-book-action.png new file mode 100644 index 0000000000..f2b0b83f30 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-delete-book-action.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-edit-book-action-2.png b/docs/zh-Hans/Tutorials/images/blazor-edit-book-action-2.png new file mode 100644 index 0000000000..c3e2b1e0e1 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-edit-book-action-2.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-edit-book-modal.png b/docs/zh-Hans/Tutorials/images/blazor-edit-book-modal.png new file mode 100644 index 0000000000..e63e796d34 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-edit-book-modal.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-menu-bookstore.png b/docs/zh-Hans/Tutorials/images/blazor-menu-bookstore.png new file mode 100644 index 0000000000..f9f334aa1d Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-menu-bookstore.png differ diff --git a/docs/zh-Hans/Tutorials/images/blazor-new-book-modal.png b/docs/zh-Hans/Tutorials/images/blazor-new-book-modal.png new file mode 100644 index 0000000000..dd284a0ffd Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/blazor-new-book-modal.png differ diff --git a/docs/zh-Hans/Tutorials/images/generated-proxies-3.png b/docs/zh-Hans/Tutorials/images/generated-proxies-3.png new file mode 100644 index 0000000000..2a94f4e389 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/generated-proxies-3.png differ diff --git a/docs/zh-Hans/Tutorials/images/vs-run-without-iisexpress.png b/docs/zh-Hans/Tutorials/images/vs-run-without-iisexpress.png new file mode 100644 index 0000000000..03c30e2b48 Binary files /dev/null and b/docs/zh-Hans/Tutorials/images/vs-run-without-iisexpress.png differ diff --git a/docs/zh-Hans/UI/Angular/Service-Proxies.md b/docs/zh-Hans/UI/Angular/Service-Proxies.md index 2824bc44a7..cc07a24175 100644 --- a/docs/zh-Hans/UI/Angular/Service-Proxies.md +++ b/docs/zh-Hans/UI/Angular/Service-Proxies.md @@ -15,7 +15,7 @@ ABP CLI 的`generate-proxies` 命令在 `src/app` 文件夹中创建按模块名 在angular应用程序的**根文件夹**中运行以下命令: ```bash -abp generate-proxy +abp generate-proxy -t ng ``` 它只为你自己的应用程序的服务创建代理. 不会为你正在使用的应用程序模块的服务创建代理(默认情况下). 有几个选项,参见[CLI文档](../../CLI). diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs index cb104533cb..b92bb96f70 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Microsoft/AspNetCore/Components/WebAssembly/Hosting/AbpWebAssemblyHostBuilderExtensions.cs @@ -17,6 +17,30 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting; public static class AbpWebAssemblyHostBuilderExtensions { + public async static Task AddApplicationAsync( + [NotNull] this WebAssemblyHostBuilder builder, + Action options) + where TStartupModule : IAbpModule + { + Check.NotNull(builder, nameof(builder)); + + // Related this commit(https://github.com/dotnet/aspnetcore/commit/b99d805bc037fcac56afb79abeb7d5a43141c85e) + // Microsoft.AspNetCore.Blazor.BuildTools has been removed in net 5.0. + // This call may be removed when we find a suitable solution. + // System.Runtime.CompilerServices.AsyncStateMachineAttribute + Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(); + + builder.Services.AddSingleton(builder.Configuration); + builder.Services.AddSingleton(builder); + + var application = await builder.Services.AddApplicationAsync(opts => + { + options?.Invoke(new AbpWebAssemblyApplicationCreationOptions(builder, opts)); + }); + + return application; + } + public static IAbpApplicationWithExternalServiceProvider AddApplication( [NotNull] this WebAssemblyHostBuilder builder, Action options) @@ -41,7 +65,7 @@ public static class AbpWebAssemblyHostBuilderExtensions return application; } - public static async Task InitializeAsync( + public async static Task InitializeAsync( [NotNull] this IAbpApplicationWithExternalServiceProvider application, [NotNull] IServiceProvider serviceProvider) { @@ -51,12 +75,12 @@ public static class AbpWebAssemblyHostBuilderExtensions ((ComponentsClientScopeServiceProviderAccessor)serviceProvider .GetRequiredService()).ServiceProvider = serviceProvider; - application.Initialize(serviceProvider); + await application.InitializeAsync(serviceProvider); await InitializeModulesAsync(serviceProvider); await SetCurrentLanguageAsync(serviceProvider); } - private static async Task InitializeModulesAsync(IServiceProvider serviceProvider) + private async static Task InitializeModulesAsync(IServiceProvider serviceProvider) { foreach (var service in serviceProvider.GetServices()) { @@ -64,7 +88,7 @@ public static class AbpWebAssemblyHostBuilderExtensions } } - private static async Task SetCurrentLanguageAsync(IServiceProvider serviceProvider) + private async static Task SetCurrentLanguageAsync(IServiceProvider serviceProvider) { var configurationClient = serviceProvider.GetRequiredService(); var utilsService = serviceProvider.GetRequiredService(); diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs new file mode 100644 index 0000000000..3f5e9ad4b8 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreAsyncIntegratedTestBase.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Volo.Abp.Modularity; + +namespace Volo.Abp.AspNetCore.TestBase; + +public class AbpAspNetCoreAsyncIntegratedTestBase + where TModule : IAbpModule +{ + protected WebApplication WebApplication { get; set; } + + protected TestServer Server { get; set; } + + protected HttpClient Client { get; set; } + + protected IServiceProvider ServiceProvider { get; set; } + + protected virtual T GetService() + { + return ServiceProvider.GetService(); + } + + protected virtual T GetRequiredService() + { + return ServiceProvider.GetRequiredService(); + } + + public virtual async Task InitializeAsync() + { + var builder = WebApplication.CreateBuilder(); + builder.Host.ConfigureServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + }) + .UseAutofac(); + + await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + }); + + await ConfigureServicesAsync(builder.Services); + WebApplication = builder.Build(); + await WebApplication.InitializeApplicationAsync(); + await WebApplication.StartAsync(); + + Server = WebApplication.Services.GetRequiredService().GetTestServer(); + Client = Server.CreateClient(); + + ServiceProvider = Server.Services; + ServiceProvider.GetRequiredService().Server = Server; + } + + public virtual async Task DisposeAsync() + { + await WebApplication.DisposeAsync(); + } + + protected virtual Task ConfigureServicesAsync(IServiceCollection services) + { + return Task.CompletedTask; + } + + #region GetUrl + + /// + /// Gets default URL for given controller type. + /// + /// The type of the controller. + protected virtual string GetUrl() + { + return "/" + typeof(TController).Name.RemovePostFix("Controller", "AppService", "ApplicationService", "Service"); + } + + /// + /// Gets default URL for given controller type's given action. + /// + /// The type of the controller. + protected virtual string GetUrl(string actionName) + { + return GetUrl() + "/" + actionName; + } + + /// + /// Gets default URL for given controller type's given action with query string parameters (as anonymous object). + /// + /// The type of the controller. + protected virtual string GetUrl(string actionName, object queryStringParamsAsAnonymousObject) + { + var url = GetUrl(actionName); + + var dictionary = new RouteValueDictionary(queryStringParamsAsAnonymousObject); + if (dictionary.Any()) + { + url += "?" + dictionary.Select(d => $"{d.Key}={d.Value}").JoinAsString("&"); + } + + return url; + } + + #endregion +} diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs index 1fa62b2417..f3e60979bb 100644 --- a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/AbpAspNetCoreIntegratedTestBase.cs @@ -17,8 +17,6 @@ public abstract class AbpAspNetCoreIntegratedTestBase : AbpTestBaseWit protected HttpClient Client { get; } - protected override IServiceProvider ServiceProvider { get; } - private readonly IHost _host; protected AbpAspNetCoreIntegratedTestBase() diff --git a/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs new file mode 100644 index 0000000000..a0fe2d46c1 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.TestBase/Volo/Abp/AspNetCore/TestBase/TestNoopHostLifetime.cs @@ -0,0 +1,18 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; + +namespace Volo.Abp.AspNetCore.TestBase; + +public class TestNoopHostLifetime : IHostLifetime +{ + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public Task WaitForStartAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } +} diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs index 2e8b221b3c..8ef3ec8d99 100644 --- a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.AspNetCore.RequestLocalization; using Microsoft.Extensions.DependencyInjection; @@ -11,6 +12,7 @@ using Volo.Abp.AspNetCore.Security.Claims; using Volo.Abp.AspNetCore.Tracing; using Volo.Abp.AspNetCore.Uow; using Volo.Abp.DependencyInjection; +using Volo.Abp.Threading; namespace Microsoft.AspNetCore.Builder; @@ -18,6 +20,27 @@ public static class AbpApplicationBuilderExtensions { private const string ExceptionHandlingMiddlewareMarker = "_AbpExceptionHandlingMiddleware_Added"; + public async static Task InitializeApplicationAsync([NotNull] this IApplicationBuilder app) + { + Check.NotNull(app, nameof(app)); + + app.ApplicationServices.GetRequiredService>().Value = app; + var application = app.ApplicationServices.GetRequiredService(); + var applicationLifetime = app.ApplicationServices.GetRequiredService(); + + applicationLifetime.ApplicationStopping.Register(() => + { + AsyncHelper.RunSync(() => application.ShutdownAsync()); + }); + + applicationLifetime.ApplicationStopped.Register(() => + { + application.Dispose(); + }); + + await application.InitializeAsync(app.ApplicationServices); + } + public static void InitializeApplication([NotNull] this IApplicationBuilder app) { Check.NotNull(app, nameof(app)); diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/AbpAspNetCoreServiceCollectionExtensions.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/AbpAspNetCoreServiceCollectionExtensions.cs index cc88cac891..bda87a4e32 100644 --- a/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/AbpAspNetCoreServiceCollectionExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/AbpAspNetCoreServiceCollectionExtensions.cs @@ -1,4 +1,6 @@ -using Microsoft.AspNetCore.Hosting; +using System.Linq; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace Microsoft.Extensions.DependencyInjection; @@ -6,6 +8,16 @@ public static class AbpAspNetCoreServiceCollectionExtensions { public static IWebHostEnvironment GetHostingEnvironment(this IServiceCollection services) { - return services.GetSingletonInstance(); + var hostingEnvironment = services.GetSingletonInstanceOrNull(); + + if (hostingEnvironment == null) + { + return new EmptyHostingEnvironment() + { + EnvironmentName = Environments.Development + }; + } + + return hostingEnvironment; } } diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/EmptyHostingEnvironment.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/EmptyHostingEnvironment.cs new file mode 100644 index 0000000000..371162f0da --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/EmptyHostingEnvironment.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.FileProviders; + +namespace Microsoft.Extensions.DependencyInjection; + +internal class EmptyHostingEnvironment : IWebHostEnvironment +{ + public string EnvironmentName { get; set; } + + public string ApplicationName { get; set; } + + public string WebRootPath { get; set; } + + public IFileProvider WebRootFileProvider { get; set; } + + public string ContentRootPath { get; set; } + + public IFileProvider ContentRootFileProvider { get; set; } +} \ No newline at end of file diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/WebApplicationBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/WebApplicationBuilderExtensions.cs new file mode 100644 index 0000000000..692825520b --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/Extensions/DependencyInjection/WebApplicationBuilderExtensions.cs @@ -0,0 +1,35 @@ +using System; +using System.Threading.Tasks; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Builder; +using Volo.Abp; +using Volo.Abp.Modularity; + +namespace Microsoft.Extensions.DependencyInjection; + +public static class WebApplicationBuilderExtensions +{ + public async static Task AddApplicationAsync( + [NotNull] this WebApplicationBuilder builder, + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + return await builder.Services.AddApplicationAsync(options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + optionsAction?.Invoke(options); + }); + } + + public async static Task AddApplicationAsync( + [NotNull] this WebApplicationBuilder builder, + [NotNull] Type startupModuleType, + [CanBeNull] Action optionsAction = null) + { + return await builder.Services.AddApplicationAsync(startupModuleType, options => + { + options.Services.ReplaceConfiguration(builder.Configuration); + optionsAction?.Invoke(options); + }); + } +} diff --git a/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs b/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs index 33cbc740e4..c601ca5549 100644 --- a/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs +++ b/framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/AbpBackgroundJobsRabbitMqModule.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; using Volo.Abp.RabbitMQ; using Volo.Abp.Threading; @@ -17,31 +18,37 @@ public class AbpBackgroundJobsRabbitMqModule : AbpModule context.Services.AddSingleton(typeof(IJobQueue<>), typeof(JobQueue<>)); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + await StartJobQueueManagerAsync(context); + } + + public async override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + await StopJobQueueManagerAsync(context); + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { - StartJobQueueManager(context); + AsyncHelper.RunSync(() => StartJobQueueManagerAsync(context)); } public override void OnApplicationShutdown(ApplicationShutdownContext context) { - StopJobQueueManager(context); + AsyncHelper.RunSync(() => StopJobQueueManagerAsync(context)); } - private static void StartJobQueueManager(ApplicationInitializationContext context) + private async static Task StartJobQueueManagerAsync(ApplicationInitializationContext context) { - AsyncHelper.RunSync( - () => context.ServiceProvider - .GetRequiredService() - .StartAsync() - ); + await context.ServiceProvider + .GetRequiredService() + .StartAsync(); } - private static void StopJobQueueManager(ApplicationShutdownContext context) + private async static Task StopJobQueueManagerAsync(ApplicationShutdownContext context) { - AsyncHelper.RunSync( - () => context.ServiceProvider - .GetRequiredService() - .StopAsync() - ); + await context.ServiceProvider + .GetRequiredService() + .StopAsync(); } } diff --git a/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs b/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs index aaa4a7ba01..47a165ca83 100644 --- a/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs +++ b/framework/src/Volo.Abp.BackgroundJobs/Volo/Abp/BackgroundJobs/AbpBackgroundJobsModule.cs @@ -1,9 +1,11 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp.BackgroundWorkers; using Volo.Abp.DistributedLocking; using Volo.Abp.Guids; using Volo.Abp.Modularity; +using Volo.Abp.Threading; using Volo.Abp.Timing; namespace Volo.Abp.BackgroundJobs; @@ -17,12 +19,21 @@ namespace Volo.Abp.BackgroundJobs; )] public class AbpBackgroundJobsModule : AbpModule { + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsJobExecutionEnabled) + { + await context.AddBackgroundWorkerAsync(); + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; if (options.IsJobExecutionEnabled) { - context.AddBackgroundWorker(); + AsyncHelper.RunSync(() => context.AddBackgroundWorkerAsync()); } } } diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs index 162b2fa472..ab1cd461e7 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Hangfire/Volo/Abp/BackgroundWorkers/Hangfire/HangfireBackgroundWorkerManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -21,7 +21,7 @@ public class HangfireBackgroundWorkerManager : IBackgroundWorkerManager, ISingle return Task.CompletedTask; } - public void Add(IBackgroundWorker worker) + public async Task AddAsync(IBackgroundWorker worker) { if (worker is IHangfireBackgroundWorker hangfireBackgroundWorker) { @@ -32,7 +32,7 @@ public class HangfireBackgroundWorkerManager : IBackgroundWorkerManager, ISingle } else { - RecurringJob.AddOrUpdate(hangfireBackgroundWorker.RecurringJobId, () => hangfireBackgroundWorker.DoWorkAsync(), + RecurringJob.AddOrUpdate(hangfireBackgroundWorker.RecurringJobId,() => hangfireBackgroundWorker.DoWorkAsync(), hangfireBackgroundWorker.CronExpression); } } @@ -42,7 +42,7 @@ public class HangfireBackgroundWorkerManager : IBackgroundWorkerManager, ISingle if (worker is AsyncPeriodicBackgroundWorkerBase or PeriodicBackgroundWorkerBase) { - var timer = (AbpTimer)worker.GetType() + var timer = (AbpAsyncTimer) worker.GetType() .GetProperty("Timer", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(worker); period = timer?.Period; } diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs index 5884532f1e..07586b461b 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/AbpBackgroundWorkersQuartzModule.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Volo.Abp.Modularity; using Volo.Abp.Quartz; +using Volo.Abp.Threading; namespace Volo.Abp.BackgroundWorkers.Quartz; @@ -34,6 +35,21 @@ public class AbpBackgroundWorkersQuartzModule : AbpModule } } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var quartzBackgroundWorkerOptions = context.ServiceProvider.GetRequiredService>().Value; + if (quartzBackgroundWorkerOptions.IsAutoRegisterEnabled) + { + var backgroundWorkerManager = context.ServiceProvider.GetRequiredService(); + var works = context.ServiceProvider.GetServices().Where(x => x.AutoRegister); + + foreach (var work in works) + { + await backgroundWorkerManager.AddAsync(work); + } + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var quartzBackgroundWorkerOptions = context.ServiceProvider.GetRequiredService>().Value; @@ -44,7 +60,7 @@ public class AbpBackgroundWorkersQuartzModule : AbpModule foreach (var work in works) { - backgroundWorkerManager.Add(work); + AsyncHelper.RunSync(() => backgroundWorkerManager.AddAsync(work)); } } } diff --git a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs index efee2d2139..954f21bcda 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers.Quartz/Volo/Abp/BackgroundWorkers/Quartz/QuartzBackgroundWorkerManager.cs @@ -33,9 +33,9 @@ public class QuartzBackgroundWorkerManager : IBackgroundWorkerManager, ISingleto } } - public virtual void Add(IBackgroundWorker worker) + public virtual async Task AddAsync(IBackgroundWorker worker) { - AsyncHelper.RunSync(() => ReScheduleJobAsync(worker)); + await ReScheduleJobAsync(worker); } protected virtual async Task ReScheduleJobAsync(IBackgroundWorker worker) diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs index 40c4a70fb1..32341f101e 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AbpBackgroundWorkersModule.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp.Modularity; using Volo.Abp.Threading; @@ -10,6 +11,28 @@ namespace Volo.Abp.BackgroundWorkers; )] public class AbpBackgroundWorkersModule : AbpModule { + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsEnabled) + { + await context.ServiceProvider + .GetRequiredService() + .StartAsync(); + } + } + + public async override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsEnabled) + { + await context.ServiceProvider + .GetRequiredService() + .StopAsync(); + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs index 62c1f3607b..3276c837c0 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerManager.cs @@ -26,15 +26,13 @@ public class BackgroundWorkerManager : IBackgroundWorkerManager, ISingletonDepen _backgroundWorkers = new List(); } - public virtual void Add(IBackgroundWorker worker) + public virtual async Task AddAsync(IBackgroundWorker worker) { _backgroundWorkers.Add(worker); if (IsRunning) { - AsyncHelper.RunSync( - () => worker.StartAsync() - ); + await worker.StartAsync(); } } diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs index 5cff67b7de..9df0f6c5e4 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; @@ -6,17 +7,17 @@ namespace Volo.Abp.BackgroundWorkers; public static class BackgroundWorkersApplicationInitializationContextExtensions { - public static ApplicationInitializationContext AddBackgroundWorker([NotNull] this ApplicationInitializationContext context) + public async static Task AddBackgroundWorkerAsync([NotNull] this ApplicationInitializationContext context) where TWorker : IBackgroundWorker { Check.NotNull(context, nameof(context)); - context.AddBackgroundWorker(typeof(TWorker)); + await context.AddBackgroundWorkerAsync(typeof(TWorker)); return context; } - public static ApplicationInitializationContext AddBackgroundWorker([NotNull] this ApplicationInitializationContext context, [NotNull] Type workerType) + public async static Task AddBackgroundWorkerAsync([NotNull] this ApplicationInitializationContext context, [NotNull] Type workerType) { Check.NotNull(context, nameof(context)); Check.NotNull(workerType, nameof(workerType)); @@ -26,9 +27,9 @@ public static class BackgroundWorkersApplicationInitializationContextExtensions throw new AbpException($"Given type ({workerType.AssemblyQualifiedName}) must implement the {typeof(IBackgroundWorker).AssemblyQualifiedName} interface, but it doesn't!"); } - context.ServiceProvider + await context.ServiceProvider .GetRequiredService() - .Add( + .AddAsync( (IBackgroundWorker)context.ServiceProvider.GetRequiredService(workerType) ); diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs index e1bf0e53f2..7f5268afff 100644 --- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs +++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/IBackgroundWorkerManager.cs @@ -1,4 +1,5 @@ -using Volo.Abp.Threading; +using System.Threading.Tasks; +using Volo.Abp.Threading; namespace Volo.Abp.BackgroundWorkers; @@ -13,5 +14,5 @@ public interface IBackgroundWorkerManager : IRunnable /// /// The worker. It should be resolved from IOC. /// - void Add(IBackgroundWorker worker); + Task AddAsync(IBackgroundWorker worker); } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs index 303acd7e00..3e4649b6e3 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs @@ -41,29 +41,29 @@ public class AbpCliCoreModule : AbpModule Configure(options => { - //TODO: Define constants like done for GenerateProxyCommand.Name. - options.Commands["help"] = typeof(HelpCommand); - options.Commands["prompt"] = typeof(PromptCommand); - options.Commands["new"] = typeof(NewCommand); - options.Commands["get-source"] = typeof(GetSourceCommand); - options.Commands["update"] = typeof(UpdateCommand); - options.Commands["add-package"] = typeof(AddPackageCommand); - options.Commands["add-module"] = typeof(AddModuleCommand); - options.Commands["list-modules"] = typeof(ListModulesCommand); - options.Commands["login"] = typeof(LoginCommand); - options.Commands["login-info"] = typeof(LoginInfoCommand); - options.Commands["logout"] = typeof(LogoutCommand); + options.Commands[HelpCommand.Name] = typeof(HelpCommand); + options.Commands[PromptCommand.Name] = typeof(PromptCommand); + options.Commands[NewCommand.Name] = typeof(NewCommand); + options.Commands[GetSourceCommand.Name] = typeof(GetSourceCommand); + options.Commands[UpdateCommand.Name] = typeof(UpdateCommand); + options.Commands[AddPackageCommand.Name] = typeof(AddPackageCommand); + options.Commands[AddModuleCommand.Name] = typeof(AddModuleCommand); + options.Commands[ListModulesCommand.Name] = typeof(ListModulesCommand); + options.Commands[LoginCommand.Name] = typeof(LoginCommand); + options.Commands[LoginInfoCommand.Name] = typeof(LoginInfoCommand); + options.Commands[LogoutCommand.Name] = typeof(LogoutCommand); options.Commands[GenerateProxyCommand.Name] = typeof(GenerateProxyCommand); options.Commands[RemoveProxyCommand.Name] = typeof(RemoveProxyCommand); - options.Commands["suite"] = typeof(SuiteCommand); - options.Commands["switch-to-preview"] = typeof(SwitchToPreviewCommand); - options.Commands["switch-to-stable"] = typeof(SwitchToStableCommand); - options.Commands["switch-to-nightly"] = typeof(SwitchToNightlyCommand); - options.Commands["translate"] = typeof(TranslateCommand); - options.Commands["build"] = typeof(BuildCommand); - options.Commands["bundle"] = typeof(BundleCommand); - options.Commands["create-migration-and-run-migrator"] = typeof(CreateMigrationAndRunMigratorCommand); - options.Commands["install-libs"] = typeof(InstallLibsCommand); + options.Commands[SuiteCommand.Name] = typeof(SuiteCommand); + options.Commands[SwitchToPreviewCommand.Name] = typeof(SwitchToPreviewCommand); + options.Commands[SwitchToStableCommand.Name] = typeof(SwitchToStableCommand); + options.Commands[SwitchToNightlyCommand.Name] = typeof(SwitchToNightlyCommand); + options.Commands[TranslateCommand.Name] = typeof(TranslateCommand); + options.Commands[BuildCommand.Name] = typeof(BuildCommand); + options.Commands[BundleCommand.Name] = typeof(BundleCommand); + options.Commands[CreateMigrationAndRunMigratorCommand.Name] = typeof(CreateMigrationAndRunMigratorCommand); + options.Commands[InstallLibsCommand.Name] = typeof(InstallLibsCommand); + options.Commands[CleanCommand.Name] = typeof(CleanCommand); }); Configure(options => diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddModuleCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddModuleCommand.cs index df38d7c57b..df81fe4cb7 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddModuleCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddModuleCommand.cs @@ -14,6 +14,8 @@ namespace Volo.Abp.Cli.Commands; public class AddModuleCommand : IConsoleCommand, ITransientDependency { + public const string Name = "add-module"; + private AddModuleInfoOutput _lastAddedModuleInfo; public ILogger Logger { get; set; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddPackageCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddPackageCommand.cs index 41d9824c6b..d21730dbb8 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddPackageCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/AddPackageCommand.cs @@ -14,6 +14,8 @@ namespace Volo.Abp.Cli.Commands; public class AddPackageCommand : IConsoleCommand, ITransientDependency { + public const string Name = "add-package"; + public ILogger Logger { get; set; } protected ProjectNugetPackageAdder ProjectNugetPackageAdder { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BuildCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BuildCommand.cs index 52c7fdd56c..327b737e89 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BuildCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BuildCommand.cs @@ -12,6 +12,8 @@ namespace Volo.Abp.Cli.Commands; public class BuildCommand : IConsoleCommand, ITransientDependency { + public const string Name = "build"; + public IDotNetProjectDependencyFiller DotNetProjectDependencyFiller { get; set; } public IChangedProjectFinder ChangedProjectFinder { get; set; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BundleCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BundleCommand.cs index 5367e7461a..e758d22dd3 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BundleCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/BundleCommand.cs @@ -11,6 +11,8 @@ namespace Volo.Abp.Cli.Commands; public class BundleCommand : IConsoleCommand, ITransientDependency { + public const string Name = "bundle"; + public ILogger Logger { get; set; } public IBundlingService BundlingService { get; set; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CleanCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CleanCommand.cs new file mode 100644 index 0000000000..9cc89c6017 --- /dev/null +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CleanCommand.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Volo.Abp.Cli.Args; +using Volo.Abp.DependencyInjection; + +namespace Volo.Abp.Cli.Commands; + +public class CleanCommand : IConsoleCommand, ITransientDependency +{ + public const string Name = "clean"; + + public ILogger Logger { get; set; } + + public CleanCommand() + { + Logger = NullLogger.Instance; + } + + public Task ExecuteAsync(CommandLineArgs commandLineArgs) + { + var binEntries = Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "bin", SearchOption.AllDirectories); + var objEntries = Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "obj", SearchOption.AllDirectories); + + foreach (var path in binEntries.Concat(objEntries)) + { + if (path.IndexOf("node_modules", StringComparison.OrdinalIgnoreCase) > 0) + { + Logger.LogInformation($"Skipping: {path}"); + } + else + { + Logger.LogInformation($"Deleting: {path}"); + Directory.Delete(path, true); + } + } + + Logger.LogInformation($"BIN and OBJ folders have been successfully deleted!"); + + return Task.CompletedTask; + } + + public string GetUsageInfo() + { + var sb = new StringBuilder(); + + sb.AppendLine(""); + sb.AppendLine("Usage:"); + sb.AppendLine(" abp clean"); + sb.AppendLine(""); + sb.AppendLine("See the documentation for more info: https://docs.abp.io/en/abp/latest/CLI"); + + return sb.ToString(); + } + + public string GetShortDescription() + { + return "Delete all BIN and OBJ folders in current folder."; + } +} diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CreateMigrationAndRunMigratorCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CreateMigrationAndRunMigratorCommand.cs index a0ffbeacea..3b6fbefe98 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CreateMigrationAndRunMigratorCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CreateMigrationAndRunMigratorCommand.cs @@ -12,6 +12,8 @@ namespace Volo.Abp.Cli.Commands; public class CreateMigrationAndRunMigratorCommand : IConsoleCommand, ITransientDependency { + public const string Name = "create-migration-and-run-migrator"; + public ICmdHelper CmdHelper { get; } public ILogger Logger { get; set; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GetSourceCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GetSourceCommand.cs index 164fc52193..1cccf87f7b 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GetSourceCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GetSourceCommand.cs @@ -13,6 +13,8 @@ namespace Volo.Abp.Cli.Commands; public class GetSourceCommand : IConsoleCommand, ITransientDependency { + public const string Name = "get-source"; + private readonly SourceCodeDownloadService _sourceCodeDownloadService; public ModuleProjectBuilder ModuleProjectBuilder { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/HelpCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/HelpCommand.cs index 317b1f34ea..918136c8d1 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/HelpCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/HelpCommand.cs @@ -12,6 +12,8 @@ namespace Volo.Abp.Cli.Commands; public class HelpCommand : IConsoleCommand, ITransientDependency { + public const string Name = "help"; + public ILogger Logger { get; set; } protected AbpCliOptions AbpCliOptions { get; } protected IServiceScopeFactory ServiceScopeFactory { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/InstallLibsCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/InstallLibsCommand.cs index df95204f51..0cf2fd525b 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/InstallLibsCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/InstallLibsCommand.cs @@ -12,6 +12,8 @@ namespace Volo.Abp.Cli.Commands; public class InstallLibsCommand : IConsoleCommand, ITransientDependency { + public const string Name = "install-libs"; + public ILogger Logger { get; set; } protected IInstallLibsService InstallLibsService { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/ListModulesCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/ListModulesCommand.cs index 1c59a37c46..a916598aac 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/ListModulesCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/ListModulesCommand.cs @@ -12,6 +12,8 @@ namespace Volo.Abp.Cli.Commands; public class ListModulesCommand : IConsoleCommand, ITransientDependency { + public const string Name = "list-modules"; + public ModuleInfoProvider ModuleInfoProvider { get; } public ILogger Logger { get; set; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs index 9cd84a4d41..d98beb268d 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs @@ -18,6 +18,8 @@ namespace Volo.Abp.Cli.Commands; public class LoginCommand : IConsoleCommand, ITransientDependency { + public const string Name = "login"; + public ILogger Logger { get; set; } protected AuthService AuthService { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginInfoCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginInfoCommand.cs index 19ce3853cd..0c456f0bca 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginInfoCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginInfoCommand.cs @@ -11,6 +11,8 @@ namespace Volo.Abp.Cli.Commands; public class LoginInfoCommand : IConsoleCommand, ITransientDependency { + public const string Name = "login-info"; + public ILogger Logger { get; set; } protected AuthService AuthService { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LogoutCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LogoutCommand.cs index 6cefaad8e4..ed571dd7b4 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LogoutCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LogoutCommand.cs @@ -9,6 +9,8 @@ namespace Volo.Abp.Cli.Commands; public class LogoutCommand : IConsoleCommand, ITransientDependency { + public const string Name = "logout"; + public ILogger Logger { get; set; } protected AuthService AuthService { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs index 6b01d93de9..2a8542d640 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs @@ -19,6 +19,8 @@ namespace Volo.Abp.Cli.Commands; public class NewCommand : ProjectCreationCommandBase, IConsoleCommand, ITransientDependency { + public const string Name = "new"; + public ILogger Logger { get; set; } protected TemplateProjectBuilder TemplateProjectBuilder { get; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/PromptCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/PromptCommand.cs index f1ff0f6025..cbd9267989 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/PromptCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/PromptCommand.cs @@ -7,6 +7,8 @@ namespace Volo.Abp.Cli.Commands; public class PromptCommand : IConsoleCommand, ITransientDependency { + public const string Name = "prompt"; + public Task ExecuteAsync(CommandLineArgs commandLineArgs) { return Task.CompletedTask; diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs index cbb8ae6640..1a4d5bfc98 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; using Volo.Abp.Cli.ProjectBuilding.Building; using Volo.Abp.DependencyInjection; @@ -21,7 +22,8 @@ public class ConnectionStringProvider : ITransientDependency case DatabaseManagementSystem.OracleDevart: return "Data Source=MyProjectName;Integrated Security=yes;"; case DatabaseManagementSystem.SQLite: - return $"Data Source={Path.Combine(outputFolder, "MyProjectName.db")};".Replace("\\", "\\\\"); + var comment = outputFolder.IsNullOrWhiteSpace() ? "//You need to change to an absolute filename" : string.Empty; + return $"Data Source={Path.Combine(outputFolder, "MyProjectName.db")};".Replace("\\", "\\\\") + comment; default: return null; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs index 760cbb0e45..0e797e682f 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs @@ -15,6 +15,8 @@ namespace Volo.Abp.Cli.Commands; public class SuiteCommand : IConsoleCommand, ITransientDependency { + public const string Name = "suite"; + public ICmdHelper CmdHelper { get; } private readonly AbpNuGetIndexUrlService _nuGetIndexUrlService; private readonly NuGetService _nuGetService; diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToNightlyCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToNightlyCommand.cs index 0bfb3ea24b..4893680004 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToNightlyCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToNightlyCommand.cs @@ -8,6 +8,8 @@ namespace Volo.Abp.Cli.Commands; public class SwitchToNightlyCommand : IConsoleCommand, ITransientDependency { + public const string Name = "switch-to-nightly"; + private readonly PackagePreviewSwitcher _packagePreviewSwitcher; public SwitchToNightlyCommand(PackagePreviewSwitcher packagePreviewSwitcher) diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToPreviewCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToPreviewCommand.cs index 2917a58449..84b58d6b8b 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToPreviewCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToPreviewCommand.cs @@ -8,6 +8,8 @@ namespace Volo.Abp.Cli.Commands; public class SwitchToPreviewCommand : IConsoleCommand, ITransientDependency { + public const string Name = "switch-to-preview"; + private readonly PackagePreviewSwitcher _packagePreviewSwitcher; public SwitchToPreviewCommand(PackagePreviewSwitcher packagePreviewSwitcher) diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToStableCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToStableCommand.cs index 84400f85ef..cc0fa9ff75 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToStableCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SwitchToStableCommand.cs @@ -8,6 +8,8 @@ namespace Volo.Abp.Cli.Commands; public class SwitchToStableCommand : IConsoleCommand, ITransientDependency { + public const string Name = "switch-to-stable"; + private readonly PackagePreviewSwitcher _packagePreviewSwitcher; public SwitchToStableCommand(PackagePreviewSwitcher packagePreviewSwitcher) diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/TranslateCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/TranslateCommand.cs index f4895538da..ea6b1d45f6 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/TranslateCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/TranslateCommand.cs @@ -15,6 +15,8 @@ namespace Volo.Abp.Cli.Commands; public class TranslateCommand : IConsoleCommand, ITransientDependency { + public const string Name = "translate"; + public ILogger Logger { get; set; } public Task ExecuteAsync(CommandLineArgs commandLineArgs) diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/UpdateCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/UpdateCommand.cs index 7057df1dd0..fdc9b83fcf 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/UpdateCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/UpdateCommand.cs @@ -13,6 +13,8 @@ namespace Volo.Abp.Cli.Commands; public class UpdateCommand : IConsoleCommand, ITransientDependency { + public const string Name = "update"; + public ILogger Logger { get; set; } private readonly VoloNugetPackagesVersionUpdater _nugetPackagesVersionUpdater; diff --git a/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs b/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs index 7748953cc4..ce4af2befa 100644 --- a/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs +++ b/framework/src/Volo.Abp.Core/Microsoft/Extensions/DependencyInjection/ServiceCollectionApplicationExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp; using Volo.Abp.Modularity; @@ -22,4 +23,20 @@ public static class ServiceCollectionApplicationExtensions { return AbpApplicationFactory.Create(startupModuleType, services, optionsAction); } + + public async static Task AddApplicationAsync( + [NotNull] this IServiceCollection services, + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + return await AbpApplicationFactory.CreateAsync(services, optionsAction); + } + + public async static Task AddApplicationAsync( + [NotNull] this IServiceCollection services, + [NotNull] Type startupModuleType, + [CanBeNull] Action optionsAction = null) + { + return await AbpApplicationFactory.CreateAsync(startupModuleType, services, optionsAction); + } } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs index 85b1989445..2a73b72932 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationBase.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -23,6 +24,8 @@ public abstract class AbpApplicationBase : IAbpApplication public IReadOnlyList Modules { get; } + private bool _configuredServices; + internal AbpApplicationBase( [NotNull] Type startupModuleType, [NotNull] IServiceCollection services, @@ -46,7 +49,21 @@ public abstract class AbpApplicationBase : IAbpApplication services.AddCoreAbpServices(this, options); Modules = LoadModules(services, options); - ConfigureServices(); + + if (!options.SkipConfigureServices) + { + ConfigureServices(); + } + } + + public virtual async Task ShutdownAsync() + { + using (var scope = ServiceProvider.CreateScope()) + { + await scope.ServiceProvider + .GetRequiredService() + .ShutdownModulesAsync(new ApplicationShutdownContext(scope.ServiceProvider)); + } } public virtual void Shutdown() @@ -70,6 +87,17 @@ public abstract class AbpApplicationBase : IAbpApplication ServiceProvider.GetRequiredService>().Value = ServiceProvider; } + protected virtual async Task InitializeModulesAsync() + { + using (var scope = ServiceProvider.CreateScope()) + { + WriteInitLogs(scope.ServiceProvider); + await scope.ServiceProvider + .GetRequiredService() + .InitializeModulesAsync(new ApplicationInitializationContext(scope.ServiceProvider)); + } + } + protected virtual void InitializeModules() { using (var scope = ServiceProvider.CreateScope()) @@ -111,8 +139,99 @@ public abstract class AbpApplicationBase : IAbpApplication } //TODO: We can extract a new class for this - protected virtual void ConfigureServices() + public virtual async Task ConfigureServicesAsync() + { + CheckMultipleConfigureServices(); + + var context = new ServiceConfigurationContext(Services); + Services.AddSingleton(context); + + foreach (var module in Modules) + { + if (module.Instance is AbpModule abpModule) + { + abpModule.ServiceConfigurationContext = context; + } + } + + //PreConfigureServices + foreach (var module in Modules.Where(m => m.Instance is IPreConfigureServices)) + { + try + { + await ((IPreConfigureServices)module.Instance).PreConfigureServicesAsync(context); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during {nameof(IPreConfigureServices.PreConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex); + } + } + + var assemblies = new HashSet(); + + //ConfigureServices + foreach (var module in Modules) + { + if (module.Instance is AbpModule abpModule) + { + if (!abpModule.SkipAutoServiceRegistration) + { + var assembly = module.Type.Assembly; + if (!assemblies.Contains(assembly)) + { + Services.AddAssembly(assembly); + assemblies.Add(assembly); + } + } + } + + try + { + await module.Instance.ConfigureServicesAsync(context); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during {nameof(IAbpModule.ConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex); + } + } + + //PostConfigureServices + foreach (var module in Modules.Where(m => m.Instance is IPostConfigureServices)) + { + try + { + await ((IPostConfigureServices)module.Instance).PostConfigureServicesAsync(context); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during {nameof(IPostConfigureServices.PostConfigureServicesAsync)} phase of the module {module.Type.AssemblyQualifiedName}. See the inner exception for details.", ex); + } + } + + foreach (var module in Modules) + { + if (module.Instance is AbpModule abpModule) + { + abpModule.ServiceConfigurationContext = null; + } + } + + _configuredServices = true; + } + + private void CheckMultipleConfigureServices() + { + if (_configuredServices) + { + throw new AbpInitializationException("Services have already been configured! If you call ConfigureServicesAsync method, you must have set AbpApplicationCreationOptions.SkipConfigureServices tu true before."); + } + } + + //TODO: We can extract a new class for this + public virtual void ConfigureServices() { + CheckMultipleConfigureServices(); + var context = new ServiceConfigurationContext(Services); Services.AddSingleton(context); @@ -185,5 +304,7 @@ public abstract class AbpApplicationBase : IAbpApplication abpModule.ServiceConfigurationContext = null; } } + + _configuredServices = true; } } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs index ea2d69aae6..d18e43275b 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationCreationOptions.cs @@ -19,6 +19,8 @@ public class AbpApplicationCreationOptions [NotNull] public AbpConfigurationBuilderOptions Configuration { get; } + public bool SkipConfigureServices { get; set; } + public AbpApplicationCreationOptions([NotNull] IServiceCollection services) { Services = Check.NotNull(services, nameof(services)); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs index 13b886f1c3..3d64b39b7c 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationFactory.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; @@ -7,6 +8,60 @@ namespace Volo.Abp; public static class AbpApplicationFactory { + public async static Task CreateAsync( + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + var app = Create(typeof(TStartupModule), options => + { + options.SkipConfigureServices = true; + optionsAction?.Invoke(options); + }); + await app.ConfigureServicesAsync(); + return app; + } + + public async static Task CreateAsync( + [NotNull] Type startupModuleType, + [CanBeNull] Action optionsAction = null) + { + var app = new AbpApplicationWithInternalServiceProvider(startupModuleType, options => + { + options.SkipConfigureServices = true; + optionsAction?.Invoke(options); + }); + await app.ConfigureServicesAsync(); + return app; + } + + public async static Task CreateAsync( + [NotNull] IServiceCollection services, + [CanBeNull] Action optionsAction = null) + where TStartupModule : IAbpModule + { + var app = Create(typeof(TStartupModule), services, options => + { + options.SkipConfigureServices = true; + optionsAction?.Invoke(options); + }); + await app.ConfigureServicesAsync(); + return app; + } + + public async static Task CreateAsync( + [NotNull] Type startupModuleType, + [NotNull] IServiceCollection services, + [CanBeNull] Action optionsAction = null) + { + var app = new AbpApplicationWithExternalServiceProvider(startupModuleType, services, options => + { + options.SkipConfigureServices = true; + optionsAction?.Invoke(options); + }); + await app.ConfigureServicesAsync(); + return app; + } + public static IAbpApplicationWithInternalServiceProvider Create( [CanBeNull] Action optionsAction = null) where TStartupModule : IAbpModule diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs index 162d68b5d7..fbb9d611cf 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithExternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; @@ -35,6 +36,15 @@ internal class AbpApplicationWithExternalServiceProvider : AbpApplicationBase, I SetServiceProvider(serviceProvider); } + public async Task InitializeAsync(IServiceProvider serviceProvider) + { + Check.NotNull(serviceProvider, nameof(serviceProvider)); + + SetServiceProvider(serviceProvider); + + await InitializeModulesAsync(); + } + public void Initialize([NotNull] IServiceProvider serviceProvider) { Check.NotNull(serviceProvider, nameof(serviceProvider)); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs index eb118410cd..245ce6fb06 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/AbpApplicationWithInternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; @@ -44,6 +45,12 @@ internal class AbpApplicationWithInternalServiceProvider : AbpApplicationBase, I return ServiceProvider; } + public async Task InitializeAsync() + { + CreateServiceProvider(); + await InitializeModulesAsync(); + } + public void Initialize() { CreateServiceProvider(); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs index de9201bebc..2fb66b735f 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplication.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; @@ -22,6 +23,18 @@ public interface IAbpApplication : IModuleContainer, IDisposable /// This can not be used before initialize the application. /// IServiceProvider ServiceProvider { get; } + + /// + /// Calls the Pre/Post/ConfigureServicesAsync methods of the modules. + /// If you use this method, you must have set the + /// option to true before. + /// + Task ConfigureServicesAsync(); + + /// + /// Used to gracefully shutdown the application and all modules. + /// + Task ShutdownAsync(); /// /// Used to gracefully shutdown the application and all modules. diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs index 91c95f4518..a17bb146e3 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithExternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JetBrains.Annotations; namespace Volo.Abp; @@ -9,6 +10,13 @@ public interface IAbpApplicationWithExternalServiceProvider : IAbpApplication /// Sets the service provider, but not initializes the modules. /// void SetServiceProvider([NotNull] IServiceProvider serviceProvider); + + /// + /// Sets the service provider and initializes all the modules. + /// If was called before, the same + /// instance should be passed to this method. + /// + Task InitializeAsync([NotNull] IServiceProvider serviceProvider); /// /// Sets the service provider and initializes all the modules. diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs index 61fdb0652f..0079608c2e 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IAbpApplicationWithInternalServiceProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; namespace Volo.Abp; @@ -10,6 +11,13 @@ public interface IAbpApplicationWithInternalServiceProvider : IAbpApplication /// IServiceProvider CreateServiceProvider(); + /// + /// Creates the service provider and initializes all the modules. + /// If method was called before, + /// it does not re-create it, but uses the previous one. + /// + Task InitializeAsync(); + /// /// Creates the service provider and initializes all the modules. /// If method was called before, diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs index 5ed95a545b..6131a8b710 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationInitialization.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp; public interface IOnApplicationInitialization { + Task OnApplicationInitializationAsync([NotNull] ApplicationInitializationContext context); + void OnApplicationInitialization([NotNull] ApplicationInitializationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs index ced040851e..9f67ebb466 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/IOnApplicationShutdown.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp; public interface IOnApplicationShutdown { + Task OnApplicationShutdownAsync([NotNull] ApplicationShutdownContext context); + void OnApplicationShutdown([NotNull] ApplicationShutdownContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs index 537ccc54f6..ae2bec3112 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/AbpModule.cs @@ -1,5 +1,6 @@ using System; using System.Reflection; +using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -30,36 +31,78 @@ public abstract class AbpModule : private ServiceConfigurationContext _serviceConfigurationContext; + public virtual Task PreConfigureServicesAsync(ServiceConfigurationContext context) + { + PreConfigureServices(context); + return Task.CompletedTask; + } + public virtual void PreConfigureServices(ServiceConfigurationContext context) { } + public virtual Task ConfigureServicesAsync(ServiceConfigurationContext context) + { + ConfigureServices(context); + return Task.CompletedTask; + } + public virtual void ConfigureServices(ServiceConfigurationContext context) { } + public virtual Task PostConfigureServicesAsync(ServiceConfigurationContext context) + { + PostConfigureServices(context); + return Task.CompletedTask; + } + public virtual void PostConfigureServices(ServiceConfigurationContext context) { } + public virtual Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPreApplicationInitialization(context); + return Task.CompletedTask; + } + public virtual void OnPreApplicationInitialization(ApplicationInitializationContext context) { } + public virtual Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnApplicationInitialization(context); + return Task.CompletedTask; + } + public virtual void OnApplicationInitialization(ApplicationInitializationContext context) { } + public virtual Task OnPostApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPostApplicationInitialization(context); + return Task.CompletedTask; + } + public virtual void OnPostApplicationInitialization(ApplicationInitializationContext context) { } + public virtual Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + OnApplicationShutdown(context); + return Task.CompletedTask; + } + public virtual void OnApplicationShutdown(ApplicationShutdownContext context) { diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs index f548cfaafb..c520cc8d58 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/DefaultModuleLifecycleContributor.cs @@ -1,7 +1,17 @@ -namespace Volo.Abp.Modularity; +using System.Threading.Tasks; + +namespace Volo.Abp.Modularity; public class OnApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + if (module is IOnApplicationInitialization onApplicationInitialization) + { + await onApplicationInitialization.OnApplicationInitializationAsync(context); + } + } + public override void Initialize(ApplicationInitializationContext context, IAbpModule module) { (module as IOnApplicationInitialization)?.OnApplicationInitialization(context); @@ -10,6 +20,14 @@ public class OnApplicationInitializationModuleLifecycleContributor : ModuleLifec public class OnApplicationShutdownModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task ShutdownAsync(ApplicationShutdownContext context, IAbpModule module) + { + if (module is IOnApplicationShutdown onApplicationShutdown) + { + await onApplicationShutdown.OnApplicationShutdownAsync(context); + } + } + public override void Shutdown(ApplicationShutdownContext context, IAbpModule module) { (module as IOnApplicationShutdown)?.OnApplicationShutdown(context); @@ -18,6 +36,14 @@ public class OnApplicationShutdownModuleLifecycleContributor : ModuleLifecycleCo public class OnPreApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + if (module is IOnPreApplicationInitialization onPreApplicationInitialization) + { + await onPreApplicationInitialization.OnPreApplicationInitializationAsync(context); + } + } + public override void Initialize(ApplicationInitializationContext context, IAbpModule module) { (module as IOnPreApplicationInitialization)?.OnPreApplicationInitialization(context); @@ -26,6 +52,14 @@ public class OnPreApplicationInitializationModuleLifecycleContributor : ModuleLi public class OnPostApplicationInitializationModuleLifecycleContributor : ModuleLifecycleContributorBase { + public async override Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + if (module is IOnPostApplicationInitialization onPostApplicationInitialization) + { + await onPostApplicationInitialization.OnPostApplicationInitializationAsync(context); + } + } + public override void Initialize(ApplicationInitializationContext context, IAbpModule module) { (module as IOnPostApplicationInitialization)?.OnPostApplicationInitialization(context); diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs index b992020d4c..3622a50324 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IAbpModule.cs @@ -1,6 +1,10 @@ -namespace Volo.Abp.Modularity; +using System.Threading.Tasks; + +namespace Volo.Abp.Modularity; public interface IAbpModule { + Task ConfigureServicesAsync(ServiceConfigurationContext context); + void ConfigureServices(ServiceConfigurationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs index 299bfe9e5a..ca0ad1cfd8 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleLifecycleContributor.cs @@ -1,11 +1,16 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; using Volo.Abp.DependencyInjection; namespace Volo.Abp.Modularity; public interface IModuleLifecycleContributor : ITransientDependency { + Task InitializeAsync([NotNull] ApplicationInitializationContext context, [NotNull] IAbpModule module); + void Initialize([NotNull] ApplicationInitializationContext context, [NotNull] IAbpModule module); + Task ShutdownAsync([NotNull] ApplicationShutdownContext context, [NotNull] IAbpModule module); + void Shutdown([NotNull] ApplicationShutdownContext context, [NotNull] IAbpModule module); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs index d981b745b9..eb4cf52e3c 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IModuleManager.cs @@ -1,10 +1,15 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp.Modularity; public interface IModuleManager { + Task InitializeModulesAsync([NotNull] ApplicationInitializationContext context); + void InitializeModules([NotNull] ApplicationInitializationContext context); + Task ShutdownModulesAsync([NotNull] ApplicationShutdownContext context); + void ShutdownModules([NotNull] ApplicationShutdownContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs index d79a0318ec..26177360f9 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPostApplicationInitialization.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp.Modularity; public interface IOnPostApplicationInitialization { + Task OnPostApplicationInitializationAsync([NotNull] ApplicationInitializationContext context); + void OnPostApplicationInitialization([NotNull] ApplicationInitializationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs index 0426ef50af..7e63301e3e 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IOnPreApplicationInitialization.cs @@ -1,8 +1,11 @@ -using JetBrains.Annotations; +using System.Threading.Tasks; +using JetBrains.Annotations; namespace Volo.Abp.Modularity; public interface IOnPreApplicationInitialization { + Task OnPreApplicationInitializationAsync([NotNull] ApplicationInitializationContext context); + void OnPreApplicationInitialization([NotNull] ApplicationInitializationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs index 38d3449b85..a1ea07de27 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPostConfigureServices.cs @@ -1,8 +1,10 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; namespace Volo.Abp.Modularity; public interface IPostConfigureServices { + Task PostConfigureServicesAsync(ServiceConfigurationContext context); + void PostConfigureServices(ServiceConfigurationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs index 51db8f5fb8..dfb9eef1df 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/IPreConfigureServices.cs @@ -1,8 +1,10 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; namespace Volo.Abp.Modularity; public interface IPreConfigureServices { + Task PreConfigureServicesAsync(ServiceConfigurationContext context); + void PreConfigureServices(ServiceConfigurationContext context); } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs index b3ac566eab..3192d1f2ea 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleLifecycleContributorBase.cs @@ -1,11 +1,23 @@ -namespace Volo.Abp.Modularity; +using System.Threading.Tasks; + +namespace Volo.Abp.Modularity; public abstract class ModuleLifecycleContributorBase : IModuleLifecycleContributor { + public virtual Task InitializeAsync(ApplicationInitializationContext context, IAbpModule module) + { + return Task.CompletedTask; + } + public virtual void Initialize(ApplicationInitializationContext context, IAbpModule module) { } + public virtual Task ShutdownAsync(ApplicationShutdownContext context, IAbpModule module) + { + return Task.CompletedTask; + } + public virtual void Shutdown(ApplicationShutdownContext context, IAbpModule module) { } diff --git a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs index 2218b2f6fd..71697a1a83 100644 --- a/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs +++ b/framework/src/Volo.Abp.Core/Volo/Abp/Modularity/ModuleManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -30,6 +31,26 @@ public class ModuleManager : IModuleManager, ISingletonDependency .ToArray(); } + public virtual async Task InitializeModulesAsync(ApplicationInitializationContext context) + { + foreach (var contributor in _lifecycleContributors) + { + foreach (var module in _moduleContainer.Modules) + { + try + { + await contributor.InitializeAsync(context, module.Instance); + } + catch (Exception ex) + { + throw new AbpInitializationException($"An error occurred during the initialize {contributor.GetType().FullName} phase of the module {module.Type.AssemblyQualifiedName}: {ex.Message}. See the inner exception for details.", ex); + } + } + } + + _logger.LogInformation("Initialized all ABP modules."); + } + public void InitializeModules(ApplicationInitializationContext context) { foreach (var contributor in _lifecycleContributors) @@ -50,6 +71,26 @@ public class ModuleManager : IModuleManager, ISingletonDependency _logger.LogInformation("Initialized all ABP modules."); } + public virtual async Task ShutdownModulesAsync(ApplicationShutdownContext context) + { + var modules = _moduleContainer.Modules.Reverse().ToList(); + + foreach (var contributor in _lifecycleContributors) + { + foreach (var module in modules) + { + try + { + await contributor.ShutdownAsync(context, module.Instance); + } + catch (Exception ex) + { + throw new AbpShutdownException($"An error occurred during the shutdown {contributor.GetType().FullName} phase of the module {module.Type.AssemblyQualifiedName}: {ex.Message}. See the inner exception for details.", ex); + } + } + } + } + public void ShutdownModules(ApplicationShutdownContext context) { var modules = _moduleContainer.Modules.Reverse().ToList(); diff --git a/framework/src/Volo.Abp.EntityFrameworkCore.Oracle.Devart/Volo.Abp.EntityFrameworkCore.Oracle.Devart.csproj b/framework/src/Volo.Abp.EntityFrameworkCore.Oracle.Devart/Volo.Abp.EntityFrameworkCore.Oracle.Devart.csproj index a3021984d2..918ac8ddf3 100644 --- a/framework/src/Volo.Abp.EntityFrameworkCore.Oracle.Devart/Volo.Abp.EntityFrameworkCore.Oracle.Devart.csproj +++ b/framework/src/Volo.Abp.EntityFrameworkCore.Oracle.Devart/Volo.Abp.EntityFrameworkCore.Oracle.Devart.csproj @@ -19,8 +19,8 @@ - - + + diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs index cb0a32f47c..b4a873dcd4 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs +++ b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/AbpEventBusModule.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; +using System.Threading.Tasks; using Volo.Abp.BackgroundWorkers; using Volo.Abp.DistributedLocking; using Volo.Abp.EventBus.Abstractions; @@ -12,6 +13,7 @@ using Volo.Abp.Json; using Volo.Abp.Modularity; using Volo.Abp.MultiTenancy; using Volo.Abp.Reflection; +using Volo.Abp.Threading; namespace Volo.Abp.EventBus; @@ -30,10 +32,16 @@ public class AbpEventBusModule : AbpModule AddEventHandlers(context.Services); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + await context.AddBackgroundWorkerAsync(); + await context.AddBackgroundWorkerAsync(); + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { - context.AddBackgroundWorker(); - context.AddBackgroundWorker(); + AsyncHelper.RunSync(() => context.AddBackgroundWorkerAsync()); + AsyncHelper.RunSync(() => context.AddBackgroundWorkerAsync()); } private static void AddEventHandlers(IServiceCollection services) diff --git a/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs b/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs index ade14f1b83..db790a717d 100644 --- a/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs +++ b/framework/src/Volo.Abp.Quartz/Volo/Abp/Quartz/AbpQuartzModule.cs @@ -1,8 +1,8 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Quartz; using Quartz.Impl; -using Quartz.Impl.AdoJobStore.Common; using Volo.Abp.Modularity; using Volo.Abp.Threading; @@ -18,8 +18,8 @@ public class AbpQuartzModule : AbpModule context.Services.AddQuartz(options.Properties, build => { - // these are the defaults - if (options.Properties[StdSchedulerFactory.PropertySchedulerJobFactoryType] == null) + // these are the defaults + if (options.Properties[StdSchedulerFactory.PropertySchedulerJobFactoryType] == null) { build.UseMicrosoftDependencyInjectionScopedJobFactory(); } @@ -62,6 +62,23 @@ public class AbpQuartzModule : AbpModule }); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + + _scheduler = context.ServiceProvider.GetRequiredService(); + + await options.StartSchedulerFactory.Invoke(_scheduler); + } + + public async override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + if (_scheduler.IsStarted) + { + await _scheduler.Shutdown(); + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; diff --git a/framework/src/Volo.Abp.Settings/Volo/Abp/Settings/SettingProvider.cs b/framework/src/Volo.Abp.Settings/Volo/Abp/Settings/SettingProvider.cs index 710e64539a..01791bef00 100644 --- a/framework/src/Volo.Abp.Settings/Volo/Abp/Settings/SettingProvider.cs +++ b/framework/src/Volo.Abp.Settings/Volo/Abp/Settings/SettingProvider.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Volo.Abp.DependencyInjection; @@ -73,6 +73,10 @@ public class SettingProvider : ISettingProvider, ITransientDependency } settingDefinitions.RemoveAll(x => notNullValues.Any(v => v.Name == x.Name)); + if (!settingDefinitions.Any()) + { + break; + } } return result.Values.ToList(); @@ -106,4 +110,4 @@ public class SettingProvider : ISettingProvider, ITransientDependency return null; } -} +} \ No newline at end of file diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs index 6167d823cb..407660e854 100644 --- a/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/AbpTestBaseWithServiceProvider.cs @@ -5,7 +5,7 @@ namespace Volo.Abp; public abstract class AbpTestBaseWithServiceProvider { - protected abstract IServiceProvider ServiceProvider { get; } + protected IServiceProvider ServiceProvider { get; set; } protected virtual T GetService() { diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs new file mode 100644 index 0000000000..4238a8712b --- /dev/null +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpAsyncIntegratedTest.cs @@ -0,0 +1,70 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Modularity; + +namespace Volo.Abp.Testing; + +public class AbpAsyncIntegratedTest : AbpTestBaseWithServiceProvider + where TStartupModule : IAbpModule +{ + protected IAbpApplication Application { get; set; } + + protected IServiceProvider RootServiceProvider { get; set; } + + protected IServiceScope TestServiceScope { get; set; } + + public virtual async Task InitializeAsync() + { + var services = await CreateServiceCollectionAsync(); + + await BeforeAddApplicationAsync(services); + var application = await services.AddApplicationAsync(await SetAbpApplicationCreationOptionsAsync()); + await AfterAddApplicationAsync(services); + + RootServiceProvider = await CreateServiceProviderAsync(services); + TestServiceScope = RootServiceProvider.CreateScope(); + await application.InitializeAsync(TestServiceScope.ServiceProvider); + ServiceProvider = application.ServiceProvider; + Application = application; + + await InitializeServicesAsync(); + } + + public virtual async Task DisposeAsync() + { + await Application.ShutdownAsync(); + TestServiceScope.Dispose(); + Application.Dispose(); + } + + protected virtual Task CreateServiceCollectionAsync() + { + return Task.FromResult(new ServiceCollection()); + } + + protected virtual Task BeforeAddApplicationAsync(IServiceCollection services) + { + return Task.CompletedTask; + } + + protected virtual Task> SetAbpApplicationCreationOptionsAsync() + { + return Task.FromResult>(_ => { }); + } + + protected virtual Task AfterAddApplicationAsync(IServiceCollection services) + { + return Task.CompletedTask; + } + + protected virtual Task CreateServiceProviderAsync(IServiceCollection services) + { + return Task.FromResult(services.BuildServiceProviderFromFactory()); + } + + protected virtual Task InitializeServicesAsync() + { + return Task.CompletedTask; + } +} diff --git a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs index bb085f6f74..8d8612c5b9 100644 --- a/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs +++ b/framework/src/Volo.Abp.TestBase/Volo/Abp/Testing/AbpIntegratedTest.cs @@ -9,8 +9,6 @@ public abstract class AbpIntegratedTest : AbpTestBaseWithService { protected IAbpApplication Application { get; } - protected override IServiceProvider ServiceProvider => Application.ServiceProvider; - protected IServiceProvider RootServiceProvider { get; } protected IServiceScope TestServiceScope { get; } @@ -30,6 +28,7 @@ public abstract class AbpIntegratedTest : AbpTestBaseWithService TestServiceScope = RootServiceProvider.CreateScope(); application.Initialize(TestServiceScope.ServiceProvider); + ServiceProvider = Application.ServiceProvider; } protected virtual IServiceCollection CreateServiceCollection() diff --git a/framework/src/Volo.Abp.UI/Localization/Resources/AbpUi/zh-Hant.json b/framework/src/Volo.Abp.UI/Localization/Resources/AbpUi/zh-Hant.json index 5f73fa7ccd..449dd67480 100644 --- a/framework/src/Volo.Abp.UI/Localization/Resources/AbpUi/zh-Hant.json +++ b/framework/src/Volo.Abp.UI/Localization/Resources/AbpUi/zh-Hant.json @@ -46,8 +46,8 @@ "GoHomePage": "返回首頁", "GoBack": "返回", "Search": "查詢", - "ItemWillBeDeletedMessageWithFormat": "{0} will be deleted!", - "ItemWillBeDeletedMessage": "This item will be deleted!", - "ManageYourAccount": "Manage your account" + "ItemWillBeDeletedMessageWithFormat": "{0} 將被刪除!", + "ItemWillBeDeletedMessage": "此項目將被刪除!", + "ManageYourAccount": "管理個人帳號" } } diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs new file mode 100644 index 0000000000..5d475966a2 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreAsyncTestBase_Tests.cs @@ -0,0 +1,62 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Volo.Abp.AspNetCore.TestBase; +using Volo.Abp.Autofac; +using Volo.Abp.Modularity; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc; + +public class AbpAspNetCoreAsyncTestBase_Tests : AbpAspNetCoreAsyncTestBase +{ + [Fact] + public async Task Get_API_Response_Test() + { + var result = await GetResponseAsStringAsync("/api"); + result.ShouldBe(await GetRequiredService().GetResponseAsync()); + } +} + +[DependsOn( + typeof(AbpAspNetCoreMvcModule), + typeof(AbpAspNetCoreTestBaseModule), + typeof(AbpAutofacModule) +)] +public class AbpAspNetCoreAsyncTestModule : AbpModule +{ + public override Task ConfigureServicesAsync(ServiceConfigurationContext context) + { + context.Services.AddTransient(); + return Task.CompletedTask; + } + + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + var app = context.GetApplicationBuilder(); + + var dataBaseService = app.ApplicationServices.GetRequiredService(); + + var apiResponse = await dataBaseService.GetResponseAsync(); + app.Map("/api", _ => + { + app.Run(async httpContext => + { + await httpContext.Response.WriteAsync(apiResponse); + }); + }); + + app.UseRouting(); + app.UseConfiguredEndpoints(); + } +} + +public class DataBaseService +{ + public Task GetResponseAsync() + { + return Task.FromResult("hello api!"); + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs b/framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs new file mode 100644 index 0000000000..0d222deab4 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Tests/Volo/Abp/AspNetCore/AbpAspNetCoreAsyncTestBase.cs @@ -0,0 +1,45 @@ +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.Net.Http.Headers; +using Shouldly; +using Volo.Abp.AspNetCore.TestBase; +using Volo.Abp.Modularity; +using Xunit; + +namespace Volo.Abp.AspNetCore; + +public abstract class AbpAspNetCoreAsyncTestBase : AbpAspNetCoreAsyncIntegratedTestBase, IAsyncLifetime + where TModule : AbpModule +{ + protected virtual async Task GetResponseAsObjectAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) + { + var strResponse = await GetResponseAsStringAsync(url, expectedStatusCode); + return JsonSerializer.Deserialize(strResponse, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + } + + protected virtual async Task GetResponseAsStringAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) + { + using (var response = await GetResponseAsync(url, expectedStatusCode)) + { + return await response.Content.ReadAsStringAsync(); + } + } + + protected virtual async Task GetResponseAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, bool xmlHttpRequest = false) + { + using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, url)) + { + requestMessage.Headers.Add("Accept-Language", CultureInfo.CurrentUICulture.Name); + if (xmlHttpRequest) + { + requestMessage.Headers.Add(HeaderNames.XRequestedWith, "XMLHttpRequest"); + } + var response = await Client.SendAsync(requestMessage); + response.StatusCode.ShouldBe(expectedStatusCode); + return response; + } + } +} diff --git a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs index a7a2dfafbc..290abda61b 100644 --- a/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs +++ b/framework/test/Volo.Abp.Autofac.Tests/Volo/Abp/Autofac/Interception/Autofac_Interception_Test.cs @@ -1,11 +1,13 @@ -using Volo.Abp.DynamicProxy; +using System; +using System.Threading.Tasks; +using Volo.Abp.DynamicProxy; namespace Volo.Abp.Autofac.Interception; public class Autofac_Interception_Test : AbpInterceptionTestBase { - protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) + protected override Task> SetAbpApplicationCreationOptionsAsync() { - options.UseAutofac(); + return Task.FromResult>(options => options.UseAutofac()); } } diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs index 63bc7f5f78..f69d94ce61 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/AbpApplication_Initialize_Tests.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; using Volo.Abp.Modularity.PlugIns; @@ -8,6 +9,39 @@ namespace Volo.Abp; public class AbpApplication_Initialize_Tests { + [Fact] + public async Task Should_Initialize_Single_Module_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + //Assert + var module = application.Services.GetSingletonInstance(); + + module.PreConfigureServicesAsyncIsCalled.ShouldBeTrue(); + module.PreConfigureServicesIsCalled.ShouldBeTrue(); + + module.ConfigureServicesAsyncIsCalled.ShouldBeTrue(); + module.ConfigureServicesIsCalled.ShouldBeTrue(); + + module.PostConfigureServicesAsyncIsCalled.ShouldBeTrue(); + module.PostConfigureServicesIsCalled.ShouldBeTrue(); + + //Act + await application.InitializeAsync(); + + //Assert + application.ServiceProvider.GetRequiredService().ShouldBeSameAs(module); + module.OnApplicationInitializeAsyncIsCalled.ShouldBeTrue(); + module.OnApplicationInitializeIsCalled.ShouldBeTrue(); + //Act + await application.ShutdownAsync(); + + //Assert + module.OnApplicationShutdownAsyncIsCalled.ShouldBeTrue(); + module.OnApplicationShutdownIsCalled.ShouldBeTrue(); + } + } + [Fact] public void Should_Initialize_Single_Module() { @@ -34,6 +68,50 @@ public class AbpApplication_Initialize_Tests } } + [Fact] + public async Task Should_Initialize_PlugIn_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync(options => + { + options.PlugInSources.AddTypes(typeof(IndependentEmptyPlugInModule)); + })) + { + //Assert + var plugInModule = application.Services.GetSingletonInstance(); + + plugInModule.PreConfigureServicesAsyncIsCalled.ShouldBeTrue(); + plugInModule.PreConfigureServicesIsCalled.ShouldBeTrue(); + + plugInModule.ConfigureServicesAsyncIsCalled.ShouldBeTrue(); + plugInModule.ConfigureServicesIsCalled.ShouldBeTrue(); + + plugInModule.PostConfigureServicesAsyncIsCalled.ShouldBeTrue(); + plugInModule.PostConfigureServicesIsCalled.ShouldBeTrue(); + + //Act + await application.InitializeAsync(); + + //Assert + application.ServiceProvider.GetRequiredService().ShouldBeSameAs(plugInModule); + + plugInModule.OnPreApplicationInitializationAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnPreApplicationInitializationIsCalled.ShouldBeTrue(); + + plugInModule.OnApplicationInitializeAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnApplicationInitializeIsCalled.ShouldBeTrue(); + + plugInModule.OnPostApplicationInitializationAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnPostApplicationInitializationIsCalled.ShouldBeTrue(); + + //Act + await application.ShutdownAsync(); + + //Assert + plugInModule.OnApplicationShutdownAsyncIsCalled.ShouldBeTrue(); + plugInModule.OnApplicationShutdownIsCalled.ShouldBeTrue(); + } + } + [Fact] public void Should_Initialize_PlugIn() { @@ -53,7 +131,9 @@ public class AbpApplication_Initialize_Tests //Assert application.ServiceProvider.GetRequiredService().ShouldBeSameAs(plugInModule); + plugInModule.OnPreApplicationInitializationIsCalled.ShouldBeTrue(); plugInModule.OnApplicationInitializeIsCalled.ShouldBeTrue(); + plugInModule.OnPostApplicationInitializationIsCalled.ShouldBeTrue(); //Act application.Shutdown(); diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs index 9023fb6ce7..4a0dda26fb 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Configuration/ConfigurationAccessor_Tests.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; @@ -8,6 +9,22 @@ namespace Volo.Abp.Configuration; public class ConfigurationAccessor_Tests { + [Fact] + public async Task Should_Use_Empty_ConfigurationRoot_By_Default_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + var configuration1 = application.Services.GetConfiguration(); + configuration1.ShouldNotBeNull(); + + await application.InitializeAsync(); + + var configuration2 = ResolveConfiguration(application); + + configuration2.ShouldBe(configuration1); + } + } + [Fact] public void Should_Use_Empty_ConfigurationRoot_By_Default() { @@ -24,6 +41,23 @@ public class ConfigurationAccessor_Tests } } + [Fact] + public async Task Should_Use_The_Registered_ConfigurationRoot_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + var myConfiguration = new ConfigurationBuilder().Build(); + application.Services.ReplaceConfiguration(myConfiguration); + application.Services.GetConfiguration().ShouldBe(myConfiguration); + + await application.InitializeAsync(); + + var configuration = ResolveConfiguration(application); + + configuration.ShouldBe(myConfiguration); + } + } + [Fact] public void Should_Use_The_Registered_ConfigurationRoot() { diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs index 6fc5716a22..71ec559824 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/AutoServiceRegistration_Tests.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; @@ -8,6 +9,20 @@ namespace Volo.Abp.DependencyInjection; public class AutoServiceRegistration_Tests { + [Fact] + public async Task AutoServiceRegistration_Should_Not_Duplicate_Test_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + //Act + await application.InitializeAsync(); + + //Assert + var services = application.ServiceProvider.GetServices().ToList(); + services.Count.ShouldBe(1); + } + } + [Fact] public void AutoServiceRegistration_Should_Not_Duplicate_Test() { diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs index d665c863dc..6a3f059ba8 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DependencyInjection/HybridServiceScopeFactory_Tests.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Modularity; @@ -8,6 +9,26 @@ namespace Volo.Abp.DependencyInjection; public class HybridServiceScopeFactory_Tests { + [Fact] + public async Task Should_Use_Default_ServiceScopeFactory_By_Default_Async() + { + using (var application = await AbpApplicationFactory.CreateAsync()) + { + application.Services.AddType(typeof(MyServiceAsync)); + + await application.InitializeAsync(); + + var serviceScopeFactory = application.ServiceProvider.GetRequiredService(); + + using (var scope = serviceScopeFactory.CreateScope()) + { + scope.ServiceProvider.GetRequiredService(); + } + + MyServiceAsync.DisposeCount.ShouldBe(1); + } + } + [Fact] public void Should_Use_Default_ServiceScopeFactory_By_Default() { @@ -28,6 +49,16 @@ public class HybridServiceScopeFactory_Tests } } + private class MyServiceAsync : ITransientDependency, IDisposable + { + public static int DisposeCount { get; private set; } + + public void Dispose() + { + ++DisposeCount; + } + } + private class MyService : ITransientDependency, IDisposable { public static int DisposeCount { get; private set; } diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs index befc9af679..f4b584701f 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/DynamicProxy/AbpInterceptionTestBase.cs @@ -7,10 +7,10 @@ using Xunit; namespace Volo.Abp.DynamicProxy; -public abstract class AbpInterceptionTestBase : AbpIntegratedTest +public abstract class AbpInterceptionTestBase : AbpAsyncIntegratedTest, IAsyncLifetime where TStartupModule : IAbpModule { - protected override void BeforeAddApplication(IServiceCollection services) + protected override Task BeforeAddApplicationAsync(IServiceCollection services) { services.AddTransient(); services.AddTransient(); @@ -32,6 +32,8 @@ public abstract class AbpInterceptionTestBase : AbpIntegratedTes registration.Interceptors.Add(); } }); + + return Task.CompletedTask; } [Fact] diff --git a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs index 327d2982a5..29b7927c64 100644 --- a/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs +++ b/framework/test/Volo.Abp.Core.Tests/Volo/Abp/Modularity/TestModuleBase.cs @@ -1,39 +1,97 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; namespace Volo.Abp.Modularity; public class TestModuleBase : AbpModule { - public bool PreConfigureServicesIsCalled { get; set; } + public bool PreConfigureServicesAsyncIsCalled { get; set; } + public bool ConfigureServicesAsyncIsCalled { get; set; } + public bool PostConfigureServicesAsyncIsCalled { get; set; } + public bool OnPreApplicationInitializationIsCalled { get; set; } + public bool OnPostApplicationInitializationIsCalled { get; set; } + public bool OnApplicationInitializeAsyncIsCalled { get; set; } + public bool OnApplicationShutdownAsyncIsCalled { get; set; } + public bool PreConfigureServicesIsCalled { get; set; } public bool ConfigureServicesIsCalled { get; set; } - public bool PostConfigureServicesIsCalled { get; set; } - + public bool OnPreApplicationInitializationAsyncIsCalled { get; set; } + public bool OnPostApplicationInitializationAsyncIsCalled { get; set; } public bool OnApplicationInitializeIsCalled { get; set; } - public bool OnApplicationShutdownIsCalled { get; set; } + public override Task PreConfigureServicesAsync(ServiceConfigurationContext context) + { + PreConfigureServicesAsyncIsCalled = true; + return base.PreConfigureServicesAsync(context); + } + public override void PreConfigureServices(ServiceConfigurationContext context) { PreConfigureServicesIsCalled = true; } + public override Task ConfigureServicesAsync(ServiceConfigurationContext context) + { + ConfigureServicesAsyncIsCalled = true; + return base.ConfigureServicesAsync(context); + } + public override void ConfigureServices(ServiceConfigurationContext context) { ConfigureServicesIsCalled = true; } + public override Task PostConfigureServicesAsync(ServiceConfigurationContext context) + { + PostConfigureServicesAsyncIsCalled = true; + return base.PostConfigureServicesAsync(context); + } + public override void PostConfigureServices(ServiceConfigurationContext context) { PostConfigureServicesIsCalled = true; } + public override Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPreApplicationInitializationAsyncIsCalled = true; + return base.OnPreApplicationInitializationAsync(context); + } + + public override void OnPreApplicationInitialization(ApplicationInitializationContext context) + { + OnPreApplicationInitializationIsCalled = true; + } + + public override Task OnPostApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnPostApplicationInitializationAsyncIsCalled = true; + return base.OnPostApplicationInitializationAsync(context); + } + + public override void OnPostApplicationInitialization(ApplicationInitializationContext context) + { + OnPostApplicationInitializationIsCalled = true; + } + + public override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + OnApplicationInitializeAsyncIsCalled = true; + return base.OnApplicationInitializationAsync(context); + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { OnApplicationInitializeIsCalled = true; } + public override Task OnApplicationShutdownAsync(ApplicationShutdownContext context) + { + OnApplicationShutdownAsyncIsCalled = true; + return base.OnApplicationShutdownAsync(context); + } + public override void OnApplicationShutdown(ApplicationShutdownContext context) { OnApplicationShutdownIsCalled = true; diff --git a/modules/cms-kit/src/Volo.CmsKit.Domain.Shared/Volo/CmsKit/Localization/Resources/zh-Hant.json b/modules/cms-kit/src/Volo.CmsKit.Domain.Shared/Volo/CmsKit/Localization/Resources/zh-Hant.json index 1d87b80110..49584e5af0 100644 --- a/modules/cms-kit/src/Volo.CmsKit.Domain.Shared/Volo/CmsKit/Localization/Resources/zh-Hant.json +++ b/modules/cms-kit/src/Volo.CmsKit.Domain.Shared/Volo/CmsKit/Localization/Resources/zh-Hant.json @@ -1,7 +1,7 @@ { "culture": "zh-Hant", "texts": { - "AddSubMenuItem": "添加子菜單項", + "AddSubMenuItem": "添加子選單項目", "AreYouSure": "你確定嗎?", "BlogDeletionConfirmationMessage": "部落格 '{0}' 將被刪除. 你確定嗎?", "BlogFeatureNotAvailable": "目前此功能不可使用. 請用 `GlobalFeatureManager` 來啟用它.", @@ -47,15 +47,15 @@ "ExportCSV": "匯出 CSV", "Features": "功能", "GenericDeletionConfirmationMessage": "你確定刪除 '{0}' 嗎?", - "IsActive": "積極的", + "IsActive": "是否啟用", "LastModification": "最後一次修改", "LastModificationTime": "最後修改時間", "LoginToAddComment": "登錄後添加評論", "LoginToRate": "登錄後進行評分", "LoginToReact": "登錄以作出反應", "LoginToReply": "登錄後進行回覆", - "MainMenu": "主菜單", - "MakeMainMenu": "製作主菜單", + "MainMenu": "主選單", + "MakeMainMenu": "製作主選單", "Menu:CMS": "CMS", "Menus": "菜單", "MenuDeletionConfirmationMessage": "菜單“{0}”將被刪除。你確定嗎?", @@ -64,10 +64,10 @@ "MenuItems": "菜單項", "Message": "消息", "MessageDeletionConfirmationMessage": "這條評論將被完全刪除", - "NewBlog": "新博客", - "NewBlogPost": "新博文", - "NewMenu": "新菜單", - "NewMenuItem": "新的根菜單項", + "NewBlog": "新部落格", + "NewBlogPost": "新部落格貼文", + "NewMenu": "新選單", + "NewMenuItem": "新的根選單", "NewPage": "新的一頁", "NewTag": "新標籤", "NoMenuItems": "還沒有菜單項!", @@ -104,9 +104,9 @@ "Permission:MenuManagement.Delete": "刪除", "Permission:MenuManagement.Update": "更新", "Permission:Menus": "Menu Management", - "Permission:Menus.Create": "Create", - "Permission:Menus.Delete": "Delete", - "Permission:Menus.Update": "Update", + "Permission:Menus.Create": "創建", + "Permission:Menus.Delete": "刪除", + "Permission:Menus.Update": "更新", "Permission:PageManagement": "頁面管理", "Permission:PageManagement:Create": "創建", "Permission:PageManagement:Delete": "刪除", @@ -150,7 +150,7 @@ "Update": "更新", "UpdatePreferenceSuccessMessage": "您的 preferences 已經保存", "UpdateYourEmailPreferences": "更新你的郵件preferences", - "UnMakeMainMenu": "取消主菜單", + "UnMakeMainMenu": "取消主選單", "UploadFailedMessage": "上傳失敗", "UserId": "用戶Id", "Username": "用戶名稱", @@ -158,6 +158,7 @@ "YourEmailAddress": "你的郵件地址", "YourFullName": "你的全名", "YourMessage": "你的消息", - "YourReply": "你的回覆" + "YourReply": "你的回覆", + "MarkdownSupported": "支援 Markdown ." } -} \ No newline at end of file +} diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs index ecc52d1f26..d6c7a3a0a6 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp; @@ -39,7 +40,7 @@ namespace Volo.Docs options.EtoMappings.Add(typeof(DocsDomainModule)); options.EtoMappings.Add(typeof(DocsDomainModule)); }); - + Configure(options => { options.FileSets @@ -65,6 +66,18 @@ namespace Volo.Docs }); } + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) + { + using (var scope = context.ServiceProvider.CreateScope()) + { + if (scope.ServiceProvider.GetRequiredService>().Value.Enable) + { + var documentFullSearch = scope.ServiceProvider.GetRequiredService(); + await documentFullSearch.CreateIndexIfNeededAsync(); + } + } + } + public override void OnApplicationInitialization(ApplicationInitializationContext context) { using (var scope = context.ServiceProvider.CreateScope()) diff --git a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpClaimsService.cs b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpClaimsService.cs index 57ee725046..c3caa48971 100644 --- a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpClaimsService.cs +++ b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpClaimsService.cs @@ -5,6 +5,7 @@ using IdentityModel; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; using Volo.Abp.Security.Claims; namespace Volo.Abp.IdentityServer; @@ -20,6 +21,7 @@ public class AbpClaimsService : DefaultClaimsService AbpClaimTypes.ImpersonatorUserId, AbpClaimTypes.Name, AbpClaimTypes.SurName, + JwtRegisteredClaimNames.UniqueName, JwtClaimTypes.PreferredUserName, JwtClaimTypes.GivenName, JwtClaimTypes.FamilyName, diff --git a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs index d3663277cb..1f8fb93e4b 100644 --- a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs +++ b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AbpIdentityServerDomainModule.cs @@ -1,4 +1,5 @@ -using IdentityServer4.Services; +using System.Threading.Tasks; +using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -133,17 +134,31 @@ public class AbpIdentityServerDomainModule : AbpModule }); } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var options = context.ServiceProvider.GetRequiredService>().Value; if (options.IsCleanupEnabled) { - context.ServiceProvider + await context.ServiceProvider .GetRequiredService() - .Add( + .AddAsync( context.ServiceProvider .GetRequiredService() ); } } + + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + var options = context.ServiceProvider.GetRequiredService>().Value; + if (options.IsCleanupEnabled) + { + AsyncHelper.RunSync(() => context.ServiceProvider + .GetRequiredService() + .AddAsync( + context.ServiceProvider + .GetRequiredService() + )); + } + } } diff --git a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpUserClaimsFactory.cs b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpUserClaimsFactory.cs index fd62e61c3e..18ba6cbe2b 100644 --- a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpUserClaimsFactory.cs +++ b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpUserClaimsFactory.cs @@ -1,10 +1,11 @@ -using System; +using System; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using IdentityModel; using Microsoft.AspNetCore.Identity; +using Microsoft.IdentityModel.JsonWebTokens; using Volo.Abp.DependencyInjection; using IdentityUser = Volo.Abp.Identity.IdentityUser; @@ -41,6 +42,10 @@ public class AbpUserClaimsFactory : IUserClaimsPrincipalFactory { identity.RemoveClaim(usernameClaim); identity.AddIfNotContains(new Claim(JwtClaimTypes.PreferredUserName, username)); + + //https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1627 + //https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/05e02b5e0383be40e45c667c12f6667d38e33fcc/src/System.IdentityModel.Tokens.Jwt/ClaimTypeMapping.cs#L52 + identity.AddIfNotContains(new Claim(JwtRegisteredClaimNames.UniqueName, username)); } if (!identity.HasClaim(x => x.Type == JwtClaimTypes.Name)) diff --git a/modules/setting-management/test/Volo.Abp.SettingManagement.Tests/Volo/Abp/SettingManagement/SettingManager_Basic_Tests.cs b/modules/setting-management/test/Volo.Abp.SettingManagement.Tests/Volo/Abp/SettingManagement/SettingManager_Basic_Tests.cs index 1442126fe6..44655c8cb0 100644 --- a/modules/setting-management/test/Volo.Abp.SettingManagement.Tests/Volo/Abp/SettingManagement/SettingManager_Basic_Tests.cs +++ b/modules/setting-management/test/Volo.Abp.SettingManagement.Tests/Volo/Abp/SettingManagement/SettingManager_Basic_Tests.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Shouldly; using Volo.Abp.Settings; using Xunit; @@ -46,6 +46,15 @@ public class SettingManager_Basic_Tests : SettingsTestBase settingValues.ShouldContain(sv => sv.Name == "SettingNotSetInStore" && sv.Value == "default-value"); } + [Fact] + public async Task Should_Get_All_By_Names_Base_Store_Values() + { + var settingValues = await _settingProvider.GetAllAsync(new []{ "MySetting1", "MySetting2" }); + settingValues.Count.ShouldBe(2); + settingValues.ShouldContain(sv => sv.Name == "MySetting1" && sv.Value == "42"); + settingValues.ShouldContain(sv => sv.Name == "MySetting2" && sv.Value == "default-store-value"); + } + [Fact] public async Task Should_Set_Global_Value() { @@ -54,4 +63,4 @@ public class SettingManager_Basic_Tests : SettingsTestBase (await _settingManager.GetOrNullGlobalAsync("MySetting1")).ShouldBe("43"); (await _settingProvider.GetOrNullAsync("MySetting1")).ShouldBe("43"); } -} +} \ No newline at end of file diff --git a/nupkg/common.ps1 b/nupkg/common.ps1 index e173a913c2..fbcbae15dd 100644 --- a/nupkg/common.ps1 +++ b/nupkg/common.ps1 @@ -136,7 +136,7 @@ $projects = ( "framework/src/Volo.Abp.EntityFrameworkCore", "framework/src/Volo.Abp.EntityFrameworkCore.MySQL", "framework/src/Volo.Abp.EntityFrameworkCore.Oracle", - # "framework/src/Volo.Abp.EntityFrameworkCore.Oracle.Devart", + "framework/src/Volo.Abp.EntityFrameworkCore.Oracle.Devart", "framework/src/Volo.Abp.EntityFrameworkCore.PostgreSql", "framework/src/Volo.Abp.EntityFrameworkCore.Sqlite", "framework/src/Volo.Abp.EntityFrameworkCore.SqlServer", diff --git a/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/CsprojFileManager.cs b/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/CsprojFileManager.cs index fb7ace820e..c37321decf 100644 --- a/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/CsprojFileManager.cs +++ b/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/CsprojFileManager.cs @@ -74,6 +74,24 @@ public class CsprojFileManager : XmlFileManagerBase, ICsprojFileManager, ITransi await SaveXmlDocumentAsync(filePath, document); } + public async Task AddImportAsync(string filePath, string importFilePath) + { + var document = await GetXmlDocumentAsync(filePath); + + var relativeImportFilePath = PathHelper.GetRelativePath(filePath, importFilePath); + + var importNode = document.CreateElement("Import"); + + var projectAttr = document.CreateAttribute("Project"); + projectAttr.Value = relativeImportFilePath; + importNode.Attributes.Append(projectAttr); + + document["Project"].AppendChild(importNode); + document["Project"].AppendChild(document.CreateWhitespace(Environment.NewLine + " ")); + + await SaveXmlDocumentAsync(filePath, document); + } + public async Task ConvertPackageReferenceToProjectReferenceAsync(string filePath, string projectToReference) { var document = await GetXmlDocumentAsync(filePath); diff --git a/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/ICsprojFileManager.cs b/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/ICsprojFileManager.cs index 1fe903e78c..287debad65 100644 --- a/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/ICsprojFileManager.cs +++ b/studio/src/Volo.Abp.Studio.Domain.CommonServices/Volo/Abp/Studio/Modifying/ICsprojFileManager.cs @@ -10,8 +10,11 @@ public interface ICsprojFileManager Task AddPackageReferenceAsync(string filePath, string packageName, string version); + Task AddImportAsync(string filePath, string importFilePath); + Task ConvertPackageReferenceToProjectReferenceAsync(string filePath, string projectToReference); + Task GetTargetFrameworkAsync(string filePath); Task> GetDependencyListAsync(string filePath); diff --git a/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/ModuleInstallingPipelineBuilderBase.cs b/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/ModuleInstallingPipelineBuilderBase.cs index e03a67f428..5b3f953e1a 100644 --- a/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/ModuleInstallingPipelineBuilderBase.cs +++ b/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/ModuleInstallingPipelineBuilderBase.cs @@ -12,6 +12,7 @@ public abstract class ModuleInstallingPipelineBuilderBase if (context.WithSourceCode) { pipeline.Add(new SourceCodeDownloadStep()); + pipeline.Add(new CommonPropsStep()); if (context.AddToSolutionFile) { diff --git a/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/Steps/CommonPropsStep.cs b/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/Steps/CommonPropsStep.cs new file mode 100644 index 0000000000..519cc31c06 --- /dev/null +++ b/studio/src/Volo.Abp.Studio.ModuleInstaller/Volo/Abp/Studio/ModuleInstalling/Steps/CommonPropsStep.cs @@ -0,0 +1,29 @@ +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Studio.Packages.Modifying; + +namespace Volo.Abp.Studio.ModuleInstalling.Steps; + +public class CommonPropsStep : ModuleInstallingPipelineStep +{ + public async override Task ExecuteAsync(ModuleInstallingContext context) + { + var moduleFolder = Path.GetDirectoryName(context.TargetModule); + var commonPropsFilePath = Path.Combine(moduleFolder, "common.props"); + + if (!File.Exists(commonPropsFilePath)) + { + return; + } + + var _csprojFileManager = context.ServiceProvider.GetRequiredService(); + + var csProjFiles = Directory.GetFiles(context.GetTargetSourceCodeFolder(), "*.csproj", SearchOption.AllDirectories); + + foreach (var csProjFile in csProjFiles) + { + await _csprojFileManager.AddImportAsync(csProjFile, commonPropsFilePath); + } + } +} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs index c783074558..d028aeafad 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName.Blazor.Server.Tiered; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs deleted file mode 100644 index d3aed6dfd0..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server.Tiered/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Blazor.Server.Tiered; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs index d414fd7b78..8cffe96c42 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName.Blazor.Server; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs deleted file mode 100644 index 1aae1bb1d3..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor.Server/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Blazor.Server; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs index 1ded753836..027cac3dcf 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Blazor/Program.cs @@ -5,11 +5,11 @@ namespace MyCompanyName.MyProjectName.Blazor; public class Program { - public static async Task Main(string[] args) + public async static Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); - var application = builder.AddApplication(options => + var application = await builder.AddApplicationAsync(options => { options.UseAutofac(); }); diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator/DbMigratorHostedService.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator/DbMigratorHostedService.cs index ca084c1833..0b31a64ddd 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator/DbMigratorHostedService.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator/DbMigratorHostedService.cs @@ -22,25 +22,28 @@ public class DbMigratorHostedService : IHostedService public async Task StartAsync(CancellationToken cancellationToken) { - using (var application = AbpApplicationFactory.Create(options => + using (var application = await AbpApplicationFactory.CreateAsync(options => { - options.Services.ReplaceConfiguration(_configuration); - options.UseAutofac(); - options.Services.AddLogging(c => c.AddSerilog()); + options.Services.ReplaceConfiguration(_configuration); + options.UseAutofac(); + options.Services.AddLogging(c => c.AddSerilog()); })) { - application.Initialize(); + await application.InitializeAsync(); await application .ServiceProvider .GetRequiredService() .MigrateAsync(); - application.Shutdown(); + await application.ShutdownAsync(); _hostApplicationLifetime.StopApplication(); } } - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs index fbbae26ddd..b3bb9299ba 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting MyCompanyName.MyProjectName.HttpApi.Host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs deleted file mode 100644 index 05e84529fc..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs index fbbae26ddd..b3bb9299ba 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting MyCompanyName.MyProjectName.HttpApi.Host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs deleted file mode 100644 index 05e84529fc..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs index c1592d400c..2699dc2993 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting MyCompanyName.MyProjectName.IdentityServer."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs deleted file mode 100644 index 50f174aa59..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.IdentityServer/Startup.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs index fa6764a4fd..8c345c70a2 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName.Web; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs deleted file mode 100644 index 8175f31cb7..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web.Host/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName.Web; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs index fa6764a4fd..8c345c70a2 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName.Web; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs deleted file mode 100644 index 4500cd8c22..0000000000 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/Startup.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Web; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app) - { - app.InitializeApplication(); - } -} diff --git a/templates/app/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs b/templates/app/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs index 53eab979d4..b756d400f8 100644 --- a/templates/app/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs +++ b/templates/app/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs @@ -18,20 +18,23 @@ public class ConsoleTestAppHostedService : IHostedService public async Task StartAsync(CancellationToken cancellationToken) { - using (var application = AbpApplicationFactory.Create(options => + using (var application = await AbpApplicationFactory.CreateAsync(options => { - options.Services.ReplaceConfiguration(_configuration); - options.UseAutofac(); + options.Services.ReplaceConfiguration(_configuration); + options.UseAutofac(); })) { - application.Initialize(); + await application.InitializeAsync(); var demo = application.ServiceProvider.GetRequiredService(); await demo.RunAsync(); - application.Shutdown(); + await application.ShutdownAsync(); } } - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs b/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs index 7ddd618c3e..7c095b85ed 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/HelloWorldService.cs @@ -1,12 +1,22 @@ -using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Volo.Abp.DependencyInjection; namespace MyCompanyName.MyProjectName; public class HelloWorldService : ITransientDependency { - public void SayHello() + public ILogger Logger { get; set; } + + public HelloWorldService() + { + Logger = NullLogger.Instance; + } + + public Task SayHelloAsync() { - Console.WriteLine("\tHello World!"); + Logger.LogInformation("Hello World!"); + return Task.CompletedTask; } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj b/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj index 2ea0513d71..a2041bf970 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj +++ b/templates/console/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj @@ -14,6 +14,7 @@ + diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs index 822844e10e..756d56571e 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameHostedService.cs @@ -1,40 +1,46 @@ -using System; -using System.Threading; +using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Serilog; using Volo.Abp; namespace MyCompanyName.MyProjectName; public class MyProjectNameHostedService : IHostedService { - private readonly IAbpApplicationWithExternalServiceProvider _application; - private readonly IServiceProvider _serviceProvider; - private readonly HelloWorldService _helloWorldService; - - public MyProjectNameHostedService( - IAbpApplicationWithExternalServiceProvider application, - IServiceProvider serviceProvider, - HelloWorldService helloWorldService) + private IAbpApplicationWithInternalServiceProvider _abpApplication; + + private readonly IConfiguration _configuration; + private readonly IHostEnvironment _hostEnvironment; + + public MyProjectNameHostedService(IConfiguration configuration, IHostEnvironment hostEnvironment) { - _application = application; - _serviceProvider = serviceProvider; - _helloWorldService = helloWorldService; + _configuration = configuration; + _hostEnvironment = hostEnvironment; } - public Task StartAsync(CancellationToken cancellationToken) + public async Task StartAsync(CancellationToken cancellationToken) { - _application.Initialize(_serviceProvider); + _abpApplication = await AbpApplicationFactory.CreateAsync(options => + { + options.Services.ReplaceConfiguration(_configuration); + options.Services.AddSingleton(_hostEnvironment); + + options.UseAutofac(); + options.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); + }); - _helloWorldService.SayHello(); + await _abpApplication.InitializeAsync(); - return Task.CompletedTask; + var helloWorldService = _abpApplication.ServiceProvider.GetRequiredService(); + + await helloWorldService.SayHelloAsync(); } - public Task StopAsync(CancellationToken cancellationToken) + public async Task StopAsync(CancellationToken cancellationToken) { - _application.Shutdown(); - - return Task.CompletedTask; + await _abpApplication.ShutdownAsync(); } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs index 15ff448d74..c7045a62ea 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/MyProjectNameModule.cs @@ -1,5 +1,9 @@ -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Volo.Abp; using Volo.Abp.Autofac; using Volo.Abp.Modularity; @@ -10,11 +14,15 @@ namespace MyCompanyName.MyProjectName; )] public class MyProjectNameModule : AbpModule { - public override void ConfigureServices(ServiceConfigurationContext context) + public override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { - var configuration = context.Services.GetConfiguration(); - var hostEnvironment = context.Services.GetSingletonInstance(); + var logger = context.ServiceProvider.GetRequiredService>(); + var configuration = context.ServiceProvider.GetRequiredService(); + logger.LogInformation($"MySettingName => {configuration["MySettingName"]}"); - context.Services.AddHostedService(); + var hostEnvironment = context.ServiceProvider.GetRequiredService(); + logger.LogInformation($"EnvironmentName => {hostEnvironment.EnvironmentName}"); + + return Task.CompletedTask; } } diff --git a/templates/console/src/MyCompanyName.MyProjectName/Program.cs b/templates/console/src/MyCompanyName.MyProjectName/Program.cs index 1ec4de497c..c6317e635d 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/Program.cs +++ b/templates/console/src/MyCompanyName.MyProjectName/Program.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; @@ -10,7 +9,7 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static async Task Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG @@ -27,7 +26,14 @@ public class Program try { Log.Information("Starting console host."); - await CreateHostBuilder(args).RunConsoleAsync(); + + await Host.CreateDefaultBuilder(args) + .ConfigureServices(services => + { + services.AddHostedService(); + }) + .RunConsoleAsync(); + return 0; } catch (Exception ex) @@ -39,19 +45,5 @@ public class Program { Log.CloseAndFlush(); } - } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .UseAutofac() - .UseSerilog() - .ConfigureAppConfiguration((context, config) => - { - //setup your additional configuration sources - }) - .ConfigureServices((hostContext, services) => - { - services.AddApplication(); - }); } diff --git a/templates/console/src/MyCompanyName.MyProjectName/appsettings.json b/templates/console/src/MyCompanyName.MyProjectName/appsettings.json index 0db3279e44..1bc4c59014 100644 --- a/templates/console/src/MyCompanyName.MyProjectName/appsettings.json +++ b/templates/console/src/MyCompanyName.MyProjectName/appsettings.json @@ -1,3 +1,3 @@ { - + "MySettingName": "MySettingValue" } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs index d5b3c36ff5..d0e58677bd 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Host/Program.cs @@ -5,11 +5,11 @@ namespace MyCompanyName.MyProjectName.Blazor.Host; public class Program { - public static async Task Main(string[] args) + public async static Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); - var application = builder.AddApplication(options => + var application = await builder.AddApplicationAsync(options => { options.UseAutofac(); }); diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs index 951a9e69bc..fdb57b3435 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/MyProjectNameBlazorHostModule.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Net.Http; +using System.Threading.Tasks; using Blazorise.Bootstrap5; using Blazorise.Icons.FontAwesome; using Microsoft.AspNetCore.Builder; @@ -211,7 +212,7 @@ public class MyProjectNameBlazorHostModule : AbpModule #endif } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var env = context.GetEnvironment(); var app = context.GetApplicationBuilder(); @@ -252,12 +253,9 @@ public class MyProjectNameBlazorHostModule : AbpModule using (var scope = context.ServiceProvider.CreateScope()) { - AsyncHelper.RunSync(async () => - { - await scope.ServiceProvider - .GetRequiredService() - .SeedAsync(); - }); + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); } } } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs index 1301cbfb3e..cff77845f1 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Program.cs @@ -1,6 +1,7 @@ using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -9,27 +10,34 @@ namespace MyCompanyName.MyProjectName.Blazor.Server.Host; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,15 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs deleted file mode 100644 index d356f6bede..0000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace MyCompanyName.MyProjectName.Blazor.Server.Host; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs index 500a2cfc00..a315163da3 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Program.cs @@ -1,7 +1,7 @@ using System; -using System.IO; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,26 +10,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs deleted file mode 100644 index 200da6e542..0000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.HttpApi.Host/Startup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs index b6fc071e14..eb854d3bc1 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/MyProjectNameIdentityServerModule.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.DataProtection; @@ -187,7 +188,7 @@ public class MyProjectNameIdentityServerModule : AbpModule #endif } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); @@ -227,19 +228,16 @@ public class MyProjectNameIdentityServerModule : AbpModule app.UseAbpSerilogEnrichers(); app.UseConfiguredEndpoints(); - SeedData(context); + await SeedData(context); } - private void SeedData(ApplicationInitializationContext context) + private async Task SeedData(ApplicationInitializationContext context) { - AsyncHelper.RunSync(async () => + using (var scope = context.ServiceProvider.CreateScope()) { - using (var scope = context.ServiceProvider.CreateScope()) - { - await scope.ServiceProvider - .GetRequiredService() - .SeedAsync(); - } - }); + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); + } } } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs index 500a2cfc00..540e2312e2 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Program.cs @@ -1,7 +1,7 @@ using System; -using System.IO; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,26 +10,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +50,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs deleted file mode 100644 index 70990fa4da..0000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.IdentityServer/Startup.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs index 500a2cfc00..2d54ded331 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Program.cs @@ -1,7 +1,10 @@ using System; using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,26 +13,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -42,14 +53,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs deleted file mode 100644 index 265fb2e7d7..0000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Host/Startup.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs index ed4f5d13e9..49b63a407d 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/MyProjectNameWebUnifiedModule.cs @@ -1,5 +1,6 @@ using System.IO; using System.Reflection; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -140,7 +141,7 @@ public class MyProjectNameWebUnifiedModule : AbpModule #endif } - public override void OnApplicationInitialization(ApplicationInitializationContext context) + public async override Task OnApplicationInitializationAsync(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); @@ -180,12 +181,9 @@ public class MyProjectNameWebUnifiedModule : AbpModule using (var scope = context.ServiceProvider.CreateScope()) { - AsyncHelper.RunSync(async () => - { - await scope.ServiceProvider - .GetRequiredService() - .SeedAsync(); - }); + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); } } } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs index 6b523328cc..f8d7f828c5 100644 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs +++ b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Program.cs @@ -1,7 +1,10 @@ using System; using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -10,22 +13,34 @@ namespace MyCompanyName.MyProjectName; public class Program { - public static int Main(string[] args) + public async static Task Main(string[] args) { Log.Logger = new LoggerConfiguration() +#if DEBUG .MinimumLevel.Debug() +#else + .MinimumLevel.Information() +#endif .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) #if DEBUG - .WriteTo.Async(c => c.Console()) + .WriteTo.Async(c => c.Console()) #endif - .CreateLogger(); + .CreateLogger(); try { Log.Information("Starting web host."); - CreateHostBuilder(args).Build().Run(); + var builder = WebApplication.CreateBuilder(args); + builder.Host.AddAppSettingsSecretsJson() + .UseAutofac() + .UseSerilog(); + await builder.AddApplicationAsync(); + var app = builder.Build(); + await app.InitializeApplicationAsync(); + await app.RunAsync(); return 0; } catch (Exception ex) @@ -38,14 +53,4 @@ public class Program Log.CloseAndFlush(); } } - - internal static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .AddAppSettingsSecretsJson() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }) - .UseAutofac() - .UseSerilog(); } diff --git a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs b/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs deleted file mode 100644 index 2be66923ce..0000000000 --- a/templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Web.Unified/Startup.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace MyCompanyName.MyProjectName; - -public class Startup -{ - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } -} diff --git a/templates/module/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs b/templates/module/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs index 404248dda8..64b17070d6 100644 --- a/templates/module/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs +++ b/templates/module/aspnet-core/test/MyCompanyName.MyProjectName.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs @@ -18,20 +18,23 @@ public class ConsoleTestAppHostedService : IHostedService public async Task StartAsync(CancellationToken cancellationToken) { - using (var application = AbpApplicationFactory.Create(options => + using (var application = await AbpApplicationFactory.CreateAsync(options => { - options.Services.ReplaceConfiguration(_configuration); - options.UseAutofac(); + options.Services.ReplaceConfiguration(_configuration); + options.UseAutofac(); })) { - application.Initialize(); + await application.InitializeAsync(); var demo = application.ServiceProvider.GetRequiredService(); await demo.RunAsync(); - application.Shutdown(); + await application.ShutdownAsync(); } } - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } } diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs b/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs index ab80f115c1..21124d6400 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs +++ b/templates/wpf/src/MyCompanyName.MyProjectName/App.xaml.cs @@ -1,7 +1,6 @@ using System; using System.Windows; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; using Volo.Abp; @@ -13,35 +12,34 @@ namespace MyCompanyName.MyProjectName; /// public partial class App : Application { - private readonly IHost _host; - private readonly IAbpApplicationWithExternalServiceProvider _application; + private IAbpApplicationWithInternalServiceProvider _abpApplication; - public App() + protected async override void OnStartup(StartupEventArgs e) { Log.Logger = new LoggerConfiguration() #if DEBUG - .MinimumLevel.Debug() + .MinimumLevel.Debug() #else - .MinimumLevel.Information() + .MinimumLevel.Information() #endif - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.txt")) .CreateLogger(); - _host = CreateHostBuilder(); - _application = _host.Services.GetService(); - } - - protected override async void OnStartup(StartupEventArgs e) - { try { Log.Information("Starting WPF host."); - await _host.StartAsync(); - Initialize(_host.Services); - _host.Services.GetService()?.Show(); + _abpApplication = await AbpApplicationFactory.CreateAsync(options => + { + options.UseAutofac(); + options.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); + }); + + await _abpApplication.InitializeAsync(); + + _abpApplication.Services.GetRequiredService()?.Show(); } catch (Exception ex) @@ -50,28 +48,9 @@ public partial class App : Application } } - protected override async void OnExit(ExitEventArgs e) + protected async override void OnExit(ExitEventArgs e) { - _application.Shutdown(); - await _host.StopAsync(); - _host.Dispose(); + await _abpApplication.ShutdownAsync(); Log.CloseAndFlush(); } - - private void Initialize(IServiceProvider serviceProvider) - { - _application.Initialize(serviceProvider); - } - - private IHost CreateHostBuilder() - { - return Host - .CreateDefaultBuilder(null) - .UseAutofac() - .UseSerilog() - .ConfigureServices((hostContext, services) => - { - services.AddApplication(); - }).Build(); - } } diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs b/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs index 35127360b8..2c88a265e0 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs +++ b/templates/wpf/src/MyCompanyName.MyProjectName/HelloWorldService.cs @@ -1,11 +1,20 @@ -using Volo.Abp.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Volo.Abp.DependencyInjection; namespace MyCompanyName.MyProjectName; public class HelloWorldService : ITransientDependency { + public ILogger Logger { get; set; } + + public HelloWorldService() + { + Logger = NullLogger.Instance; + } public string SayHello() { - return "\tHello world!"; + Logger.LogInformation("Call SayHello"); + return "Hello world!"; } } diff --git a/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj b/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj index afb8fcfb4c..6b5352c3e7 100644 --- a/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj +++ b/templates/wpf/src/MyCompanyName.MyProjectName/MyCompanyName.MyProjectName.csproj @@ -15,6 +15,7 @@ + diff --git a/test/DistEvents/DistDemoApp.Shared/DistDemoApp.Shared.csproj b/test/DistEvents/DistDemoApp.Shared/DistDemoApp.Shared.csproj index 4f5cb8ad84..f43d82dd19 100644 --- a/test/DistEvents/DistDemoApp.Shared/DistDemoApp.Shared.csproj +++ b/test/DistEvents/DistDemoApp.Shared/DistDemoApp.Shared.csproj @@ -17,7 +17,7 @@ - + diff --git a/test/DistEvents/DistDemoApp.Shared/DistDemoAppSharedModule.cs b/test/DistEvents/DistDemoApp.Shared/DistDemoAppSharedModule.cs index 138b64f567..936264e828 100644 --- a/test/DistEvents/DistDemoApp.Shared/DistDemoAppSharedModule.cs +++ b/test/DistEvents/DistDemoApp.Shared/DistDemoAppSharedModule.cs @@ -5,7 +5,7 @@ using StackExchange.Redis; using Volo.Abp.Autofac; using Volo.Abp.Domain; using Volo.Abp.Domain.Entities.Events.Distributed; -using Volo.Abp.EventBus.Boxes; +using Volo.Abp.EventBus; using Volo.Abp.Modularity; namespace DistDemoApp @@ -13,8 +13,8 @@ namespace DistDemoApp [DependsOn( typeof(AbpAutofacModule), typeof(AbpDddDomainModule), - typeof(AbpEventBusBoxesModule) - )] + typeof(AbpEventBusModule) + )] public class DistDemoAppSharedModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) @@ -28,7 +28,7 @@ namespace DistDemoApp options.EtoMappings.Add(); options.AutoEventSelectors.Add(); }); - + context.Services.AddSingleton(sp => { var connection = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]); @@ -36,4 +36,4 @@ namespace DistDemoApp }); } } -} \ No newline at end of file +}