Browse Source

CmsKit - Conflict fix from dev

pull/7500/head
enisn 6 years ago
parent
commit
50a3543cf2
  1. 1
      .gitignore
  2. 4
      README.md
  3. 1
      abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json
  4. 9
      abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json
  5. 4
      abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/de-DE.json
  6. 3
      abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en-GB.json
  7. 5
      abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en.json
  8. 4
      abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/es.json
  9. 4
      abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/zh-Hans.json
  10. 4
      common.props
  11. 53
      docs/en/Blog-Posts/2021-01-28 v4_2_Release_Stable/POST.md
  12. 7
      docs/en/Caching.md
  13. 3
      docs/en/MongoDB.md
  14. 104
      docs/en/Startup-Templates/Module.md
  15. 2
      docs/en/Tutorials/Part-1.md
  16. 2
      docs/en/Tutorials/Part-7.md
  17. 176
      docs/en/Tutorials/Part-9.md
  18. 2
      docs/en/UI/Angular/Ellipsis-Directive.md
  19. 6
      docs/en/UI/Angular/Environment.md
  20. 248
      docs/en/UI/Angular/Modal.md
  21. 4
      docs/en/UI/Angular/Multi-Tenancy.md
  22. 146
      docs/en/UI/Angular/Router-Events.md
  23. BIN
      docs/en/UI/Angular/images/modal-result-1.jpg
  24. BIN
      docs/en/UI/Angular/images/modal-result-2.jpg
  25. 11
      docs/en/UI/AspNetCore/Data-Tables.md
  26. 12
      docs/en/docs-nav.json
  27. BIN
      docs/en/images/angular-module-dev-app-project.png
  28. BIN
      docs/en/images/angular-module-folder-structure.png
  29. 13
      docs/zh-Hans/Best-Practices/Application-Services.md
  30. 12
      docs/zh-Hans/Caching.md
  31. 2
      docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md
  32. 4
      docs/zh-Hans/Domain-Driven-Design-Implementation-Guide.md
  33. 9
      docs/zh-Hans/MongoDB.md
  34. 233
      docs/zh-Hans/PlugIn-Modules.md
  35. 1
      docs/zh-Hans/Redis-Cache.md
  36. 3
      docs/zh-Hans/docs-nav.json
  37. BIN
      docs/zh-Hans/images/simple-plug-in-dll-file.png
  38. BIN
      docs/zh-Hans/images/simple-plugin-library.png
  39. BIN
      docs/zh-Hans/images/simple-plugin-output.png
  40. BIN
      docs/zh-Hans/images/simple-razor-plug-in-dll-file.png
  41. BIN
      docs/zh-Hans/images/simple-razor-plugin.png
  42. 7
      framework/Volo.Abp.sln
  43. 14
      framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/SecondLevelNavMenuItem.razor
  44. 72
      framework/src/Volo.Abp.AspNetCore.MultiTenancy/Volo/Abp/AspNetCore/MultiTenancy/MultiTenancyMiddleware.cs
  45. 3
      framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/MvcCachedApplicationConfigurationClientHelper.cs
  46. 2
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/dom-event-handlers.js
  47. 9
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js
  48. 19
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js
  49. 2
      framework/src/Volo.Abp.AspNetCore.Mvc.UI/Volo.Abp.AspNetCore.Mvc.UI.csproj
  50. 2
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs
  51. 53
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
  52. 57
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProviderOptions.cs
  53. 25
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Content/InternalRemoteStreamContent.cs
  54. 11
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentInputFormatter.cs
  55. 13
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentOutputFormatter.cs
  56. 14
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Localization/AbpLanguagesController.cs
  57. 23
      framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/RequestLocalization/AbpRequestCultureCookieHelper.cs
  58. 6
      framework/src/Volo.Abp.AutoMapper/Volo/Abp/AutoMapper/AbpAutoMapperModule.cs
  59. 67
      framework/src/Volo.Abp.Autofac/Autofac/Extensions/DependencyInjection/ServiceCollectionExtensions.cs
  60. 6
      framework/src/Volo.Abp.BlazoriseUI/Volo.Abp.BlazoriseUI.csproj
  61. 57
      framework/src/Volo.Abp.Caching.StackExchangeRedis/Volo/Abp/Caching/StackExchangeRedis/AbpRedisCache.cs
  62. 381
      framework/src/Volo.Abp.Caching/Volo/Abp/Caching/DistributedCache.cs
  63. 22
      framework/src/Volo.Abp.Caching/Volo/Abp/Caching/ICacheSupportsMultipleItems.cs
  64. 90
      framework/src/Volo.Abp.Caching/Volo/Abp/Caching/IDistributedCache.cs
  65. 5
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs
  66. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/CliConsts.cs
  67. 25
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs
  68. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs
  69. 39
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs
  70. 58
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientFactory.cs
  71. 24
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Licensing/AbpIoApiKeyService.cs
  72. 29
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/NuGet/NuGetService.cs
  73. 103
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/AbpIoSourceCodeStore.cs
  74. 40
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Analyticses/CliAnalyticsCollect.cs
  75. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/ModuleInfo.cs
  76. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/SolutionRenameStep.cs
  77. 25
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/ModuleInfoProvider.cs
  78. 24
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/TemplateInfoProvider.cs
  79. 28
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/MyGetPackageListFinder.cs
  80. 23
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/NpmPackagesUpdater.cs
  81. 3
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/NuGetPackageTarget.cs
  82. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/ProjectFinder.cs
  83. 21
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/ProjectNugetPackageAdder.cs
  84. 59
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/SolutionModuleAdder.cs
  85. 23
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Utils/CmdHelper.cs
  86. 8
      framework/src/Volo.Abp.Core/Volo/Abp/Modularity/PlugIns/FolderPlugInSource.cs
  87. 9
      framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDataModule.cs
  88. 28
      framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDatabaseInfo.cs
  89. 58
      framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDatabaseInfoDictionary.cs
  90. 44
      framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDbConnectionOptions.cs
  91. 25
      framework/src/Volo.Abp.Data/Volo/Abp/Data/DefaultConnectionStringResolver.cs
  92. 38
      framework/src/Volo.Abp.Ddd.Domain/Microsoft/Extensions/DependencyInjection/ServiceCollectionRepositoryExtensions.cs
  93. 20
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/DependencyInjection/AbpCommonDbContextRegistrationOptions.cs
  94. 13
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/EntityHelper.cs
  95. 3
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/AbpRepositoryConventionalRegistrar.cs
  96. 17
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/IRepository.cs
  97. 2
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryRegistrarBase.cs
  98. 2
      framework/src/Volo.Abp.EntityFrameworkCore.Oracle/Volo.Abp.EntityFrameworkCore.Oracle.csproj
  99. 59
      framework/src/Volo.Abp.EntityFrameworkCore.Oracle/Volo/Abp/EntityFrameworkCore/AbpDbContextConfigurationContextOracleExtensions.cs
  100. 60
      framework/src/Volo.Abp.EntityFrameworkCore.Oracle/Volo/Abp/EntityFrameworkCore/AbpDbContextOptionsOracleExtensions.cs

1
.gitignore

@ -269,6 +269,7 @@ modules/blog/app/Volo.BlogTestApp/Logs/*.*
modules/blogging/app/Volo.BloggingTestApp/Logs/*.*
modules/blogging/app/Volo.BloggingTestApp/wwwroot/files/*.*
modules/docs/app/VoloDocs.Web/Logs/*.*
modules/setting-management/app/Volo.Abp.SettingManagement.DemoApp/Logs/*.*
templates/module/app/MyCompanyName.MyProjectName.DemoApp/Logs/*.*
templates/mvc/src/MyCompanyName.MyProjectName.Web/Logs/*.*

4
README.md

@ -105,3 +105,7 @@ ABP is a community-driven open source project. See [the contribution guide](http
## Support the ABP Framework
Love ABP Framework? **Please give a star** to this repository :star:
## ABP Commercial
See also [ABP Commercial](https://commercial.abp.io/) if you are looking for pre-built application modules, professional themes, code generation tooling and premium support for the ABP Framework.

1
abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json

@ -35,6 +35,7 @@
"NameFilter": "Name",
"CreationTime": "Creation time",
"IsPro": "Is pro",
"IsFreeToActiveLicenseOwners": "Free to license owners",
"ShowOnModuleList": "Show on module list",
"EfCoreConfigureMethodName": "Configure method name",
"IsProFilter": "Is pro",

9
abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json

@ -34,6 +34,13 @@
"JoinOurMarketingNewsletter": "Join our marketing newsletter",
"WouldLikeToReceiveMarketingMaterials": "I would like to receive marketing materials like product deals & special offers.",
"StartUsingYourLicenseNow": "Start using your license now!",
"WelcomePage": "Welcome Page"
"WelcomePage": "Welcome Page",
"UnsubscriptionExpireEmail": "Unsubscribe from license expire date reminder emails",
"UnsubscribeLicenseExpireEmailReminderMessage": "This email subscription only contains reminding your license expiration date.",
"UnsubscribeFromLicenseExpireEmails": "If you don't want to receive the emails about your license expiration date, you can unsubscribe at any time you want.",
"Unsubscribe": "Unsubscribe",
"NotOrganizationMember": "You are not member of any organization.",
"UnsubscribeLicenseExpirationEmailSuccessTitle": "Successfully unsubscribed",
"UnsubscribeLicenseExpirationEmailSuccessMessage": "You will not receive license expiration date reminder emails anymore."
}
}

4
abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/de-DE.json

@ -185,6 +185,8 @@
"SeeCliDocumentForMoreInformation": "Weitere Optionen finden Sie im <a href=\"{0}\">ABP CLI-Dokument</a> oder wählen Sie oben die Registerkarte \"Direkter Download\".",
"Optional": "Optional",
"LocalFrameworkRef": "Behalten Sie die lokale Projektreferenz für die Framework-Pakete bei.",
"SelectLanguage": "Sprache auswählen"
"SelectLanguage": "Sprache auswählen",
"LatestArticleOnCommunity": "Neuester Artikel zur ABP Community",
"Register": "Registrieren"
}
}

3
abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en-GB.json

@ -193,6 +193,7 @@
"MultipleDBOptions": "Multiple Database Providers",
"MultipleUIOptionsExplanation": "The core framework is designed as UI independent and can work with any type of UI system, while there are multiple pre-built and integrated options are provided out of the box.",
"MultipleDBOptionsExplanation": "The framework can work with any data source, while the following providers are officially developed and supported:",
"SelectLanguage": "Select language"
"SelectLanguage": "Select language",
"LatestArticleOnCommunity": "Latest Article on ABP Community"
}
}

5
abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/en.json

@ -8,6 +8,7 @@
"ProjectName": "Project name",
"ProjectType": "Project type",
"DatabaseProvider": "Database provider",
"DatabaseManagementSystem": "Database management system",
"NTier": "N-Tier",
"IncludeUserInterface": "Include user interface",
"CreateNow": "Create now",
@ -193,6 +194,8 @@
"MultipleDBOptions": "Multiple Database Providers",
"MultipleUIOptionsExplanation": "The core framework is designed as UI independent and can work with any type of UI system, while there are multiple pre-built and integrated options are provided out of the box.",
"MultipleDBOptionsExplanation": "The framework can work with any data source, while the following providers are officially developed and supported;",
"SelectLanguage": "Select language"
"SelectLanguage": "Select language",
"LatestArticleOnCommunity": "Latest Article on ABP Community",
"Register": "Register"
}
}

4
abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/es.json

@ -185,6 +185,8 @@
"SeeCliDocumentForMoreInformation": "Ver el <a href=\"{0}\">documento ABP CLI </a> para más opciones o selecciona la \"Direct Download\" pestaña de arriba.",
"Optional": "Opcional",
"LocalFrameworkRef": "Mantén la referencia al proyecto local para los paquetes del framework.",
"SelectLanguage": "Vali keel"
"SelectLanguage": "Vali keel",
"LatestArticleOnCommunity": "Último artículo sobre la comunidad ABP",
"Register": "Registrarse"
}
}

4
abp_io/AbpIoLocalization/AbpIoLocalization/Www/Localization/Resources/zh-Hans.json

@ -193,6 +193,8 @@
"MultipleDBOptions": "多个数据库提供程序",
"MultipleUIOptionsExplanation": "核心框架设计为独立与UI,可以和任何类型的UI系统一起使用. 同时提供了多个开箱即用的预构建集成选项.",
"MultipleDBOptionsExplanation": "该框架可以使用任何数据源,并且以下提供程序已得到正式开发和支持;",
"SelectLanguage": "选择语言"
"SelectLanguage": "选择语言",
"LatestArticleOnCommunity": "关于ABP社区的最新文章",
"Register": "寄存器"
}
}

4
common.props

@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Version>4.3.0</Version>
<LangVersion>latest</LangVersion>
<Version>4.3.0</Version>
<NoWarn>$(NoWarn);CS1591;CS0436</NoWarn>
<PackageIconUrl>https://abp.io/assets/abp_nupkg.png</PackageIconUrl>
<PackageProjectUrl>https://abp.io/</PackageProjectUrl>

53
docs/en/Blog-Posts/2021-01-28 v4_2_Release_Stable/POST.md

@ -0,0 +1,53 @@
# ABP.IO Platform 4.2 Final Has Been Released!
[ABP Framework](https://abp.io/) and [ABP Commercial](https://commercial.abp.io/) 4.2 versions have been released today.
## What's New With 4.2?
Since all the new features are already explained in details with the [4.2 RC Announcement Post](https://blog.abp.io/abp/ABP-IO-Platform-v4-2-RC-Has-Been-Released), I will not repeat all the details again. See the [RC Blog Post](https://blog.abp.io/abp/ABP-IO-Platform-v4-2-RC-Has-Been-Released) for all the features and enhancements.
## Creating New Solutions
You can create a new solution with the ABP Framework version 4.2 by either using the `abp new` command or using the **direct download** tab on the [get started page](https://abp.io/get-started).
> See the [getting started document](https://docs.abp.io/en/abp/latest/Getting-Started) for details.
## How to Upgrade an Existing Solution
### Install/Update the ABP CLI
First of all, install the ABP CLI or upgrade to the latest version.
If you haven't installed yet:
```bash
dotnet tool install -g Volo.Abp.Cli
```
To update an existing installation:
```bash
dotnet tool update -g Volo.Abp.Cli
```
### ABP UPDATE Command
[ABP CLI](https://docs.abp.io/en/abp/latest/CLI) provides a handy command to update all the ABP related NuGet and NPM packages in your solution with a single command:
```bash
abp update
```
Run this command in the root folder of your solution.
## Migration Guide
Check [the migration guide](https://docs.abp.io/en/abp/latest/Migration-Guides/Abp-4_2) for the applications with the version 4.x upgrading to the version 4.2.
> It is strongly recommended to check the migration guide for this version. Especially, the new `IRepository.GetQueryableAsync()` method is a core change should be considered after upgrading the solution.
## About the Next Version
The next feature version will be 4.3. It is planned to release the 4.3 RC (Release Candidate) on March 11 and the final version on March 25, 2021.
We decided to slow down the feature development for the [next milestone](https://github.com/abpframework/abp/milestone/49). We will continue to improve the existing features and introduce new ones, sure, but wanted to have more time for the planning, documentation, creating guides and improving the development experience.

7
docs/en/Caching.md

@ -242,12 +242,15 @@ In addition, all of the `IDistributedCache<TCacheItem>` (and `IDistributedCache<
## Batch Operations
ABP's distributed cache interfaces provide methods to perform batch get/set methods those improves the performance when you want to get or set multiple cache items in a single method call.
ABP's distributed cache interfaces provide methods to perform batch methods those improves the performance when you want to batch operation multiple cache items in a single method call.
* `SetManyAsync` and `SetMany` methods can be used to set multiple values to the cache.
* `GetManyAsync` and `GetMany` methods can be used to retrieve multiple values from the cache.
* `GetOrAddManyAsync` and `GetOrAddMany` methods can be used to retrieve multiple values and set missing values from the cache
* `RefreshManyAsync` and `RefreshMany` methods can be used to resets the sliding expiration timeout of multiple values from the cache
* `RemoveManyAsync` and `RemoveMany` methods can be used to remove multiple values from the cache
> These are not standard methods of the ASP.NET Core caching. So, some providers may not support them. They are supported by the [ABP Redis Cache integration package](Redis-Cache.md). If the provider doesn't support, it fallbacks to `SetAsync` and `GetAsync` methods (called once for each item).
> These are not standard methods of the ASP.NET Core caching. So, some providers may not support them. They are supported by the [ABP Redis Cache integration package](Redis-Cache.md). If the provider doesn't support, it fallbacks to `SetAsync` and `GetAsync` ... methods (called once for each item).
## Advanced Topics

3
docs/en/MongoDB.md

@ -254,7 +254,7 @@ public async override Task DeleteAsync(
### Access to the MongoDB API
In most cases, you want to hide MongoDB APIs behind a repository (this is the main purpose of the repository). However, if you want to access the MongoDB API over the repository, you can use `GetDatabaseAsync()` or `GetCollectionAsync()` extension methods. Example:
In most cases, you want to hide MongoDB APIs behind a repository (this is the main purpose of the repository). However, if you want to access the MongoDB API over the repository, you can use `GetDatabaseAsync()`, `GetCollectionAsync()` or `GetAggregateAsync()` extension methods. Example:
```csharp
public class BookService
@ -270,6 +270,7 @@ public class BookService
{
IMongoDatabase database = await _bookRepository.GetDatabaseAsync();
IMongoCollection<Book> books = await _bookRepository.GetCollectionAsync();
IAggregateFluent<Book> bookAggregate = await _bookRepository.GetAggregateAsync();
}
}
```

104
docs/en/Startup-Templates/Module.md

@ -1,4 +1,4 @@
# MVC Module Startup Template
# Module Startup Template
This template can be used to create a **reusable [application module](../Modules/Index.md)** based on the [module development best practices & conventions](../Best-Practices/Index.md). It is also suitable for creating **microservices** (with or without UI).
@ -20,6 +20,20 @@ abp new Acme.IssueManagement -t module
- `Acme.IssueManagement` is the solution name, like *YourCompany.YourProduct*. You can use single level, two-levels or three-levels naming.
### Specify the UI Framework
This template provides multiple UI frameworks:
* `mvc`: ASP.NET Core MVC UI with Razor Pages (default)
* `blazor`: Blazor UI
* `angular`: Angular UI
Use `-u` or `--ui` option to specify the UI framework:
````bash
abp new Acme.IssueManagement -t module -u angular
````
### Without User Interface
The template comes with an MVC UI by default. You can use `--no-ui` option to not include the UI layer.
@ -160,3 +174,91 @@ You should run the application with the given order:
- First, run the `.IdentityServer` since other applications depends on it.
- Then run the `.HttpApi.Host` since it is used by the `.Web.Host` application.
- Finally, you can run the `.Web.Host` project and login to the application using `admin` as the username and `1q2w3E*` as the password.
## UI
### Angular UI
If you choose `Angular` as the UI framework (using the `-u angular` option), the solution will have a folder called `angular` in it. This is where the client-side code is located. When you open that folder in an IDE, the folder structure will look like below:
![Folder structure of ABP Angular module project](../images/angular-module-folder-structure.png)
* _angular/projects/issue-management_ folder contains the Angular module project.
* _angular/projects/dev-app_ folder contains a development application that runs your module.
The server-side is similar to the solution described above. `*.HttpApi.Host` project serves the API and the `Angular` demo application consumes it. You will not need to run the `.Web.Host` project though.
#### How to Run the Angular Development App
For module development, you will need the `dev-app` project up and running. So, here is how we can start the development server.
First, we need to install dependencies:
1. Open your terminal at the root folder, i.e. `angular`.
2. Run `yarn` or `npm install`.
The dependencies will be installed and some of them are ABP modules published as NPM packages. To see all ABP packages, you can run the following command in the `angular` folder:
```bash
yarn list --pattern abp
```
> There is no equivalent of this command in npm.
The module you will develop depends on two of these ABP packages: _@abp/ng.core_ and _@abp/ng.theme.shared_. Rest of the ABP modules are included in _package.json_ because of the `dev-app` project.
Once all dependencies are installed, follow the steps below to serve your development app:
1. Make sure `.IdentityServer` and `*.HttpApi.Host` projects are up and running.
2. Open your terminal at the root folder, i.e. `angular`.
3. Run `yarn start` or `npm start`.
![ABP Angular module dev-app project](../images/angular-module-dev-app-project.png)
The issue management page is empty in the beginning. You may change the content in `IssueManagementComponent` at the _angular/projects/issue-management/src/lib/issue-management.component.ts_ path and observe that the view changes accordingly.
Now, let's have a closer look at some key elements of your project.
#### Main Module
`IssueManagementModule` at the _angular/projects/issue-management/src/lib/issue-management.module.ts_ path is the main module of your module project. There are a few things worth mentioning in it:
- Essential ABP modules, i.e. `CoreModule` and `ThemeSharedModule`, are imported.
- `IssueManagementRoutingModule` is imported.
- `IssueManagementComponent` is declared.
- It is prepared for configurability. The `forLazy` static method enables [a configuration to be passed to the module when it is loaded by the router](https://volosoft.com/blog/how-to-configure-angular-modules-loaded-by-the-router).
#### Main Routing Module
`IssueManagementRoutingModule` at the _angular/projects/issue-management/src/lib/issue-management-routing.module.ts_ path is the main routing module of your module project. It currently does two things:
- Loads `DynamicLayoutComponent` at base path it is given.
- Loads `IssueManagementComponent` as child to the layout, again at the given base path.
You can rearrange this module to load more than one component at different routes, but you need to update the route provider at _angular/projects/issue-management/config/src/providers/route.provider.ts_ to match the new routing structure with the routes in the menu. Please check [Modifying the Menu](../UI/Angular/Modifying-the-Menu.md) to see how route providers work.
#### Config Module
There is a config module at the _angular/projects/issue-management/config/src/issue-management-config.module.ts_ path. The static `forRoot` method of this module is supposed to be called at the route level. So, you may assume the following will take place:
```js
@NgModule({
imports: [
/* other imports */
IssueManagementConfigModule.forRoot(),
],
/* rest of the module meta data */
})
export class AppModule {}
```
You can use this static method to configure an application that uses your module project. An example of such configuration is already implemented and the `ISSUE_MANAGEMENT_ROUTE_PROVIDERS` token is provided here. The method can take options which enables further configuration possibilities.
The difference between the `forRoot` method of the config module and the `forLazy` method of the main module is that, for smallest bundle size, the former should only be used when you have to configure an app before your module is even loaded.
#### Testing Angular UI
Please see the [testing document](../UI/Angular/Testing.md).

2
docs/en/Tutorials/Part-1.md

@ -189,6 +189,8 @@ Add-Migration "Created_Book_Entity"
![bookstore-pmc-add-book-migration](./images/bookstore-pmc-add-book-migration-v2.png)
> If you get an error like "*Your startup project ... doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work*", right click to the `Acme.BookStore.EntityFrameworkCore.DbMigrations` project and **Set as the Startup Project** and try again.
This will create a new migration class inside the `Migrations` folder of the `Acme.BookStore.EntityFrameworkCore.DbMigrations` project.
Before updating the database, read the section below to learn how to seed some initial data to the database.

2
docs/en/Tutorials/Part-7.md

@ -70,7 +70,7 @@ This is just like done for the `Book` entity before, so no need to explain again
## Create a new Database Migration
Open the **Package Manager Console** on Visual Studio and ensure that the **Default project** is `Acme.BookStore.EntityFrameworkCore.DbMigrations` in the Package Manager Console, as shown on the picture below. Also, set the `Acme.BookStore.Web` (or `Acme.BookStore.HttpApi.Host`, depending on your solution) as the **startup project** (right click it on the solution explorer and click to "Set as Startup Project").
Open the **Package Manager Console** on Visual Studio and ensure that the **Default project** is `Acme.BookStore.EntityFrameworkCore.DbMigrations` in the Package Manager Console, as shown on the picture below. Also, set this project as the **startup project** (right click it on the solution explorer and click to "Set as Startup Project").
Run the following command to create a new database migration:

176
docs/en/Tutorials/Part-9.md

@ -843,8 +843,10 @@ Create a new Razor Component Page, `/Pages/Authors.razor`, in the `Acme.BookStor
````xml
@page "/authors"
@using Acme.BookStore.Authors
@using Acme.BookStore.Localization
@inherits BookStoreComponentBase
@inject IAuthorAppService AuthorAppService
@inject AbpBlazorMessageLocalizerHelper<BookStoreResource> LH
<Card>
<CardHeader>
<Row>
@ -917,68 +919,104 @@ Create a new Razor Component Page, `/Pages/Authors.razor`, in the `Acme.BookStor
<Modal @ref="CreateAuthorModal">
<ModalBackdrop />
<ModalContent IsCentered="true">
<ModalHeader>
<ModalTitle>@L["NewAuthor"]</ModalTitle>
<CloseButton Clicked="CloseCreateAuthorModal" />
</ModalHeader>
<ModalBody>
<Field>
<FieldLabel>@L["Name"]</FieldLabel>
<TextEdit @bind-text="@NewAuthor.Name" />
</Field>
<Field>
<FieldLabel>@L["BirthDate"]</FieldLabel>
<DateEdit TValue="DateTime" @bind-Date="@NewAuthor.BirthDate" />
</Field>
<Field>
<FieldLabel>@L["ShortBio"]</FieldLabel>
<MemoEdit Rows="5" @bind-text="@NewAuthor.ShortBio" />
</Field>
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary"
Clicked="CloseCreateAuthorModal">
@L["Cancel"]
</Button>
<Button Color="Color.Primary"
Clicked="CreateAuthorAsync">
@L["Save"]
</Button>
</ModalFooter>
<Form>
<ModalHeader>
<ModalTitle>@L["NewAuthor"]</ModalTitle>
<CloseButton Clicked="CloseCreateAuthorModal" />
</ModalHeader>
<ModalBody>
<Validations @ref="@CreateValidationsRef" Model="@NewAuthor" ValidateOnLoad="false">
<Validation MessageLocalizer="@LH.Localize">
<Field>
<FieldLabel>@L["Name"]</FieldLabel>
<TextEdit @bind-Text="@NewAuthor.Name">
<Feedback>
<ValidationError/>
</Feedback>
</TextEdit>
</Field>
</Validation>
<Field>
<FieldLabel>@L["BirthDate"]</FieldLabel>
<DateEdit TValue="DateTime" @bind-Date="@NewAuthor.BirthDate"/>
</Field>
<Validation MessageLocalizer="@LH.Localize">
<Field>
<FieldLabel>@L["ShortBio"]</FieldLabel>
<MemoEdit Rows="5" @bind-Text="@NewAuthor.ShortBio">
<Feedback>
<ValidationError/>
</Feedback>
</MemoEdit>
</Field>
</Validation>
</Validations>
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary"
Clicked="CloseCreateAuthorModal">
@L["Cancel"]
</Button>
<Button Color="Color.Primary"
Type="@ButtonType.Submit"
PreventDefaultOnSubmit="true"
Clicked="CreateAuthorAsync">
@L["Save"]
</Button>
</ModalFooter>
</Form>
</ModalContent>
</Modal>
<Modal @ref="EditAuthorModal">
<ModalBackdrop />
<ModalContent IsCentered="true">
<ModalHeader>
<ModalTitle>@EditingAuthor.Name</ModalTitle>
<CloseButton Clicked="CloseEditAuthorModal" />
</ModalHeader>
<ModalBody>
<Field>
<FieldLabel>@L["Name"]</FieldLabel>
<TextEdit @bind-text="@EditingAuthor.Name" />
</Field>
<Field>
<FieldLabel>@L["BirthDate"]</FieldLabel>
<DateEdit TValue="DateTime" @bind-Date="@EditingAuthor.BirthDate" />
</Field>
<Field>
<FieldLabel>@L["ShortBio"]</FieldLabel>
<MemoEdit Rows="5" @bind-text="@EditingAuthor.ShortBio" />
</Field>
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary"
Clicked="CloseEditAuthorModal">
@L["Cancel"]
</Button>
<Button Color="Color.Primary"
Clicked="UpdateAuthorAsync">
@L["Save"]
</Button>
</ModalFooter>
<Form>
<ModalHeader>
<ModalTitle>@EditingAuthor.Name</ModalTitle>
<CloseButton Clicked="CloseEditAuthorModal" />
</ModalHeader>
<ModalBody>
<Validations @ref="@EditValidationsRef" Model="@EditingAuthor" ValidateOnLoad="false">
<Validation MessageLocalizer="@LH.Localize">
<Field>
<FieldLabel>@L["Name"]</FieldLabel>
<TextEdit @bind-Text="@EditingAuthor.Name">
<Feedback>
<ValidationError/>
</Feedback>
</TextEdit>
</Field>
</Validation>
<Field>
<FieldLabel>@L["BirthDate"]</FieldLabel>
<DateEdit TValue="DateTime" @bind-Date="@EditingAuthor.BirthDate"/>
</Field>
<Validation>
<Field>
<FieldLabel>@L["ShortBio"]</FieldLabel>
<MemoEdit Rows="5" @bind-Text="@EditingAuthor.ShortBio">
<Feedback>
<ValidationError/>
</Feedback>
</MemoEdit>
</Field>
</Validation>
</Validations>
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary"
Clicked="CloseEditAuthorModal">
@L["Cancel"]
</Button>
<Button Color="Color.Primary"
Type="@ButtonType.Submit"
PreventDefaultOnSubmit="true"
Clicked="UpdateAuthorAsync">
@L["Save"]
</Button>
</ModalFooter>
</Form>
</ModalContent>
</Modal>
````
@ -1025,6 +1063,10 @@ namespace Acme.BookStore.Blazor.Pages
private Modal CreateAuthorModal { get; set; }
private Modal EditAuthorModal { get; set; }
private Validations CreateValidationsRef;
private Validations EditValidationsRef;
public Authors()
{
NewAuthor = new CreateAuthorDto();
@ -1079,6 +1121,8 @@ namespace Acme.BookStore.Blazor.Pages
private void OpenCreateAuthorModal()
{
CreateValidationsRef.ClearAll();
NewAuthor = new CreateAuthorDto();
CreateAuthorModal.Show();
}
@ -1090,6 +1134,8 @@ namespace Acme.BookStore.Blazor.Pages
private void OpenEditAuthorModal(AuthorDto author)
{
EditValidationsRef.ClearAll();
EditingAuthorId = author.Id;
EditingAuthor = ObjectMapper.Map<AuthorDto, UpdateAuthorDto>(author);
EditAuthorModal.Show();
@ -1114,16 +1160,22 @@ namespace Acme.BookStore.Blazor.Pages
private async Task CreateAuthorAsync()
{
await AuthorAppService.CreateAsync(NewAuthor);
await GetAuthorsAsync();
CreateAuthorModal.Hide();
if (CreateValidationsRef.ValidateAll())
{
await AuthorAppService.CreateAsync(NewAuthor);
await GetAuthorsAsync();
CreateAuthorModal.Hide();
}
}
private async Task UpdateAuthorAsync()
{
await AuthorAppService.UpdateAsync(EditingAuthorId, EditingAuthor);
await GetAuthorsAsync();
EditAuthorModal.Hide();
if (EditValidationsRef.ValidateAll())
{
await AuthorAppService.UpdateAsync(EditingAuthorId, EditingAuthor);
await GetAuthorsAsync();
EditAuthorModal.Hide();
}
}
}
}

2
docs/en/UI/Angular/Ellipsis-Directive.md

@ -1,6 +1,6 @@
# Ellipsis
Text inside an HTML element can be truncated easily with an ellipsis by using CSS. To make this even easier, you can use the `EllipsisDirective` which has been exposed from the `@abp/ng.theme.shared` package.
Text inside an HTML element can be truncated easily with an ellipsis by using CSS. To make this even easier, you can use the `EllipsisDirective` which has been exposed by the `@abp/ng.theme.shared` package.
## Getting Started

6
docs/en/UI/Angular/Environment.md

@ -138,10 +138,10 @@ You can use the `getEnvironment` or `getEnvironment$` method of `EnvironmentServ
```js
// this.environment is instance of EnvironmentService
const environment = this.environment.getAll();
const environment = this.environment.getEnvironment();
// or
this.environment.getAll$().subscribe(environment => {
this.environment.getEnvironment$().subscribe(environment => {
// use environment here
})
```
@ -166,7 +166,7 @@ This method returns the `url` of a specific API based on the key given as its on
#### How to Set the Environment
`EnvironmentService` has a method named `setState` which allow you to set the state value.
`EnvironmentService` has a method named `setState` which allows you to set the state value.
```js
// this.environment is instance of EnvironmentService

248
docs/en/UI/Angular/Modal.md

@ -0,0 +1,248 @@
# Modal
`ModalComponent` is a pre-built component exposed by `@abp/ng.theme.shared` package to show modals. The component uses the [`ng-bootstrap`](https://ng-bootstrap.github.io/)'s modal service inside to render a modal.
The `abp-modal` provides some additional benefits:
- It is **flexible**. You can pass header, body, footer templates easily by adding the templates to the `abp-modal` content. It can also be implemented quickly.
- Provides several inputs be able to customize the modal and several outputs be able to listen to some events.
- Automatically detects the close button which has a `#abpClose` template variable and closes the modal when pressed this button.
- Automatically detects the `abp-button` and triggers its loading spinner when the `busy` input value of the modal component is true.
- Automatically checks if the form inside the modal **has changed, but not saved**. It warns the user by displaying a [confirmation popup](Confirmation-Service) in this case when a user tries to close the modal or refresh/close the tab of the browser.
> Note: A modal can also be rendered by using the `ng-bootstrap` modal. For further information, see [Modal doc](https://ng-bootstrap.github.io/#/components/modal) on the `ng-bootstrap` documentation.
## Getting Started
In order to use the `abp-modal` in an HTML template, the **`ThemeSharedModule`** should be imported into your module like this:
```js
// ...
import { ThemeSharedModule } from '@abp/ng.theme.shared';
@NgModule({
//...
imports: [..., ThemeSharedModule],
})
export class MyFeatureModule {}
```
## Usage
You can add the `abp-modal` to your component very quickly. See an example:
```html
<!-- sample.component.html -->
<button class="btn btn-primary" (click)="isModalOpen = true">Open modal</button>
<abp-modal [(visible)]="isModalOpen">
<ng-template #abpHeader>
<h3>Modal Title</h3>
</ng-template>
<ng-template #abpBody>
<p>Modal content</p>
</ng-template>
<ng-template #abpFooter>
<button type="button" class="btn btn-secondary" #abpClose>Close</button>
</ng-template>
</abp-modal>
```
```js
// sample.component.ts
@Component(/* component metadata */)
export class SampleComponent {
isModelOpen = false
}
```
![Example modal result](./images/modal-result-1.jpg)
See an example form inside a modal:
```html
<!-- book.component.ts -->
<abp-modal [(visible)]="isModalOpen" [busy]="inProgress">
<ng-template #abpHeader>
<h3>Book</h3>
</ng-template>
<ng-template #abpBody>
<form id="book-form" [formGroup]="form" (ngSubmit)="save()">
<div class="form-group">
<label for="book-name">Author</label><span> * </span>
<input type="text" id="author" class="form-control" formControlName="author" autofocus />
</div>
<div class="form-group">
<label for="book-name">Name</label><span> * </span>
<input type="text" id="book-name" class="form-control" formControlName="name" />
</div>
<div class="form-group">
<label for="book-price">Price</label><span> * </span>
<input type="number" id="book-price" class="form-control" formControlName="price" />
</div>
<div class="form-group">
<label for="book-type">Type</label><span> * </span>
<select class="form-control" id="book-type" formControlName="type">
<option [ngValue]="null">Select a book type</option>
<option [ngValue]="0">Undefined</option>
<option [ngValue]="1">Adventure</option>
<option [ngValue]="2">Biography</option>
<option [ngValue]="3">Fantastic</option>
<option [ngValue]="4">Science</option>
</select>
</div>
<div class="form-group">
<label for="book-publish-date">Publish date</label><span> * </span>
<input
id="book-publish-date"
formControlName="publishDate"
class="form-control"
type="date"
/>
</div>
</form>
</ng-template>
<ng-template #abpFooter>
<button type="button" class="btn btn-secondary" #abpClose>
Cancel
</button>
<button form="book-form" class="btn btn-primary" [disabled]="form.invalid || form.pristine">
<i class="fa fa-check mr-1"></i>
Save
</button>
</ng-template>
</abp-modal>
```
```ts
// book.component.ts
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component(/* component metadata */)
export class BookComponent {
form = this.fb.group({
author: [null, [Validators.required]],
name: [null, [Validators.required]],
price: [null, [Validators.required, Validators.min(0)]],
type: [null, [Validators.required]],
publishDate: [null, [Validators.required]],
});
inProgress: boolean;
isModalOpen: boolean;
constructor(private fb: FormBuilder, private service: BookService) {}
save() {
if (this.form.invalid) return;
this.inProgress = true;
this.service.save(this.form.value).subscribe(() => {
this.inProgress = false;
});
}
}
```
The modal with form looks like this:
![Form example result](./images/modal-result-2.jpg)
## API
### Inputs
#### visible
```js
@Input() visible: boolean
```
**`visible`** is a boolean input that determines whether the modal is open. It is also can be used two-way binding.
#### busy
```js
@Input() busy: boolean
```
**`busy`** is a boolean input that determines whether the busy status of the modal is true. When `busy` is true, the modal cannot be closed and the `abp-button` loading spinner is triggered.
#### options
```js
@Input() options: NgbModalOptions
```
**`options`** is an input typed [NgbModalOptions](https://ng-bootstrap.github.io/#/components/modal/api#NgbModalOptions). It is configuration for the `ng-bootstrap` modal.
#### suppressUnsavedChangesWarning
```js
@Input() suppressUnsavedChangesWarning: boolean
```
**`suppressUnsavedChangesWarning`** is a boolean input that determines whether the confirmation popup triggering active or not. It can also be set globally as shown below:
```ts
//app.module.ts
// app.module.ts
import { SUPPRESS_UNSAVED_CHANGES_WARNING } from '@abp/ng.theme.shared';
// ...
@NgModule({
// ...
providers: [{provide: SUPPRESS_UNSAVED_CHANGES_WARNING, useValue: true}]
})
export class AppModule {}
```
Note: The `suppressUnsavedChangesWarning` input of `abp-modal` value overrides the `SUPPRESS_UNSAVED_CHANGES_WARNING` injection token value.
### Outputs
#### visibleChange
```js
@Output() readonly visibleChange = new EventEmitter<boolean>();
```
**`visibleChange`** is an event emitted when the modal visibility has changed. The event payload is a boolean.
#### appear
```js
@Output() readonly appear = new EventEmitter<void>();
```
**`appear`** is an event emitted when the modal has opened.
#### disappear
```js
@Output() readonly disappear = new EventEmitter<void>();
```
**`disappear`** is an event emitted when the modal has closed.

4
docs/en/UI/Angular/Multi-Tenancy.md

@ -91,10 +91,10 @@ export const environment = {
> **Important Note:** The `application.baseUrl` and the `{0}` placeholder in the value of the `baseUrl` property are required to be able to get tenant from running URL. Other placeholders in API URLs are optional.
After the configuration above, if your app runs on the `mytenant1.mydomain.com`, the app will get tenant name as **mytenant1** and replace the environment object in `ConfigState` on app initialization as follows:
After the configuration above, if your app runs on the `mytenant1.mydomain.com`, the app will get tenant name as **mytenant1** and replace the environment object in `EnvironmentService` on app initialization as follows:
```js
// environment object in ConfigState
// environment object in EnvironmentService
{
//...

146
docs/en/UI/Angular/Router-Events.md

@ -0,0 +1,146 @@
# Router Events Simplified
`RouterEvents` is a utility service to provide an easy implementation for one of the most frequent needs in Angular templates: `TrackByFunction`. Please see [this page in Angular docs](https://angular.io/guide/template-syntax#ngfor-with-trackby) for its purpose.
## Benefit
You can use router events directly and filter them as seen below:
```js
import {
NavigationEnd,
NavigationError,
NavigationCancel,
Router,
} from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable()
class SomeService {
navigationFinish$ = this.router.events.pipe(
filter(
event =>
event instanceof NavigationEnd ||
event instanceof NavigationError ||
event instanceof NavigationCancel,
),
);
/* Observable<Event> */
constructor(private router: Router) {}
}
```
However, `RouterEvents` makes filtering router events easier.
```js
import { RouterEvents } from '@abp/ng.core';
@Injectable()
class SomeService {
navigationFinish$ = this.routerEvents.getNavigationEvents('End', 'Error', 'Cancel');
/* Observable<NavigationCancel | NavigationEnd | NavigationError> */
constructor(private routerEvents: RouterEvents) {}
}
```
`RouterEvents` also delivers improved type-safety. In the example above, `navigationFinish$` has inferred type of `Observable<NavigationCancel | NavigationEnd | NavigationError>` whereas it would have `Observable<Event>` when router events are filtered directly.
## Usage
You do not have to provide `RouterEvents` at the module or component level, because it is already **provided in root**. You can inject and start using it immediately in your components.
### How to Get Specific Navigation Events
You can use `getNavigationEvents` to get a stream of navigation events matching given event keys.
```js
import { RouterEvents } from '@abp/ng.core';
import { merge } from 'rxjs';
import { mapTo } from 'rxjs/operators';
@Injectable()
class SomeService {
navigationStart$ = this.routerEvents.getNavigationEvents('Start');
/* Observable<NavigationStart> */
navigationFinish$ = this.routerEvents.getNavigationEvents('End', 'Error', 'Cancel');
/* Observable<NavigationCancel | NavigationEnd | NavigationError> */
loading$ = merge(
this.navigationStart$.pipe(mapTo(true)),
this.navigationFinish$.pipe(mapTo(false)),
);
/* Observable<boolean> */
constructor(private routerEvents: RouterEvents) {}
}
```
### How to Get All Navigation Events
You can use `getAllNavigationEvents` to get a stream of all navigation events without passing any keys.
```js
import { RouterEvents, NavigationStart } from '@abp/ng.core';
import { map } from 'rxjs/operators';
@Injectable()
class SomeService {
navigationEvent$ = this.routerEvents.getAllNavigationEvents();
/* Observable<NavigationCancel | NavigationEnd | NavigationError | NavigationStart> */
loading$ = this.navigationEvent$.pipe(
map(event => event instanceof NavigationStart),
);
/* Observable<boolean> */
constructor(private routerEvents: RouterEvents) {}
}
```
### How to Get Specific Router Events
You can use `getEvents` to get a stream of router events matching given event constructors.
```js
import { RouterEvents } from '@abp/ng.core';
import { ActivationEnd, ChildActivationEnd } from '@angular/router';
@Injectable()
class SomeService {
moduleActivation$ = this.routerEvents.getEvents(ActivationEnd, ChildActivationEnd);
/* Observable<ActivationEnd | ChildActivationEnd> */
constructor(private routerEvents: RouterEvents) {}
}
```
### How to Get All Router Events
You can use `getEvents` to get a stream of all router events without passing any event constructors. This is nothing different from accessing `events` property of `Router` and is added to the service just for convenience.
```js
import { RouterEvents } from '@abp/ng.core';
import { ActivationEnd, ChildActivationEnd } from '@angular/router';
@Injectable()
class SomeService {
routerEvent$ = this.routerEvents.getAllEvents();
/* Observable<Event> */
constructor(private routerEvents: RouterEvents) {}
}
```

BIN
docs/en/UI/Angular/images/modal-result-1.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
docs/en/UI/Angular/images/modal-result-2.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

11
docs/en/UI/AspNetCore/Data-Tables.md

@ -110,7 +110,7 @@ The `createAjax` also supports you to customize request parameters and handle th
**Example:**
````csharp
var inputAction = function () {
var inputAction = function (requestData, dataTableSettings) {
return {
id: $('#Id').val(),
name: $('#Name').val(),
@ -131,6 +131,15 @@ var responseCallback = function(result) {
ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList, inputAction, responseCallback)
````
If you don't need access or modify the `requestData` or the `dataTableSettings`, you can specify a simple object as the second parameter.
````js
ajax: abp.libs.datatables.createAjax(
acme.bookStore.books.book.getList,
{ id: $('#Id').val(), name: $('#Name').val() }
)
````
### Row Actions
`rowAction` is an option defined by the ABP Framework to the column definitions to show a drop down button to take actions for a row in the table.

12
docs/en/docs-nav.json

@ -807,6 +807,10 @@
"text": "Easy *ngFor trackBy",
"path": "UI/Angular/Track-By-Service.md"
},
{
"text": "Router Events",
"path": "UI/Angular/Router-Events.md"
},
{
"text": "Inserting Scripts & Styles to DOM",
"path": "UI/Angular/Dom-Insertion-Service.md"
@ -819,6 +823,10 @@
"text": "Projecting Angular Content",
"path": "UI/Angular/Content-Projection-Service.md"
},
{
"text": "Modal",
"path": "UI/Angular/Modal.md"
},
{
"text": "Confirmation Popup",
"path": "UI/Angular/Confirmation-Service.md"
@ -1060,10 +1068,6 @@
{
"text": "CLI",
"path": "CLI.md"
},
{
"text": "API Documentation",
"path": "{ApiDocumentationUrl}"
}
]
},

BIN
docs/en/images/angular-module-dev-app-project.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
docs/en/images/angular-module-folder-structure.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

13
docs/zh-Hans/Best-Practices/Application-Services.md

@ -199,7 +199,7 @@ Task<int> VoteAsync(Guid id, VoteType type);
#### 查询数据
* **不推荐** 在应用程序服务方法中使用linq/sql查询来自数据库的数据. 让仓储负责从数据源执行linq/sql查询.
* **不推荐** 在应用服务方法中使用linq/sql查询来自数据库的数据. 让仓储负责从数据源执行linq/sql查询.
#### 额外的属性
@ -210,11 +210,16 @@ Task<int> VoteAsync(Guid id, VoteType type);
* **推荐** 总是从数据库中获取所有的相关实体以对他们执行操作.
* **推荐** 更新实体后调用存储的Update/UpdateAsync方法.因为并非所有数据库API都支持更改跟踪和自动更新.
#### 处理文件
* **不推荐** 在应用服务中使用任何web组件, 例如`IFormFile`和`Stream`. 如果你想接收一个文件, 可以使用`byte[]`.
* **推荐** 使用`Controller`来处理文件上传, 然后将文件的`byte[]`传递给应用服务的方法。
#### 使用其他应用服务
* **不推荐** 使用相同 **模块/应用程序** 的其他应用服务. 相反;
* **不推荐** 在同一个模块/应用中使用其他应用服务. 相反;
* 使用领域层执行所需的任务.
* 提取新类并在应用程序服务之间共享, 在必要时代码重用. 但要小心不要结合两个用例. 它们在开始时可能看起来相似, 但可能会随时间演变为不同的方向. 请谨慎使用代码共享.
* 提取新类并在应用服务之间共享, 在必要时代码重用. 但要小心不要结合两个用例. 它们在开始时可能看起来相似, 但可能会随时间演变为不同的方向. 请谨慎使用代码共享.
* **可以** 在以下情况下使用其他应用服务;
* 它们是另一个模块/微服务的一部分.
* 当前模块仅引用已使用模块的application contracts.
* 当前模块仅引用已使用模块的application contracts.

12
docs/zh-Hans/Caching.md

@ -192,6 +192,18 @@ public class BookService : ITransientDependency
}
````
## 批量操作
ABP的分布式缓存接口定义了以下批量操作方法,当你需要在一个方法中调用多次缓存操作时,这些方法可以提高性能
* `SetManyAsync` 和 `SetMany` 方法可以用来设置多个值.
* `GetManyAsync` 和 `GetMany` 方法可以用来从缓存中获取多个值.
* `GetOrAddManyAsync` 和 `GetOrAddMany` 方法可以用来从缓存中获取并添加缺少的值.
* `RefreshManyAsync` 和 `RefreshMany` 方法可以来用重置多个值的滚动过期时间.
* `RemoveManyAsync` 和 `RemoveMany` 方法呆以用来删除多个值.
> 这些不是标准的ASP.NET Core缓存方法, 所以某些提供程序可能不支持. [ABP Redis集成包](Redis-Cache.md)实现了它们. 如果提供程序不支持,会回退到 `SetAsync` 和 `GetAsync` ... 方法(循环调用).
### DistributedCacheOptions
TODO

2
docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md

@ -243,7 +243,7 @@ ObjectExtensionManager.Instance
这是定义实体属性的另一种方法( 有关 `ObjectExtensionManager` 更多信息,请参阅[文档](Object-Extensions.md)). 这次我们设置了 `CheckPairDefinitionOnMapping` 为false,在将实体映射到DTO时会跳过定义检查.
如果你不喜欢这种方法,但想简单的向多个对象(DTO)添加单个属, `AddOrUpdateProperty` 可以使用类型数组添加额外的属性:
如果你不喜欢这种方法,但想简单的向多个对象(DTO)添加单个属性, `AddOrUpdateProperty` 可以使用类型数组添加额外的属性:
````csharp
ObjectExtensionManager.Instance

4
docs/zh-Hans/Domain-Driven-Design-Implementation-Guide.md

@ -1315,7 +1315,7 @@ namespace IssueTracking.Users
#### 输出DTO最佳实践
* 保持**数量较少**的输出DTO,尽可能**重用输入DTO**(例外:不要将输入DTO作为输出DTO).
* 保持**数量较少**的输出DTO,尽可能**重用输出DTO**(例外:不要将输入DTO作为输出DTO).
* 输出DTO可以包含比用例需要的属性**更多**的属性.
* 针对 **Create** 和 **Update** 方法,返回实体的DTO.
@ -1976,4 +1976,4 @@ public class IssueAppService
* "*Domain Driven Design*" by Eric Evans
* "*Implementing Domain Driven Design*" by Vaughn Vernon
* "*Clean Architecture*" by Robert C. Martin
* "*Clean Architecture*" by Robert C. Martin

9
docs/zh-Hans/MongoDB.md

@ -211,7 +211,7 @@ public async override Task DeleteAsync(
#### 访问MongoDB API
大多数情况下,你想要将MongoDB API隐藏在仓储后面(这是仓储的主要目的).如果你想在仓储之上访问MongoDB API,你可以使用`GetDatabase()`或`GetCollection()`方法.例如:
大多数情况下,你想要将MongoDB API隐藏在仓储后面(这是仓储的主要目的).如果你想在仓储之上访问MongoDB API,你可以使用`GetDatabaseAsync()`, `GetAggregateAsync()` 或`GetCollectionAsync()`方法.例如:
```csharp
public class BookService
@ -223,10 +223,11 @@ public class BookService
_bookRepository = bookRepository;
}
public void Foo()
public async Task FooAsync()
{
IMongoDatabase database = _bookRepository.GetDatabase();
IMongoCollection<Book> books = _bookRepository.GetCollection();
IMongoDatabase database = await _bookRepository.GetDatabaseAsync();
IMongoCollection<Book> books = await _bookRepository.GetCollectionAsync();
IAggregateFluent<Book> bookAggregate = await _bookRepository.GetAggregateAsync();
}
}
```

233
docs/zh-Hans/PlugIn-Modules.md

@ -0,0 +1,233 @@
# 模块化插件
可以将[模块](Module-Development-Basics.md)加载为插件.这意味着你可能不需要在解决方案中引用模块的程序集,就可以像其它模块一样在启动应用时加载该模块.
## 基本用法
`IServiceCollection.AddApplication<T>()` 扩展方法可以获取配置插件源的选项.
**示例: 从文件夹加载插件**
````csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity.PlugIns;
namespace MyPlugInDemo.Web
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication<MyPlugInDemoWebModule>(options =>
{
options.PlugInSources.AddFolder(@"D:\Temp\MyPlugIns");
});
}
public void Configure(IApplicationBuilder app)
{
app.InitializeApplication();
}
}
}
````
* 这是典型的ASP.NET Core应用程序的`Startup`类.
* `PlugInSources.AddFolder`从指定的目录中加载程序集(通常为dll).
就这样.ABP将在这个目录中发现这些模块,像其它常规一样配置和初始化它们.
### 插件源
`options.PlugInSources`类实际上是`IPlugInSource`接口的一系列实现并且 `AddFolder`方法仅仅是以下表达式的便捷方法:
````csharp
options.PlugInSources.Add(new FolderPlugInSource(@"D:\Temp\MyPlugIns"));
````
> `AddFolder()`方法仅在给定目录下查找程序集文件,而不在子目录中查找.你可以传递一个`SearchOption.AllDirectories`参数作为第二个参数,来递归地查找它的子目录.
这里有两个内置插件源的示例:
* `PlugInSources.AddFiles()`方法获取程序集(通常是dll)文件列表.这是使用`FilePlugInSource`类的快捷方式.
* `PlugInSources.AddTypes()`方法获取模块类类型的列表.如果实用化此方法,则需要自己加载模块的程序集,但是在需要时它提供了灵活性.这是使用`TypePlugInSource`类的快捷方式.
如果需要,你可以创建自己的`IPlugInSource`的接口实现,并像其它方法一样添加到`options.PlugInSources`中.
## 示例:创建一个简单的插件
在一个解决方案中创建一个简单的**类库项目**
![简单插件库](images/simple-plugin-library.png)
你可以在模块中添加需要使用的ABP框架包.至少,你应该为这个项目添加包`Volo.Abp.Core`:
````
Install-Package Volo.Abp.Core
````
每个[模块](Module-Development-Basics.md)必须声明为一个继承自`AbpModule`的类.这里是一个简单的模块类,用于解析一个服务并在应用启动时对其初始化:
````csharp
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Modularity;
namespace MyPlugIn
{
public class MyPlungInModule : AbpModule
{
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var myService = context.ServiceProvider
.GetRequiredService<MyService>();
myService.Initialize();
}
}
}
````
`MyService`可以是注册在[依赖注入](Dependency-Injection.md)系统中的任意类,如下所示:
````csharp
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
namespace MyPlugIn
{
public class MyService : ITransientDependency
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public void Initialize()
{
_logger.LogInformation("MyService has been initialized");
}
}
}
````
编译这个项目,打开build目录,找到`MyPlugIn.dll`:
![简单dll插件](images/simple-plug-in-dll-file.png)
将`MyPlugIn.dll`复制到到插件目录中(此实例为`D:\Temp\MyPlugIns`).
如果你已经按照上述方式配置了主应用程序(参见“基础用法”部分),那么在应用程序启动时,你可以看到“MyService has been initialized(MyService已经初始化)的日志.
## 示例:创建一个Razor Pages插件
创建内部带视图的插件需要更多的注意.
> 这个示例假设你已经使用应用程序启动模板和MVC / Razor Pages UI[创建了一个新的Web应用程序](https://abp.io/get-started).
在解决方案中创建一个新的**类库**项目:
![简单razor插件](images/simple-razor-plugin.png)
编辑这个`.csproj`文件内容:
````xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<OutputType>Library</OutputType>
<IsPackable>true</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared" Version="4.0.1" />
</ItemGroup>
</Project>
````
* 将`Sdk`修改为`Microsoft.NET.Sdk.Web`.
* 添加了`OutputType`和`IsPackable`属性.
* 添加了`Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared`NuGet包.
> 不需要[Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared) 包.你可以引用更基础的程序包,例如[Volo.Abp.AspNetCore.Mvc](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc/). 但是,如果需要构建一个UI视图/组件,建议参考[Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared](https://www.nuget.org/packages/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared)程序包,因为它是最高级的程序包,不依赖于特定[theme](UI/AspNetCore/Theming.md).如果依赖特定主题没有问题,则可以直接引用该主题的程序包,以便能够使用插件中特定于主题的功能.
接下来在插件中创建模块类:
````csharp
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
using Volo.Abp.Modularity;
namespace MyMvcUIPlugIn
{
[DependsOn(typeof(AbpAspNetCoreMvcUiThemeSharedModule))]
public class MyMvcUIPlugInModule : AbpModule
{
public override void PreConfigureServices(ServiceConfigurationContext context)
{
PreConfigure<IMvcBuilder>(mvcBuilder =>
{
// 添加插件程序集
mvcBuilder.PartManager.ApplicationParts.Add(new AssemblyPart(typeof(MyMvcUIPlugInModule).Assembly));
// 添加视图程序集
var viewDllPath = Path.Combine(Path.GetDirectoryName(typeof(MyMvcUIPlugInModule).Assembly.Location), "MyMvcUIPlugIn.Views.dll");
var viewAssembly = new CompiledRazorAssemblyPart(Assembly.LoadFrom(viewDllPath));
mvcBuilder.PartManager.ApplicationParts.Add(viewAssembly);
});
}
}
}
````
* 由于我们添加了相关的NuGet包,因此取决于`AbpAspNetCoreMvcUiThemeSharedModule`.
* 添加插件程序集到ASP.NET Core MVC的`PartManager`中.这是ASP.NET Core所必需的.否则,你插件中的控制器将无法正常工作.
* 添加插件的视图程序集到ASP.NET Core MVC的`PartManager`中.这是ASP.NET Core所必需的.否则,你在插件中的视图将不起作用.
现在,你可以在`Pages`目录下添加一个razor页面,例如`MyPlugInPage.cshtml`:
````html
@page
@model MyMvcUIPlugIn.Pages.MyPlugInPage
<h1>Welcome to my plug-in page</h1>
<p>This page is located inside a plug-in module! :)</p>
````
现在,你可以构建插件项目.它将产生以下输出:
![simple-razor-plug-in-dll-file](images/simple-razor-plug-in-dll-file.png)
将`MyMvcUIPlugIn.dll`和`MyMvcUIPlugIn.Views.dll`复制到到插件目录下(此示例中为`D:\Temp\MyPlugIns`).
如果你已经按照上述方式配置了主应用程序(参见“基础用法”部分),那么在应用程序启动的时候,你应该能够访问`/MyPlugInPage`URL:
![simple-plugin-output](images/simple-plugin-output.png)
## 讨论
在现实世界中,你的插件可能具有一些外部依赖性.另外,你的应用程序可能被设计为支持插件.所有这些都是你自己的系统要求.ABP做的仅仅是在应用程序启动时加载模块.你在这些模块中执行什么操作由你决定.
但是,我们可以为一些常见情况提供一些建议.
### 库依赖
对于包/dll依赖,你可以将相关的dll复制到插件目录下.ABP会自动将所有程序集加载到该目录下,并且你的插件将按预期工作.
> 请参见[Microsoft文档](https://docs.microsoft.com/zh-cn/dotnet/core/tutorials/creating-app-with-plugin-support#plugin-with-library-dependencies).
### 数据库模式
如果你的模块使用关系型数据库和[Entity Framework Core](Entity-Framework-Core.md), 那么它需要在数据库中提供表.有多种不同的方法可确保在应用程序使用插件时创建表.一些例子;
1. 插件可以检查数据库表是否存在,并在应用程序启动时创建表,或者如果插件已更新且需要进行某些架构更改时,则会迁移它们.你可以使用EF Core的迁移API来做到这一点.
2. 你可以改进`DbMigrator`应用程序,用于查找插件的迁移并执行它们.
可能还有其它解决方案.例如,如果你的数据库管理员不允许你在应用程序代码中更改数据库模式,则可能需要手动将SQL文件发送给数据库管理员,以将其应用于数据库.

1
docs/zh-Hans/Redis-Cache.md

@ -0,0 +1 @@
TODO...

3
docs/zh-Hans/docs-nav.json

@ -313,7 +313,8 @@
"path": "Module-Development-Basics.md"
},
{
"text": "模块插件"
"text": "模块插件",
"path": "PlugIn-Modules.md"
},
{
"text": "自定义应用模块",

BIN
docs/zh-Hans/images/simple-plug-in-dll-file.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

BIN
docs/zh-Hans/images/simple-plugin-library.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
docs/zh-Hans/images/simple-plugin-output.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

BIN
docs/zh-Hans/images/simple-razor-plug-in-dll-file.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

BIN
docs/zh-Hans/images/simple-razor-plugin.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

7
framework/Volo.Abp.sln

@ -359,6 +359,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Json.Tests", "test
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Http.Tests", "test\Volo.Abp.Http.Tests\Volo.Abp.Http.Tests.csproj", "{A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.EventBus.Abstractions", "src\Volo.Abp.EventBus.Abstractions\Volo.Abp.EventBus.Abstractions.csproj", "{8FDB3BF7-AD89-43F6-8DEB-C3E29B8801FE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -1069,6 +1071,10 @@ Global
{A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1}.Release|Any CPU.Build.0 = Release|Any CPU
{8FDB3BF7-AD89-43F6-8DEB-C3E29B8801FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8FDB3BF7-AD89-43F6-8DEB-C3E29B8801FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FDB3BF7-AD89-43F6-8DEB-C3E29B8801FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FDB3BF7-AD89-43F6-8DEB-C3E29B8801FE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -1250,6 +1256,7 @@ Global
{DD9519E0-5A68-48DC-A051-7BF2AC922F3E} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6}
{00D07595-993C-40FC-BD90-0DD6331414D3} = {447C8A77-E5F0-4538-8687-7383196D04EA}
{A37BFEB5-7C57-4CDC-93B8-B5CE4BB9ACE1} = {447C8A77-E5F0-4538-8687-7383196D04EA}
{8FDB3BF7-AD89-43F6-8DEB-C3E29B8801FE} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BB97ECF4-9A84-433F-A80B-2A3285BDD1D5}

14
framework/src/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/Themes/Basic/SecondLevelNavMenuItem.razor

@ -10,14 +10,12 @@
if (MenuItem.Url != null)
{
<a class="dropdown-item @cssClass @disabled" href="@url" target="@MenuItem.Target" id="@elementId">
@if (MenuItem.Icon != null)
{
if (MenuItem.Icon.StartsWith("fa"))
{
<i class="@MenuItem.Icon"></i>
}
}
@MenuItem.DisplayName
<span class="lp-icon">
<i class="@(MenuItem.Icon ?? "")"></i>
</span>
<span class="lp-text">
@MenuItem.DisplayName
</span>
</a>
}
}

72
framework/src/Volo.Abp.AspNetCore.MultiTenancy/Volo/Abp/AspNetCore/MultiTenancy/MultiTenancyMiddleware.cs

@ -1,7 +1,14 @@
using System.Threading.Tasks;
using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.RequestLocalization;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Localization;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Settings;
namespace Volo.Abp.AspNetCore.MultiTenancy
{
@ -21,10 +28,71 @@ namespace Volo.Abp.AspNetCore.MultiTenancy
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var tenant = await _tenantConfigurationProvider.GetAsync(saveResolveResult: true);
using (_currentTenant.Change(tenant?.Id, tenant?.Name))
if (tenant?.Id != _currentTenant.Id)
{
using (_currentTenant.Change(tenant?.Id, tenant?.Name))
{
var requestCulture = await TryGetRequestCultureAsync(context);
if (requestCulture != null)
{
CultureInfo.CurrentCulture = requestCulture.Culture;
CultureInfo.CurrentUICulture = requestCulture.UICulture;
AbpRequestCultureCookieHelper.SetCultureCookie(
context,
requestCulture
);
}
await next(context);
}
}
else
{
await next(context);
}
}
private async Task<RequestCulture> TryGetRequestCultureAsync(HttpContext httpContext)
{
var requestCultureFeature = httpContext.Features.Get<IRequestCultureFeature>();
/* If requestCultureFeature == null, that means the RequestLocalizationMiddleware was not used
* and we don't want to set the culture. */
if (requestCultureFeature == null)
{
return null;
}
/* If requestCultureFeature.Provider is not null, that means RequestLocalizationMiddleware
* already picked a language, so we don't need to set the default. */
if (requestCultureFeature.Provider != null)
{
return null;
}
var settingProvider = httpContext.RequestServices.GetRequiredService<ISettingProvider>();
var defaultLanguage = await settingProvider.GetOrNullAsync(LocalizationSettingNames.DefaultLanguage);
if (defaultLanguage.IsNullOrWhiteSpace())
{
return null;
}
string culture;
string uiCulture;
if (defaultLanguage.Contains(';'))
{
var splitted = defaultLanguage.Split(';');
culture = splitted[0];
uiCulture = splitted[1];
}
else
{
culture = defaultLanguage;
uiCulture = defaultLanguage;
}
return new RequestCulture(culture, uiCulture);
}
}
}

3
framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/MvcCachedApplicationConfigurationClientHelper.cs

@ -7,7 +7,8 @@ namespace Volo.Abp.AspNetCore.Mvc.Client
{
public static string CreateCacheKey(ICurrentUser currentUser)
{
return $"ApplicationConfiguration_{currentUser.Id?.ToString("N") ?? "Anonymous"}_{CultureInfo.CurrentUICulture.Name}";
var userKey = currentUser.Id?.ToString("N") ?? "Anonymous";
return $"ApplicationConfiguration_{userKey}_{CultureInfo.CurrentUICulture.Name}";
}
}
}

2
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/dom-event-handlers.js

@ -159,7 +159,7 @@
abp.dom.initializers.initializeDatepickers = function ($rootElement) {
$rootElement
.findWithSelf('input.datepicker,input[type=date]')
.findWithSelf('input.datepicker,input[type=date][abp-data-datepicker!=false]')
.each(function () {
var $input = $(this);
$input

9
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js

@ -39,7 +39,7 @@ $.validator.defaults.ignore = ''; //TODO: Would be better if we can apply only f
var _$modal = null;
var _$form = null;
var _modalId = 'Modal_' + (Math.floor((Math.random() * 1000000))) + new Date().getTime();
var _modalId = 'Abp_Modal_' + (Math.floor((Math.random() * 1000000))) + new Date().getTime();
var _modalObject = null;
var _publicApi = null;
@ -56,7 +56,12 @@ $.validator.defaults.ignore = ''; //TODO: Would be better if we can apply only f
function _createContainer() {
_removeContainer();
_$modalContainer = $('<div id="' + _modalId + 'Container' + '"></div>');
$('body').prepend(_$modalContainer);
var existsModals = $('[id^="Abp_Modal_"]');
if (existsModals.length) {
existsModals.last().after(_$modalContainer)
} else {
$('body').prepend(_$modalContainer);
}
return _$modalContainer;
}

19
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js

@ -30,7 +30,7 @@
var htmlEncode = function (html) {
return $('<div/>').text(html).html();
}
var _createDropdownItem = function (record, fieldItem, tableInstance) {
var $li = $('<li/>');
var $a = $('<a/>');
@ -90,15 +90,15 @@
}
$button.append(htmlEncode(firstItem.text));
}
if (firstItem.enabled && !firstItem.enabled({ record: record, table: tableInstance })) {
$button.addClass('disabled');
}
if (firstItem.action) {
$button.click(function (e) {
e.preventDefault();
if (!$(this).hasClass('disabled')) {
if (firstItem.confirmMessage) {
abp.message.confirm(firstItem.confirmMessage({ record: record, table: tableInstance }))
@ -217,7 +217,7 @@
var renderRowActions = function (tableInstance, nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var columns;
if (tableInstance.aoColumns) {
columns = tableInstance.aoColumns;
} else {
@ -334,7 +334,10 @@
};
}
return function (requestData, callback, settings) {
var input = inputAction ? inputAction(requestData, settings) : {};
var input = typeof inputAction === 'function'
? inputAction(requestData, settings)
: typeof inputAction === 'object'
? inputAction : {};
//Paging
if (settings.oInit.paging) {
@ -463,7 +466,7 @@
datatables.defaultConfigurations.scrollX = true;
datatables.defaultConfigurations.responsive = true;
datatables.defaultConfigurations.responsive = true;
datatables.defaultConfigurations.language = function () {
return {
@ -484,6 +487,6 @@
};
};
datatables.defaultConfigurations.dom = '<"dataTable_filters"f>rt<"row dataTable_footer"<"col-auto"l><"col-auto"i><"col"p>>';
datatables.defaultConfigurations.dom = '<"dataTable_filters"f>rt<"row dataTable_footer"<"col-auto"l><"col-auto mr-auto"i><"col-auto"p>>';
})(jQuery);

2
framework/src/Volo.Abp.AspNetCore.Mvc.UI/Volo.Abp.AspNetCore.Mvc.UI.csproj

@ -15,7 +15,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NUglify" Version="1.11.4" />
<PackageReference Include="NUglify" Version="1.13.2" />
</ItemGroup>
<ItemGroup>

2
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs

@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.AspNetCore.Mvc.Auditing;
using Volo.Abp.AspNetCore.Mvc.Content;
using Volo.Abp.AspNetCore.Mvc.ContentFormatters;
using Volo.Abp.AspNetCore.Mvc.Conventions;
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
using Volo.Abp.AspNetCore.Mvc.Features;

53
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs

@ -25,17 +25,20 @@ namespace Volo.Abp.AspNetCore.Mvc
{
public ILogger<AspNetCoreApiDescriptionModelProvider> Logger { get; set; }
private readonly AspNetCoreApiDescriptionModelProviderOptions _options;
private readonly IApiDescriptionGroupCollectionProvider _descriptionProvider;
private readonly AbpAspNetCoreMvcOptions _options;
private readonly AbpAspNetCoreMvcOptions _abpAspNetCoreMvcOptions;
private readonly AbpApiDescriptionModelOptions _modelOptions;
public AspNetCoreApiDescriptionModelProvider(
IOptions<AspNetCoreApiDescriptionModelProviderOptions> options,
IApiDescriptionGroupCollectionProvider descriptionProvider,
IOptions<AbpAspNetCoreMvcOptions> options,
IOptions<AbpAspNetCoreMvcOptions> abpAspNetCoreMvcOptions,
IOptions<AbpApiDescriptionModelOptions> modelOptions)
{
_descriptionProvider = descriptionProvider;
_options = options.Value;
_descriptionProvider = descriptionProvider;
_abpAspNetCoreMvcOptions = abpAspNetCoreMvcOptions.Value;
_modelOptions = modelOptions.Value;
Logger = NullLogger<AspNetCoreApiDescriptionModelProvider>.Instance;
@ -82,14 +85,14 @@ namespace Volo.Abp.AspNetCore.Mvc
var controllerModel = moduleModel.GetOrAddController(
controllerType.FullName,
CalculateControllerName(controllerType, setting),
_options.ControllerNameGenerator(controllerType, setting),
controllerType,
_modelOptions.IgnoredInterfaces
);
var method = apiDescription.ActionDescriptor.GetMethodInfo();
var uniqueMethodName = GetUniqueActionName(method);
var uniqueMethodName = _options.ActionNameGenerator(method);
if (controllerModel.Actions.ContainsKey(uniqueMethodName))
{
Logger.LogWarning(
@ -119,44 +122,6 @@ namespace Volo.Abp.AspNetCore.Mvc
AddParameterDescriptionsToModel(actionModel, method, apiDescription);
}
private static string CalculateControllerName(Type controllerType, ConventionalControllerSetting setting)
{
var controllerName = controllerType.Name.RemovePostFix("Controller")
.RemovePostFix(ApplicationService.CommonPostfixes);
if (setting?.UrlControllerNameNormalizer != null)
{
controllerName =
setting.UrlControllerNameNormalizer(
new UrlControllerNameNormalizerContext(setting.RootPath, controllerName));
}
return controllerName;
}
private static string GetUniqueActionName(MethodInfo method)
{
var methodNameBuilder = new StringBuilder(method.Name);
var parameters = method.GetParameters();
if (parameters.Any())
{
methodNameBuilder.Append("By");
for (var i = 0; i < parameters.Length; i++)
{
if (i > 0)
{
methodNameBuilder.Append("And");
}
methodNameBuilder.Append(parameters[i].Name.ToPascalCase());
}
}
return methodNameBuilder.ToString();
}
private static List<string> GetSupportedVersions(Type controllerType, MethodInfo method,
ConventionalControllerSetting setting)
{
@ -377,7 +342,7 @@ namespace Volo.Abp.AspNetCore.Mvc
[CanBeNull]
private ConventionalControllerSetting FindSetting(Type controllerType)
{
foreach (var controllerSetting in _options.ConventionalControllers.ConventionalControllerSettings)
foreach (var controllerSetting in _abpAspNetCoreMvcOptions.ConventionalControllers.ConventionalControllerSettings)
{
if (controllerSetting.ControllerTypes.Contains(controllerType))
{

57
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProviderOptions.cs

@ -0,0 +1,57 @@
using System;
using System.Linq;
using System.Reflection;
using System.Text;
using Volo.Abp.Application.Services;
using Volo.Abp.AspNetCore.Mvc.Conventions;
namespace Volo.Abp.AspNetCore.Mvc
{
public class AspNetCoreApiDescriptionModelProviderOptions
{
public Func<Type, ConventionalControllerSetting, string> ControllerNameGenerator { get; set; }
public Func<MethodInfo, string> ActionNameGenerator { get; set; }
public AspNetCoreApiDescriptionModelProviderOptions()
{
ControllerNameGenerator = (controllerType, setting) =>
{
var controllerName = controllerType.Name.RemovePostFix("Controller")
.RemovePostFix(ApplicationService.CommonPostfixes);
if (setting?.UrlControllerNameNormalizer != null)
{
controllerName =
setting.UrlControllerNameNormalizer(
new UrlControllerNameNormalizerContext(setting.RootPath, controllerName));
}
return controllerName;
};
ActionNameGenerator = (method) =>
{
var methodNameBuilder = new StringBuilder(method.Name);
var parameters = method.GetParameters();
if (parameters.Any())
{
methodNameBuilder.Append("By");
for (var i = 0; i < parameters.Length; i++)
{
if (i > 0)
{
methodNameBuilder.Append("And");
}
methodNameBuilder.Append(parameters[i].Name.ToPascalCase());
}
}
return methodNameBuilder.ToString();
};
}
}
}

25
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Content/InternalRemoteStreamContent.cs

@ -1,25 +0,0 @@
using System.IO;
using Microsoft.AspNetCore.Http;
using Volo.Abp.Content;
namespace Volo.Abp.AspNetCore.Mvc.Content
{
internal class InternalRemoteStreamContent : IRemoteStreamContent
{
private readonly HttpContext _httpContext;
public InternalRemoteStreamContent(HttpContext httpContext)
{
_httpContext = httpContext;
}
public string ContentType => _httpContext.Request.ContentType;
public long? ContentLength => _httpContext.Request.ContentLength;
public Stream GetStream()
{
return _httpContext.Request.Body;
}
}
}

11
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Content/RemoteStreamContentInputFormatter.cs → framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentInputFormatter.cs

@ -1,10 +1,10 @@
using System;
using System.Threading.Tasks;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using Volo.Abp.Content;
namespace Volo.Abp.AspNetCore.Mvc.Content
namespace Volo.Abp.AspNetCore.Mvc.ContentFormatters
{
public class RemoteStreamContentInputFormatter : InputFormatter
{
@ -20,9 +20,10 @@ namespace Volo.Abp.AspNetCore.Mvc.Content
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
return InputFormatterResult.SuccessAsync(
new InternalRemoteStreamContent(context.HttpContext)
);
return InputFormatterResult.SuccessAsync(new RemoteStreamContent(context.HttpContext.Request.Body)
{
ContentType = context.HttpContext.Request.ContentType
});
}
}
}

13
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Content/RemoteStreamContentOutputFormatter.cs → framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentOutputFormatter.cs

@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using Volo.Abp.Content;
namespace Volo.Abp.AspNetCore.Mvc.Content
namespace Volo.Abp.AspNetCore.Mvc.ContentFormatters
{
public class RemoteStreamContentOutputFormatter : OutputFormatter
{
@ -21,9 +21,16 @@ namespace Volo.Abp.AspNetCore.Mvc.Content
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
var remoteStream = (IRemoteStreamContent)context.Object;
using (var stream = remoteStream.GetStream())
if (remoteStream != null)
{
await stream.CopyToAsync(context.HttpContext.Response.Body);
context.HttpContext.Response.ContentType = remoteStream.ContentType;
using (var stream = remoteStream.GetStream())
{
stream.Position = 0;
await stream.CopyToAsync(context.HttpContext.Response.Body);
}
}
}
}

14
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Localization/AbpLanguagesController.cs

@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using System;
using Microsoft.AspNetCore.RequestLocalization;
using Volo.Abp.Localization;
namespace Volo.Abp.AspNetCore.Mvc.Localization
@ -20,12 +20,10 @@ namespace Volo.Abp.AspNetCore.Mvc.Localization
throw new AbpException("Unknown language: " + culture + ". It must be a valid culture!");
}
string cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture, uiCulture));
Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName, cookieValue, new CookieOptions
{
Expires = Clock.Now.AddYears(2)
});
AbpRequestCultureCookieHelper.SetCultureCookie(
HttpContext,
new RequestCulture(culture, uiCulture)
);
if (!string.IsNullOrWhiteSpace(returnUrl))
{

23
framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/RequestLocalization/AbpRequestCultureCookieHelper.cs

@ -0,0 +1,23 @@
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
namespace Microsoft.AspNetCore.RequestLocalization
{
public static class AbpRequestCultureCookieHelper
{
public static void SetCultureCookie(
HttpContext httpContext,
RequestCulture requestCulture)
{
httpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(requestCulture),
new CookieOptions
{
Expires = DateTime.Now.AddYears(2)
}
);
}
}
}

6
framework/src/Volo.Abp.AutoMapper/Volo/Abp/AutoMapper/AbpAutoMapperModule.cs

@ -25,7 +25,7 @@ namespace Volo.Abp.AutoMapper
{
context.Services.AddAutoMapperObjectMapper();
context.Services.AddSingleton<MapperAccessor>(provider => CreateMappings(provider));
context.Services.AddSingleton<MapperAccessor>(CreateMappings);
context.Services.AddSingleton<IMapperAccessor>(provider => provider.GetRequiredService<MapperAccessor>());
}
@ -43,6 +43,8 @@ namespace Volo.Abp.AutoMapper
}
}
options.Configurators.Insert(0, ctx => ctx.MapperConfiguration.ConstructServicesUsing(serviceProvider.GetService));
void ValidateAll(IConfigurationProvider config)
{
foreach (var profileType in options.ValidatingProfiles)
@ -60,7 +62,7 @@ namespace Volo.Abp.AutoMapper
return new MapperAccessor
{
Mapper = new Mapper(mapperConfiguration, serviceProvider.GetService)
Mapper = new Mapper(mapperConfiguration)
};
}
}

67
framework/src/Volo.Abp.Autofac/Autofac/Extensions/DependencyInjection/ServiceCollectionExtensions.cs

@ -1,67 +0,0 @@
// This software is part of the Autofac IoC container
// Copyright © 2017 Autofac Contributors
// http://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
namespace Autofac.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods on <see cref="IServiceCollection"/> to register the <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="AutofacServiceProviderFactory"/> to the service collection.
/// </summary>
/// <param name="services">The service collection to add the factory to.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the container.</param>
/// <returns>The service collection.</returns>
public static IServiceCollection AddAutofac(this IServiceCollection services, Action<ContainerBuilder> configurationAction = null)
{
return services
.ClearServiceProviderFactories()
.AddSingleton<IServiceProviderFactory<ContainerBuilder>>(new AutofacServiceProviderFactory(configurationAction));
}
private static IServiceCollection ClearServiceProviderFactories([NotNull] this IServiceCollection services)
{
Check.NotNull(services, nameof(services));
services.RemoveAll(
service => service.ImplementationInstance?
.GetType()
.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IServiceProviderFactory<>)) == true
);
return services;
}
}
}

6
framework/src/Volo.Abp.BlazoriseUI/Volo.Abp.BlazoriseUI.csproj

@ -12,9 +12,9 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Blazorise" Version="0.9.3-preview6" />
<PackageReference Include="Blazorise.DataGrid" Version="0.9.3-preview6" />
<PackageReference Include="Blazorise.Snackbar" Version="0.9.3-preview6" />
<PackageReference Include="Blazorise" Version="0.9.3-preview8" />
<PackageReference Include="Blazorise.DataGrid" Version="0.9.3-preview8" />
<PackageReference Include="Blazorise.Snackbar" Version="0.9.3-preview8" />
</ItemGroup>
</Project>

57
framework/src/Volo.Abp.Caching.StackExchangeRedis/Volo/Abp/Caching/StackExchangeRedis/AbpRedisCache.cs

@ -45,19 +45,26 @@ namespace Volo.Abp.Caching.StackExchangeRedis
MapMetadataMethod = type.GetMethod("MapMetadata", BindingFlags.Instance | BindingFlags.NonPublic);
GetAbsoluteExpirationMethod = type.GetMethod("GetAbsoluteExpiration", BindingFlags.Static | BindingFlags.NonPublic);
GetAbsoluteExpirationMethod =
type.GetMethod("GetAbsoluteExpiration", BindingFlags.Static | BindingFlags.NonPublic);
GetExpirationInSecondsMethod = type.GetMethod("GetExpirationInSeconds", BindingFlags.Static | BindingFlags.NonPublic);
GetExpirationInSecondsMethod =
type.GetMethod("GetExpirationInSeconds", BindingFlags.Static | BindingFlags.NonPublic);
SetScript = type.GetField("SetScript", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null).ToString();
SetScript = type.GetField("SetScript", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null)
.ToString();
AbsoluteExpirationKey = type.GetField("AbsoluteExpirationKey", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null).ToString();
AbsoluteExpirationKey = type.GetField("AbsoluteExpirationKey", BindingFlags.Static | BindingFlags.NonPublic)
?.GetValue(null).ToString();
SlidingExpirationKey = type.GetField("SlidingExpirationKey", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null).ToString();
SlidingExpirationKey = type.GetField("SlidingExpirationKey", BindingFlags.Static | BindingFlags.NonPublic)
?.GetValue(null).ToString();
DataKey = type.GetField("DataKey", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null).ToString();
DataKey = type.GetField("DataKey", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null).ToString();
NotPresent = type.GetField("NotPresent", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null).To<int>();
// ReSharper disable once PossibleNullReferenceException
NotPresent = type.GetField("NotPresent", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null)
.To<int>();
}
public AbpRedisCache(IOptions<RedisCacheOptions> optionsAccessor)
@ -124,6 +131,42 @@ namespace Volo.Abp.Caching.StackExchangeRedis
await Task.WhenAll(PipelineSetMany(items, options));
}
public void RefreshMany(
IEnumerable<string> keys)
{
keys = Check.NotNull(keys, nameof(keys));
GetAndRefreshMany(keys, false);
}
public async Task RefreshManyAsync(
IEnumerable<string> keys,
CancellationToken token = default)
{
keys = Check.NotNull(keys, nameof(keys));
await GetAndRefreshManyAsync(keys, false, token);
}
public void RemoveMany(IEnumerable<string> keys)
{
keys = Check.NotNull(keys, nameof(keys));
Connect();
RedisDatabase.KeyDelete(keys.Select(key => (RedisKey)(Instance + key)).ToArray());
}
public async Task RemoveManyAsync(IEnumerable<string> keys, CancellationToken token = default)
{
keys = Check.NotNull(keys, nameof(keys));
token.ThrowIfCancellationRequested();
await ConnectAsync(token);
await RedisDatabase.KeyDeleteAsync(keys.Select(key => (RedisKey)(Instance + key)).ToArray());
}
protected virtual byte[][] GetAndRefreshMany(
IEnumerable<string> keys,
bool getData)

381
framework/src/Volo.Abp.Caching/Volo/Abp/Caching/DistributedCache.cs

@ -527,6 +527,198 @@ namespace Volo.Abp.Caching
return value;
}
public KeyValuePair<TCacheKey, TCacheItem>[] GetOrAddMany(
IEnumerable<TCacheKey> keys,
Func<IEnumerable<TCacheKey>, List<KeyValuePair<TCacheKey, TCacheItem>>> factory,
Func<DistributedCacheEntryOptions> optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false)
{
KeyValuePair<TCacheKey, TCacheItem>[] result;
var keyArray = keys.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
result = GetManyFallback(
keyArray,
hideErrors,
considerUow
);
}
else
{
var notCachedKeys = new List<TCacheKey>();
var cachedValues = new List<KeyValuePair<TCacheKey, TCacheItem>>();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
var value = uowCache.GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
cachedValues.Add(new KeyValuePair<TCacheKey, TCacheItem>(key, value));
}
}
notCachedKeys = keyArray.Except(cachedValues.Select(x => x.Key)).ToList();
if (!notCachedKeys.Any())
{
return cachedValues.ToArray();
}
}
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
byte[][] cachedBytes;
var readKeys = notCachedKeys.Any() ? notCachedKeys.ToArray() : keyArray;
try
{
cachedBytes = cacheSupportsMultipleItems.GetMany(readKeys.Select(NormalizeKey));
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return ToCacheItemsWithDefaultValues(keyArray);
}
throw;
}
result = cachedValues.Concat(ToCacheItems(cachedBytes, readKeys)).ToArray();
}
if (result.All(x => x.Value != null))
{
return result;
}
var missingKeys = new List<TCacheKey>();
var missingValuesIndex = new List<int>();
for (var i = 0; i < keyArray.Length; i++)
{
if (result[i].Value != null)
{
continue;
}
missingKeys.Add(keyArray[i]);
missingValuesIndex.Add(i);
}
var missingValues = factory.Invoke(missingKeys).ToArray();
var valueQueue = new Queue<KeyValuePair<TCacheKey, TCacheItem>>(missingValues);
SetMany(missingValues, optionsFactory?.Invoke(), hideErrors, considerUow);
foreach (var index in missingValuesIndex)
{
result[index] = valueQueue.Dequeue();
}
return result;
}
public async Task<KeyValuePair<TCacheKey, TCacheItem>[]> GetOrAddManyAsync(
IEnumerable<TCacheKey> keys,
Func<IEnumerable<TCacheKey>, Task<List<KeyValuePair<TCacheKey, TCacheItem>>>> factory,
Func<DistributedCacheEntryOptions> optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
KeyValuePair<TCacheKey, TCacheItem>[] result;
var keyArray = keys.ToArray();
var cacheSupportsMultipleItems = Cache as ICacheSupportsMultipleItems;
if (cacheSupportsMultipleItems == null)
{
result = await GetManyFallbackAsync(
keyArray,
hideErrors,
considerUow, token);
}
else
{
var notCachedKeys = new List<TCacheKey>();
var cachedValues = new List<KeyValuePair<TCacheKey, TCacheItem>>();
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
var value = uowCache.GetOrDefault(key)?.GetUnRemovedValueOrNull();
if (value != null)
{
cachedValues.Add(new KeyValuePair<TCacheKey, TCacheItem>(key, value));
}
}
notCachedKeys = keyArray.Except(cachedValues.Select(x => x.Key)).ToList();
if (!notCachedKeys.Any())
{
return cachedValues.ToArray();
}
}
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
byte[][] cachedBytes;
var readKeys = notCachedKeys.Any() ? notCachedKeys.ToArray() : keyArray;
try
{
cachedBytes = await cacheSupportsMultipleItems.GetManyAsync(readKeys.Select(NormalizeKey), token);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return ToCacheItemsWithDefaultValues(keyArray);
}
throw;
}
result = cachedValues.Concat(ToCacheItems(cachedBytes, readKeys)).ToArray();
}
if (result.All(x => x.Value != null))
{
return result;
}
var missingKeys = new List<TCacheKey>();
var missingValuesIndex = new List<int>();
for (var i = 0; i < keyArray.Length; i++)
{
if (result[i].Value != null)
{
continue;
}
missingKeys.Add(keyArray[i]);
missingValuesIndex.Add(i);
}
var missingValues = (await factory.Invoke(missingKeys)).ToArray();
var valueQueue = new Queue<KeyValuePair<TCacheKey, TCacheItem>>(missingValues);
await SetManyAsync(missingValues, optionsFactory?.Invoke(), hideErrors, considerUow, token);
foreach (var index in missingValuesIndex)
{
result[index] = valueQueue.Dequeue();
}
return result;
}
/// <summary>
/// Sets the cache item value for the provided key.
/// </summary>
@ -924,6 +1116,71 @@ namespace Volo.Abp.Caching
}
}
public virtual void RefreshMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
cacheSupportsMultipleItems.RefreshMany(keys.Select(NormalizeKey));
}
else
{
foreach (var key in keys)
{
Cache.Refresh(NormalizeKey(key));
}
}
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
public virtual async Task RefreshManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
CancellationToken token = default)
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
await cacheSupportsMultipleItems.RefreshManyAsync(keys.Select(NormalizeKey), token);
}
else
{
foreach (var key in keys)
{
await Cache.RefreshAsync(NormalizeKey(key), token);
}
}
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
/// <summary>
/// Removes the cache item for given key from cache.
/// </summary>
@ -1027,6 +1284,130 @@ namespace Volo.Abp.Caching
}
}
public void RemoveMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false)
{
var keyArray = keys.ToArray();
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
void RemoveRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
cacheSupportsMultipleItems.RemoveMany(
keyArray.Select(NormalizeKey)
);
}
catch (Exception ex)
{
if (hideErrors == true)
{
HandleException(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].RemoveValue();
}
}
// ReSharper disable once PossibleNullReferenceException
UnitOfWorkManager.Current.OnCompleted(() =>
{
RemoveRealCache();
return Task.CompletedTask;
});
}
else
{
RemoveRealCache();
}
}
else
{
foreach (var key in keyArray)
{
Remove(key, hideErrors, considerUow);
}
}
}
public async Task RemoveManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default)
{
var keyArray = keys.ToArray();
if (Cache is ICacheSupportsMultipleItems cacheSupportsMultipleItems)
{
async Task RemoveRealCache()
{
hideErrors = hideErrors ?? _distributedCacheOption.HideErrors;
try
{
await cacheSupportsMultipleItems.RemoveManyAsync(
keyArray.Select(NormalizeKey), token);
}
catch (Exception ex)
{
if (hideErrors == true)
{
await HandleExceptionAsync(ex);
return;
}
throw;
}
}
if (ShouldConsiderUow(considerUow))
{
var uowCache = GetUnitOfWorkCache();
foreach (var key in keyArray)
{
if (uowCache.TryGetValue(key, out _))
{
uowCache[key].RemoveValue();
}
}
// ReSharper disable once PossibleNullReferenceException
UnitOfWorkManager.Current.OnCompleted(RemoveRealCache);
}
else
{
await RemoveRealCache();
}
}
else
{
foreach (var key in keyArray)
{
await RemoveAsync(key, hideErrors, considerUow, token);
}
}
}
protected virtual void HandleException(Exception ex)
{
_ = HandleExceptionAsync(ex);

22
framework/src/Volo.Abp.Caching/Volo/Abp/Caching/ICacheSupportsMultipleItems.cs

@ -25,6 +25,24 @@ namespace Volo.Abp.Caching
IEnumerable<KeyValuePair<string, byte[]>> items,
DistributedCacheEntryOptions options,
CancellationToken token = default
);
);
void RefreshMany(
IEnumerable<string> keys
);
Task RefreshManyAsync(
IEnumerable<string> keys,
CancellationToken token = default
);
void RemoveMany(
IEnumerable<string> keys
);
Task RemoveManyAsync(
IEnumerable<string> keys,
CancellationToken token = default
);
}
}
}

90
framework/src/Volo.Abp.Caching/Volo/Abp/Caching/IDistributedCache.cs

@ -14,8 +14,8 @@ namespace Volo.Abp.Caching
public interface IDistributedCache<TCacheItem> : IDistributedCache<TCacheItem, string>
where TCacheItem : class
{
}
/// <summary>
/// Represents a distributed cache of <typeparamref name="TCacheItem" /> type.
/// Uses a generic cache key type of <typeparamref name="TCacheKey" /> type.
@ -128,6 +128,44 @@ namespace Volo.Abp.Caching
CancellationToken token = default
);
/// <summary>
/// Gets or Adds multiple cache items with the given keys. If any cache items not found for the given keys then adds cache items
/// provided by <paramref name="factory" /> delegate and returns the provided cache items.
/// </summary>
/// <param name="keys">The keys of cached items to be retrieved from the cache.</param>
/// <param name="factory">The factory delegate is used to provide the cache items when no cache items are found for the given <paramref name="keys" />.</param>
/// <param name="optionsFactory">The cache options for the factory delegate.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <returns>The cache items.</returns>
KeyValuePair<TCacheKey, TCacheItem>[] GetOrAddMany(
IEnumerable<TCacheKey> keys,
Func<IEnumerable<TCacheKey>, List<KeyValuePair<TCacheKey, TCacheItem>>> factory,
Func<DistributedCacheEntryOptions> optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false
);
/// <summary>
/// Gets or Adds multiple cache items with the given keys. If any cache items not found for the given keys then adds cache items
/// provided by <paramref name="factory" /> delegate and returns the provided cache items.
/// </summary>
/// <param name="keys">The keys of cached items to be retrieved from the cache.</param>
/// <param name="factory">The factory delegate is used to provide the cache items when no cache items are found for the given <paramref name="keys" />.</param>
/// <param name="optionsFactory">The cache options for the factory delegate.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The cache items.</returns>
Task<KeyValuePair<TCacheKey, TCacheItem>[]> GetOrAddManyAsync(
IEnumerable<TCacheKey> keys,
Func<IEnumerable<TCacheKey>, Task<List<KeyValuePair<TCacheKey, TCacheItem>>>> factory,
Func<DistributedCacheEntryOptions> optionsFactory = null,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default
);
/// <summary>
/// Sets the cache item value for the provided key.
/// </summary>
@ -219,6 +257,29 @@ namespace Volo.Abp.Caching
CancellationToken token = default
);
/// <summary>
/// Refreshes the cache value of the given keys, and resets their sliding expiration timeout.
/// Based on the implementation, this can be more efficient than setting multiple items individually.
/// </summary>
/// <param name="keys">The keys of cached items to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
void RefreshMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null);
/// <summary>
/// Refreshes the cache value of the given keys, and resets their sliding expiration timeout.
/// Based on the implementation, this can be more efficient than setting multiple items individually.
/// </summary>
/// <param name="keys">The keys of cached items to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The <see cref="T:System.Threading.Tasks.Task" /> indicating that the operation is asynchronous.</returns>
Task RefreshManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
CancellationToken token = default);
/// <summary>
/// Removes the cache item for given key from cache.
/// </summary>
@ -245,5 +306,32 @@ namespace Volo.Abp.Caching
bool considerUow = false,
CancellationToken token = default
);
/// <summary>
/// Removes the cache items for given keys from cache.
/// </summary>
/// <param name="keys">The keys of cached items to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
void RemoveMany(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false
);
/// <summary>
/// Removes the cache items for given keys from cache.
/// </summary>
/// <param name="keys">The keys of cached items to be retrieved from the cache.</param>
/// <param name="hideErrors">Indicates to throw or hide the exceptions for the distributed cache.</param>
/// <param name="considerUow">This will store the cache in the current unit of work until the end of the current unit of work does not really affect the cache.</param>
/// <param name="token">The <see cref="T:System.Threading.CancellationToken" /> for the task.</param>
/// <returns>The <see cref="T:System.Threading.Tasks.Task" /> indicating that the operation is asynchronous.</returns>
Task RemoveManyAsync(
IEnumerable<TCacheKey> keys,
bool? hideErrors = null,
bool considerUow = false,
CancellationToken token = default
);
}
}

5
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs

@ -1,5 +1,7 @@
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Cli.Commands;
using Volo.Abp.Cli.Http;
using Volo.Abp.Domain;
using Volo.Abp.IdentityModel;
using Volo.Abp.Json;
@ -18,6 +20,9 @@ namespace Volo.Abp.Cli
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddHttpClient(CliConsts.HttpClientName)
.ConfigurePrimaryHttpMessageHandler(() => new CliHttpClientHandler());
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Configure<AbpCliOptions>(options =>

2
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/CliConsts.cs

@ -7,5 +7,7 @@
public const string BranchPrefix = "branch@";
public const string DocsLink = "https://docs.abp.io";
public const string HttpClientName = "AbpHttpClient";
}
}

25
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs

@ -22,13 +22,17 @@ namespace Volo.Abp.Cli.Commands
public ICancellationTokenProvider CancellationTokenProvider { get; }
public IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
private readonly CliHttpClientFactory _cliHttpClientFactory;
public LoginCommand(AuthService authService,
ICancellationTokenProvider cancellationTokenProvider,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler)
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
CliHttpClientFactory cliHttpClientFactory)
{
AuthService = authService;
CancellationTokenProvider = cancellationTokenProvider;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
_cliHttpClientFactory = cliHttpClientFactory;
Logger = NullLogger<LoginCommand>.Instance;
}
@ -79,20 +83,19 @@ namespace Volo.Abp.Cli.Commands
{
var url = $"{CliUrls.WwwAbpIo}api/license/check-multiple-organizations?username={username}";
using (var client = new CliHttpClient())
var client = _cliHttpClientFactory.CreateClient();
using (var response = await client.GetHttpResponseMessageWithRetryAsync(url, CancellationTokenProvider.Token, Logger))
{
using (var response = await client.GetHttpResponseMessageWithRetryAsync(url, CancellationTokenProvider.Token, Logger))
if (!response.IsSuccessStatusCode)
{
if (!response.IsSuccessStatusCode)
{
throw new Exception($"ERROR: Remote server returns '{response.StatusCode}'");
}
throw new Exception($"ERROR: Remote server returns '{response.StatusCode}'");
}
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<bool>(responseContent);
}
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<bool>(responseContent);
}
}

2
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs

@ -16,7 +16,7 @@ namespace Volo.Abp.Cli.Commands.Services
case DatabaseManagementSystem.MySQL:
return "Server=localhost;Port=3306;Database=MyProjectName;Uid=root;Pwd=myPassword;";
case DatabaseManagementSystem.PostgreSQL:
return "User ID=root;Password=myPassword;Host=localhost;Port=5432;Database=MyProjectName;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;";
return "Host=localhost;Port=5432;Database=MyProjectName;User ID=root;Password=myPassword;Pooling=true;MinimumPoolSize=0;MaximumPoolSize=100;Connection Lifetime=0;";
//case DatabaseManagementSystem.Oracle:
case DatabaseManagementSystem.OracleDevart:
return "Data Source=MyProjectName;Integrated Security=yes;";

39
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClient.cs → framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientExtensions.cs

@ -13,29 +13,9 @@ using Microsoft.Extensions.Logging;
namespace Volo.Abp.Cli.Http
{
public class CliHttpClient : HttpClient
public static class CliHttpClientExtensions
{
public static TimeSpan DefaultTimeout { get; set; } = TimeSpan.FromMinutes(1);
public CliHttpClient(TimeSpan? timeout = null)
: base(new CliHttpClientHandler())
{
Timeout = timeout ?? DefaultTimeout;
AddAuthentication(this);
}
public CliHttpClient(bool setBearerToken) : base(new CliHttpClientHandler())
{
Timeout = DefaultTimeout;
if (setBearerToken)
{
AddAuthentication(this);
}
}
private static void AddAuthentication(HttpClient client)
public static void AddAbpAuthenticationToken(this HttpClient httpClient)
{
if (!AuthService.IsLoggedIn())
{
@ -45,12 +25,13 @@ namespace Volo.Abp.Cli.Http
var accessToken = File.ReadAllText(CliPaths.AccessToken, Encoding.UTF8);
if (!accessToken.IsNullOrEmpty())
{
client.SetBearerToken(accessToken);
httpClient.SetBearerToken(accessToken);
}
}
public async Task<HttpResponseMessage> GetHttpResponseMessageWithRetryAsync<T>
public static async Task<HttpResponseMessage> GetHttpResponseMessageWithRetryAsync<T>
(
this HttpClient httpClient,
string url,
CancellationToken? cancellationToken = null,
ILogger<T> logger = null,
@ -67,7 +48,12 @@ namespace Volo.Abp.Cli.Http
};
}
cancellationToken ??= CancellationToken.None;
if (cancellationToken == null)
{
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(httpClient.Timeout);
cancellationToken = cancellationTokenSource.Token;
}
return await HttpPolicyExtensions
.HandleTransientHttpError()
@ -92,8 +78,7 @@ namespace Volo.Abp.Cli.Http
$"Waiting {timeSpan.TotalSeconds} secs for the next try...");
}
})
.ExecuteAsync(async () => await this.GetAsync(url, cancellationToken.Value));
.ExecuteAsync(async () => await httpClient.GetAsync(url, cancellationToken.Value));
}
}
}

58
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Http/CliHttpClientFactory.cs

@ -0,0 +1,58 @@
using System;
using System.Net.Http;
using System.Threading;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Threading;
namespace Volo.Abp.Cli.Http
{
public class CliHttpClientFactory : ISingletonDependency
{
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromMinutes(1);
private readonly IHttpClientFactory _clientFactory;
private readonly ICancellationTokenProvider _cancellationTokenProvider;
public CliHttpClientFactory(IHttpClientFactory clientFactory, ICancellationTokenProvider cancellationTokenProvider)
{
_clientFactory = clientFactory;
_cancellationTokenProvider = cancellationTokenProvider;
}
public HttpClient CreateClient(bool needsAuthentication = true, TimeSpan? timeout = null)
{
var httpClient = _clientFactory.CreateClient(CliConsts.HttpClientName);
httpClient.Timeout = timeout ?? DefaultTimeout;
if (needsAuthentication)
{
httpClient.AddAbpAuthenticationToken();
}
return httpClient;
}
public CancellationToken GetCancellationToken(TimeSpan? timeout = null)
{
if (timeout == null)
{
if (_cancellationTokenProvider == null)
{
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(DefaultTimeout);
return cancellationTokenSource.Token;
}
else
{
return _cancellationTokenProvider.Token;
}
}
else
{
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(Convert.ToInt32(timeout.Value.TotalMilliseconds));
return cancellationTokenSource.Token;
}
}
}
}

24
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Licensing/AbpIoApiKeyService.cs

@ -25,16 +25,19 @@ namespace Volo.Abp.Cli.Licensing
private readonly ILogger<AbpIoApiKeyService> _logger;
private DeveloperApiKeyResult _apiKeyResult = null;
private readonly CliHttpClientFactory _cliHttpClientFactory;
public AbpIoApiKeyService(
IJsonSerializer jsonSerializer,
ICancellationTokenProvider cancellationTokenProvider,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
ILogger<AbpIoApiKeyService> logger)
ILogger<AbpIoApiKeyService> logger,
CliHttpClientFactory cliHttpClientFactory)
{
JsonSerializer = jsonSerializer;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
_logger = logger;
_cliHttpClientFactory = cliHttpClientFactory;
CancellationTokenProvider = cancellationTokenProvider;
}
@ -56,22 +59,21 @@ namespace Volo.Abp.Cli.Licensing
}
var url = $"{CliUrls.WwwAbpIo}api/license/api-key";
var client = _cliHttpClientFactory.CreateClient();
using (var client = new CliHttpClient())
using (var response = await client.GetHttpResponseMessageWithRetryAsync(url, CancellationTokenProvider.Token, _logger))
{
using (var response = await client.GetHttpResponseMessageWithRetryAsync(url, CancellationTokenProvider.Token, _logger))
if (!response.IsSuccessStatusCode)
{
if (!response.IsSuccessStatusCode)
{
throw new Exception($"ERROR: Remote server returns '{response.StatusCode}'");
}
throw new Exception($"ERROR: Remote server returns '{response.StatusCode}'");
}
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<DeveloperApiKeyResult>(responseContent);
}
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<DeveloperApiKeyResult>(responseContent);
}
}
}
}

29
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/NuGet/NuGetService.cs

@ -23,6 +23,7 @@ namespace Volo.Abp.Cli.NuGet
protected ICancellationTokenProvider CancellationTokenProvider { get; }
protected IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
private readonly IApiKeyService _apiKeyService;
private readonly CliHttpClientFactory _cliHttpClientFactory;
private List<string> _proPackageList;
private DeveloperApiKeyResult _apiKeyResult;
@ -30,12 +31,14 @@ namespace Volo.Abp.Cli.NuGet
IJsonSerializer jsonSerializer,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
ICancellationTokenProvider cancellationTokenProvider,
IApiKeyService apiKeyService)
IApiKeyService apiKeyService,
CliHttpClientFactory cliHttpClientFactory)
{
JsonSerializer = jsonSerializer;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
CancellationTokenProvider = cancellationTokenProvider;
_apiKeyService = apiKeyService;
_cliHttpClientFactory = cliHttpClientFactory;
Logger = NullLogger<VoloNugetPackagesVersionUpdater>.Instance;
}
@ -93,18 +96,17 @@ namespace Volo.Abp.Cli.NuGet
url = $"https://api.nuget.org/v3-flatcontainer/{packageId.ToLowerInvariant()}/index.json";
}
using (var client = new CliHttpClient(setBearerToken: false))
var client = _cliHttpClientFactory.CreateClient(needsAuthentication: false);
using (var responseMessage = await client.GetHttpResponseMessageWithRetryAsync(
url,
cancellationToken: CancellationTokenProvider.Token,
logger: Logger
))
{
using (var responseMessage = await client.GetHttpResponseMessageWithRetryAsync(
url,
cancellationToken: CancellationTokenProvider.Token,
logger: Logger
))
{
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(responseMessage);
var responseContent = await responseMessage.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<NuGetVersionResultDto>(responseContent).Versions;
}
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(responseMessage);
var responseContent = await responseMessage.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<NuGetVersionResultDto>(responseContent).Versions;
}
}
@ -120,9 +122,8 @@ namespace Volo.Abp.Cli.NuGet
private async Task<List<string>> GetProPackageListAsync()
{
using var client = new CliHttpClient();
var url = $"{CliUrls.WwwAbpIo}api/app/nugetPackage/proPackageNames";
var client = _cliHttpClientFactory.CreateClient(needsAuthentication: true);
using (var responseMessage = await client.GetHttpResponseMessageWithRetryAsync(
url: url,

103
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/AbpIoSourceCodeStore.cs

@ -9,6 +9,7 @@ using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Cli.Http;
using Volo.Abp.Cli.ProjectBuilding.Templates.App;
@ -28,22 +29,23 @@ namespace Volo.Abp.Cli.ProjectBuilding
public ILogger<AbpIoSourceCodeStore> Logger { get; set; }
protected AbpCliOptions Options { get; }
protected IJsonSerializer JsonSerializer { get; }
protected IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
protected ICancellationTokenProvider CancellationTokenProvider { get; }
private readonly CliHttpClientFactory _cliHttpClientFactory;
public AbpIoSourceCodeStore(
IOptions<AbpCliOptions> options,
IJsonSerializer jsonSerializer,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
ICancellationTokenProvider cancellationTokenProvider)
ICancellationTokenProvider cancellationTokenProvider,
CliHttpClientFactory cliHttpClientFactory)
{
JsonSerializer = jsonSerializer;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
CancellationTokenProvider = cancellationTokenProvider;
_cliHttpClientFactory = cliHttpClientFactory;
Options = options.Value;
Logger = NullLogger<AbpIoSourceCodeStore>.Instance;
@ -134,24 +136,17 @@ namespace Volo.Abp.Cli.ProjectBuilding
try
{
using (var client = new CliHttpClient(TimeSpan.FromMinutes(10)))
var client = _cliHttpClientFactory.CreateClient();
var stringContent = new StringContent(
JsonSerializer.Serialize(new GetLatestSourceCodeVersionDto { Name = name, IncludePreReleases = includePreReleases }),
Encoding.UTF8,
MimeTypes.Application.Json
);
using (var response = await client.PostAsync(url, stringContent, _cliHttpClientFactory.GetCancellationToken(TimeSpan.FromMinutes(10))))
{
var response = await client.PostAsync(
url,
new StringContent(
JsonSerializer.Serialize(
new GetLatestSourceCodeVersionDto { Name = name, IncludePreReleases = includePreReleases }
),
Encoding.UTF8,
MimeTypes.Application.Json
),
CancellationTokenProvider.Token
);
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
var result = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<GetVersionResultDto>(result).Version;
}
}
@ -164,32 +159,25 @@ namespace Volo.Abp.Cli.ProjectBuilding
private async Task<string> GetTemplateNugetVersionAsync(string name, string type, string version)
{
var url = $"{CliUrls.WwwAbpIo}api/download/{type}/get-nuget-version/";
try
{
using (var client = new CliHttpClient(TimeSpan.FromMinutes(10)))
{
var response = await client.PostAsync(
url,
new StringContent(
JsonSerializer.Serialize(
new GetTemplateNugetVersionDto { Name = name, Version = version}
),
Encoding.UTF8,
MimeTypes.Application.Json
),
CancellationTokenProvider.Token
);
var url = $"{CliUrls.WwwAbpIo}api/download/{type}/get-nuget-version/";
var client = _cliHttpClientFactory.CreateClient();
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
var stringContent = new StringContent(
JsonSerializer.Serialize(new GetTemplateNugetVersionDto { Name = name, Version = version }),
Encoding.UTF8,
MimeTypes.Application.Json
);
using (var response = await client.PostAsync(url, stringContent, _cliHttpClientFactory.GetCancellationToken(TimeSpan.FromMinutes(10))))
{
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
var result = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<GetVersionResultDto>(result).Version;
}
}
catch (Exception ex)
catch (Exception)
{
return null;
}
@ -199,38 +187,39 @@ namespace Volo.Abp.Cli.ProjectBuilding
{
var url = $"{CliUrls.WwwAbpIo}api/download/{input.Type}/";
HttpResponseMessage responseMessage = null;
try
{
using (var client = new CliHttpClient(TimeSpan.FromMinutes(10)))
{
HttpResponseMessage responseMessage;
var client = _cliHttpClientFactory.CreateClient();
if (input.TemplateSource.IsNullOrWhiteSpace())
{
responseMessage = await client.PostAsync(
url,
new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, MimeTypes.Application.Json),
CancellationTokenProvider.Token
);
}
else
{
responseMessage = await client.GetAsync(input.TemplateSource, CancellationTokenProvider.Token);
}
if (input.TemplateSource.IsNullOrWhiteSpace())
{
responseMessage = await client.PostAsync(
url,
new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, MimeTypes.Application.Json),
_cliHttpClientFactory.GetCancellationToken(TimeSpan.FromMinutes(10))
);
}
else
{
responseMessage = await client.GetAsync(input.TemplateSource, _cliHttpClientFactory.GetCancellationToken());
}
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(responseMessage);
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(responseMessage);
var resultAsBytes = await responseMessage.Content.ReadAsByteArrayAsync();
responseMessage.Dispose();
return await responseMessage.Content.ReadAsByteArrayAsync();
}
return resultAsBytes;
}
catch (Exception ex)
{
Console.WriteLine("Error occured while downloading source-code from {0} : {1}", url, ex.Message);
Console.WriteLine("Error occured while downloading source-code from {0} : {1}{2}{3}", url, responseMessage?.ToString(), Environment.NewLine, ex.Message);
throw;
}
}
private bool IsNetworkSource(string source)
private static bool IsNetworkSource(string source)
{
return source.ToLower().StartsWith("http");
}

40
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Analyticses/CliAnalyticsCollect.cs

@ -18,15 +18,18 @@ namespace Volo.Abp.Cli.ProjectBuilding.Analyticses
private readonly IJsonSerializer _jsonSerializer;
private readonly ILogger<CliAnalyticsCollect> _logger;
private readonly IRemoteServiceExceptionHandler _remoteServiceExceptionHandler;
private readonly CliHttpClientFactory _cliHttpClientFactory;
public CliAnalyticsCollect(
ICancellationTokenProvider cancellationTokenProvider,
IJsonSerializer jsonSerializer,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler)
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
CliHttpClientFactory cliHttpClientFactory)
{
_cancellationTokenProvider = cancellationTokenProvider;
_jsonSerializer = jsonSerializer;
_remoteServiceExceptionHandler = remoteServiceExceptionHandler;
_cliHttpClientFactory = cliHttpClientFactory;
_logger = NullLogger<CliAnalyticsCollect>.Instance;
}
@ -34,32 +37,31 @@ namespace Volo.Abp.Cli.ProjectBuilding.Analyticses
{
var postData = _jsonSerializer.Serialize(input);
var url = $"{CliUrls.WwwAbpIo}api/clianalytics/collect";
try
{
using (var client = new CliHttpClient())
{
var responseMessage = await client.PostAsync(
url,
new StringContent(postData, Encoding.UTF8, MimeTypes.Application.Json),
_cancellationTokenProvider.Token
);
var client = _cliHttpClientFactory.CreateClient();
if (!responseMessage.IsSuccessStatusCode)
{
var exceptionMessage = "Remote server returns '" + (int)responseMessage.StatusCode + "-" + responseMessage.ReasonPhrase + "'. ";
var remoteServiceErrorMessage = await _remoteServiceExceptionHandler.GetAbpRemoteServiceErrorAsync(responseMessage);
var responseMessage = await client.PostAsync(
url,
new StringContent(postData, Encoding.UTF8, MimeTypes.Application.Json),
_cancellationTokenProvider.Token
);
if (remoteServiceErrorMessage != null)
{
exceptionMessage += remoteServiceErrorMessage;
}
if (!responseMessage.IsSuccessStatusCode)
{
var exceptionMessage = "Remote server returns '" + (int)responseMessage.StatusCode + "-" + responseMessage.ReasonPhrase + "'. ";
var remoteServiceErrorMessage = await _remoteServiceExceptionHandler.GetAbpRemoteServiceErrorAsync(responseMessage);
_logger.LogInformation(exceptionMessage);
if (remoteServiceErrorMessage != null)
{
exceptionMessage += remoteServiceErrorMessage;
}
_logger.LogInformation(exceptionMessage);
}
}
catch (Exception ex)
catch (Exception)
{
// ignored
}

2
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/ModuleInfo.cs

@ -23,5 +23,7 @@
public bool MvcUi { get; set; }
public bool BlazorUi { get; set; }
public bool IsFreeToActiveLicenseOwners { get; set; }
}
}

2
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/SolutionRenameStep.cs

@ -55,11 +55,13 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
{
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder, _companyName);
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder.ToCamelCase(), _companyName.ToCamelCase());
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder.ToKebabCase(), _companyName.ToKebabCase());
}
else
{
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder + "." + _projectNamePlaceHolder, _projectNamePlaceHolder);
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder.ToCamelCase() + "." + _projectNamePlaceHolder.ToCamelCase(), _projectNamePlaceHolder.ToCamelCase());
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder.ToKebabCase() + "/" + _projectNamePlaceHolder.ToKebabCase(), _projectNamePlaceHolder.ToKebabCase());
}
}

25
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/ModuleInfoProvider.cs

@ -16,14 +16,18 @@ namespace Volo.Abp.Cli.ProjectBuilding
public ICancellationTokenProvider CancellationTokenProvider { get; }
public IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
private readonly CliHttpClientFactory _cliHttpClientFactory;
public ModuleInfoProvider(
IJsonSerializer jsonSerializer,
ICancellationTokenProvider cancellationTokenProvider,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler)
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
CliHttpClientFactory cliHttpClientFactory)
{
JsonSerializer = jsonSerializer;
CancellationTokenProvider = cancellationTokenProvider;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
_cliHttpClientFactory = cliHttpClientFactory;
}
public async Task<ModuleInfo> GetAsync(string name)
@ -47,17 +51,16 @@ namespace Volo.Abp.Cli.ProjectBuilding
private async Task<List<ModuleInfo>> GetModuleListInternalAsync()
{
using (var client = new CliHttpClient())
var client = _cliHttpClientFactory.CreateClient();
using (var responseMessage = await client.GetAsync(
$"{CliUrls.WwwAbpIo}api/download/modules/",
CancellationTokenProvider.Token
))
{
using (var responseMessage = await client.GetAsync(
$"{CliUrls.WwwAbpIo}api/download/modules/",
CancellationTokenProvider.Token
))
{
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(responseMessage);
var result = await responseMessage.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<ModuleInfo>>(result);
}
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(responseMessage);
var result = await responseMessage.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<ModuleInfo>>(result);
}
}
}

24
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/TemplateInfoProvider.cs

@ -24,13 +24,17 @@ namespace Volo.Abp.Cli.ProjectBuilding
public IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
public AuthService AuthService { get; }
private readonly CliHttpClientFactory _cliHttpClientFactory;
public TemplateInfoProvider(ICancellationTokenProvider cancellationTokenProvider,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
AuthService authService)
AuthService authService,
CliHttpClientFactory cliHttpClientFactory)
{
CancellationTokenProvider = cancellationTokenProvider;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
AuthService = authService;
_cliHttpClientFactory = cliHttpClientFactory;
Logger = NullLogger<TemplateInfoProvider>.Instance;
}
@ -76,21 +80,19 @@ namespace Volo.Abp.Cli.ProjectBuilding
try
{
var url = $"{CliUrls.WwwAbpIo}api/license/check-user";
var client = _cliHttpClientFactory.CreateClient();
using (var client = new CliHttpClient())
using (var response = await client.GetHttpResponseMessageWithRetryAsync(url, CancellationTokenProvider.Token, Logger))
{
using (var response = await client.GetHttpResponseMessageWithRetryAsync(url, CancellationTokenProvider.Token, Logger))
if (!response.IsSuccessStatusCode)
{
if (!response.IsSuccessStatusCode)
{
throw new Exception($"ERROR: Remote server returns '{response.StatusCode}'");
}
throw new Exception($"ERROR: Remote server returns '{response.StatusCode}'");
}
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
await RemoteServiceExceptionHandler.EnsureSuccessfulHttpResponseAsync(response);
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<bool>(responseContent);
}
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<bool>(responseContent);
}
}
catch (Exception)

28
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/MyGetPackageListFinder.cs

@ -6,17 +6,23 @@ using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using Volo.Abp.Cli.Http;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Threading;
namespace Volo.Abp.Cli.ProjectModification
{
public class MyGetPackageListFinder : ISingletonDependency
{
private MyGetApiResponse _response;
public ILogger<MyGetPackageListFinder> Logger { get; set; }
public MyGetPackageListFinder()
private MyGetApiResponse _response;
private readonly CliHttpClientFactory _cliHttpClientFactory;
protected ICancellationTokenProvider CancellationTokenProvider { get; }
public MyGetPackageListFinder(CliHttpClientFactory cliHttpClientFactory,
ICancellationTokenProvider cancellationTokenProvider)
{
_cliHttpClientFactory = cliHttpClientFactory;
CancellationTokenProvider = cancellationTokenProvider;
Logger = NullLogger<MyGetPackageListFinder>.Instance;
}
@ -29,18 +35,20 @@ namespace Volo.Abp.Cli.ProjectModification
try
{
using (var client = new CliHttpClient(TimeSpan.FromMinutes(10)))
var client = _cliHttpClientFactory.CreateClient();
using (var responseMessage = await client.GetAsync(
$"{CliUrls.WwwAbpIo}api/myget/packages/",
_cliHttpClientFactory.GetCancellationToken(TimeSpan.FromMinutes(10))))
{
var responseMessage = await client.GetAsync(
$"{CliUrls.WwwAbpIo}api/myget/packages/"
_response = JsonConvert.DeserializeObject<MyGetApiResponse>(
Encoding.Default.GetString(await responseMessage.Content.ReadAsByteArrayAsync())
);
_response = JsonConvert.DeserializeObject<MyGetApiResponse>(Encoding.Default.GetString(await responseMessage.Content.ReadAsByteArrayAsync()));
}
}
catch (Exception)
catch (Exception ex)
{
Logger.LogError("Unable to get latest preview version.");
Logger.LogError("Unable to get latest preview version. Error: " + ex.Message);
throw;
}

23
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/NpmPackagesUpdater.cs

@ -27,15 +27,18 @@ namespace Volo.Abp.Cli.ProjectModification
private readonly PackageJsonFileFinder _packageJsonFileFinder;
private readonly NpmGlobalPackagesChecker _npmGlobalPackagesChecker;
private readonly Dictionary<string, string> _fileVersionStorage = new Dictionary<string, string>();
private readonly CliHttpClientFactory _cliHttpClientFactory;
public NpmPackagesUpdater(
PackageJsonFileFinder packageJsonFileFinder,
NpmGlobalPackagesChecker npmGlobalPackagesChecker,
ICancellationTokenProvider cancellationTokenProvider)
ICancellationTokenProvider cancellationTokenProvider,
CliHttpClientFactory cliHttpClientFactory)
{
_packageJsonFileFinder = packageJsonFileFinder;
_npmGlobalPackagesChecker = npmGlobalPackagesChecker;
CancellationTokenProvider = cancellationTokenProvider;
_cliHttpClientFactory = cliHttpClientFactory;
Logger = NullLogger<NpmPackagesUpdater>.Instance;
}
@ -151,16 +154,14 @@ namespace Volo.Abp.Cli.ProjectModification
{
try
{
using (var client = new CliHttpClient(TimeSpan.FromMinutes(1)))
var client = _cliHttpClientFactory.CreateClient();
using (var response = await client.GetHttpResponseMessageWithRetryAsync(
url: $"{CliUrls.WwwAbpIo}api/myget/apikey/",
cancellationToken: CancellationTokenProvider.Token,
logger: Logger
))
{
using (var response = await client.GetHttpResponseMessageWithRetryAsync(
url: $"{CliUrls.WwwAbpIo}api/myget/apikey/",
cancellationToken: CancellationTokenProvider.Token,
logger: Logger
))
{
return Encoding.Default.GetString(await response.Content.ReadAsByteArrayAsync());
}
return Encoding.Default.GetString(await response.Content.ReadAsByteArrayAsync());
}
}
catch (Exception)
@ -356,7 +357,7 @@ namespace Volo.Abp.Cli.ProjectModification
protected virtual string ExtractVersions(string output)
{
var arrayStart = output.IndexOf('[');
return output.Substring(arrayStart, output.IndexOf(']') - arrayStart + 1);
return output.Substring(arrayStart, output.IndexOf(']') - arrayStart + 1);
}
protected virtual bool SpecifiedVersionExists(string version, JProperty package)

3
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/NuGetPackageTarget.cs

@ -13,6 +13,7 @@
EntityFrameworkCore = 8,
MongoDB = 9,
SignalR = 10,
Blazor = 11
Blazor = 11,
IdentityServer = 12
}
}

2
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/ProjectFinder.cs

@ -22,6 +22,8 @@ namespace Volo.Abp.Cli.ProjectModification
{
case NuGetPackageTarget.Web:
return FindProjectEndsWith(projectFiles, assemblyNames, ".Web");
case NuGetPackageTarget.IdentityServer:
return FindProjectEndsWith(projectFiles, assemblyNames, ".IdentityServer");
case NuGetPackageTarget.EntityFrameworkCore:
return FindProjectEndsWith(projectFiles, assemblyNames, ".EntityFrameworkCore");
case NuGetPackageTarget.MongoDB:

21
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/ProjectNugetPackageAdder.cs

@ -21,13 +21,15 @@ namespace Volo.Abp.Cli.ProjectModification
public class ProjectNugetPackageAdder : ITransientDependency
{
public ILogger<ProjectNugetPackageAdder> Logger { get; set; }
public BundleCommand BundleCommand { get; }
protected IJsonSerializer JsonSerializer { get; }
protected ProjectNpmPackageAdder NpmPackageAdder { get; }
protected DerivedClassFinder ModuleClassFinder { get; }
protected ModuleClassDependcyAdder ModuleClassDependcyAdder { get; }
protected IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
public BundleCommand BundleCommand { get; }
private readonly CliHttpClientFactory _cliHttpClientFactory;
public ProjectNugetPackageAdder(
IJsonSerializer jsonSerializer,
@ -35,7 +37,8 @@ namespace Volo.Abp.Cli.ProjectModification
DerivedClassFinder moduleClassFinder,
ModuleClassDependcyAdder moduleClassDependcyAdder,
IRemoteServiceExceptionHandler remoteServiceExceptionHandler,
BundleCommand bundleCommand)
BundleCommand bundleCommand,
CliHttpClientFactory cliHttpClientFactory)
{
JsonSerializer = jsonSerializer;
NpmPackageAdder = npmPackageAdder;
@ -43,6 +46,7 @@ namespace Volo.Abp.Cli.ProjectModification
ModuleClassDependcyAdder = moduleClassDependcyAdder;
RemoteServiceExceptionHandler = remoteServiceExceptionHandler;
BundleCommand = bundleCommand;
_cliHttpClientFactory = cliHttpClientFactory;
Logger = NullLogger<ProjectNugetPackageAdder>.Instance;
}
@ -121,7 +125,7 @@ namespace Volo.Abp.Cli.ProjectModification
private Task AddToCsprojManuallyAsync(string projectFile, NugetPackageInfo package, string version = null)
{
var projectFileContent = File.ReadAllText(projectFile);
var doc = new XmlDocument() {PreserveWhitespace = true};
var doc = new XmlDocument() { PreserveWhitespace = true };
doc.Load(StreamHelper.GenerateStreamFromString(projectFileContent));
var itemGroupNodes = doc.SelectNodes("/Project/ItemGroup");
@ -162,7 +166,7 @@ namespace Volo.Abp.Cli.ProjectModification
private string GetAbpVersionOrNull(string projectFileContent)
{
var doc = new XmlDocument() {PreserveWhitespace = true};
var doc = new XmlDocument() { PreserveWhitespace = true };
doc.Load(StreamHelper.GenerateStreamFromString(projectFileContent));
@ -173,12 +177,11 @@ namespace Volo.Abp.Cli.ProjectModification
protected virtual async Task<NugetPackageInfo> FindNugetPackageInfoAsync(string packageName)
{
using (var client = new CliHttpClient())
{
var url = $"{CliUrls.WwwAbpIo}api/app/nugetPackage/byName/?name=" + packageName;
var response = await client.GetAsync(url);
var url = $"{CliUrls.WwwAbpIo}api/app/nugetPackage/byName/?name=" + packageName;
var client = _cliHttpClientFactory.CreateClient();
using (var response = await client.GetAsync(url, _cliHttpClientFactory.GetCancellationToken()))
{
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.NotFound)

59
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/SolutionModuleAdder.cs

@ -7,7 +7,6 @@ using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Volo.Abp.Cli.Args;
using Volo.Abp.Cli.Bundling;
using Volo.Abp.Cli.Commands;
using Volo.Abp.Cli.Commands.Services;
using Volo.Abp.Cli.Http;
@ -22,6 +21,12 @@ namespace Volo.Abp.Cli.ProjectModification
public class SolutionModuleAdder : ITransientDependency
{
public ILogger<SolutionModuleAdder> Logger { get; set; }
public SourceCodeDownloadService SourceCodeDownloadService { get; }
public SolutionFileModifier SolutionFileModifier { get; }
public NugetPackageToLocalReferenceConverter NugetPackageToLocalReferenceConverter { get; }
public AngularModuleSourceCodeAdder AngularModuleSourceCodeAdder { get; }
public NewCommand NewCommand { get; }
public BundleCommand BundleCommand { get; }
protected IJsonSerializer JsonSerializer { get; }
protected ProjectNugetPackageAdder ProjectNugetPackageAdder { get; }
@ -31,12 +36,9 @@ namespace Volo.Abp.Cli.ProjectModification
protected ProjectNpmPackageAdder ProjectNpmPackageAdder { get; }
protected NpmGlobalPackagesChecker NpmGlobalPackagesChecker { get; }
protected IRemoteServiceExceptionHandler RemoteServiceExceptionHandler { get; }
public SourceCodeDownloadService SourceCodeDownloadService { get; }
public SolutionFileModifier SolutionFileModifier { get; }
public NugetPackageToLocalReferenceConverter NugetPackageToLocalReferenceConverter { get; }
public AngularModuleSourceCodeAdder AngularModuleSourceCodeAdder { get; }
public NewCommand NewCommand { get; }
public BundleCommand BundleCommand { get; }
private readonly CliHttpClientFactory _cliHttpClientFactory;
public SolutionModuleAdder(
IJsonSerializer jsonSerializer,
@ -52,7 +54,8 @@ namespace Volo.Abp.Cli.ProjectModification
NugetPackageToLocalReferenceConverter nugetPackageToLocalReferenceConverter,
AngularModuleSourceCodeAdder angularModuleSourceCodeAdder,
NewCommand newCommand,
BundleCommand bundleCommand)
BundleCommand bundleCommand,
CliHttpClientFactory cliHttpClientFactory)
{
JsonSerializer = jsonSerializer;
ProjectNugetPackageAdder = projectNugetPackageAdder;
@ -68,6 +71,7 @@ namespace Volo.Abp.Cli.ProjectModification
AngularModuleSourceCodeAdder = angularModuleSourceCodeAdder;
NewCommand = newCommand;
BundleCommand = bundleCommand;
_cliHttpClientFactory = cliHttpClientFactory;
Logger = NullLogger<SolutionModuleAdder>.Instance;
}
@ -131,7 +135,7 @@ namespace Volo.Abp.Cli.ProjectModification
{
var blazorProject = projectFiles.FirstOrDefault(f => f.EndsWith(".Blazor.csproj"));
if (blazorProject == null || !module.NugetPackages.Any(np=> np.Target == NuGetPackageTarget.Blazor))
if (blazorProject == null || !module.NugetPackages.Any(np => np.Target == NuGetPackageTarget.Blazor))
{
return;
}
@ -171,7 +175,7 @@ namespace Volo.Abp.Cli.ProjectModification
{
await RemoveProjectByTarget(module, moduleSolutionFile, NuGetPackageTarget.EntityFrameworkCore, isProjectTiered);
await RemoveProjectByPostFix(module, moduleSolutionFile, "test", ".EntityFrameworkCore.Tests");
await ChangeDomainTestReferenceToMongoDB(module, moduleSolutionFile);
ChangeDomainTestReferenceToMongoDB(module, moduleSolutionFile);
}
}
@ -211,7 +215,7 @@ namespace Volo.Abp.Cli.ProjectModification
return;
}
var projectFolderPath = Directory.GetDirectories(srcPath).FirstOrDefault(d=> d.EndsWith(postFix));
var projectFolderPath = Directory.GetDirectories(srcPath).FirstOrDefault(d => d.EndsWith(postFix));
if (projectFolderPath == null)
{
@ -226,7 +230,7 @@ namespace Volo.Abp.Cli.ProjectModification
}
}
private async Task ChangeDomainTestReferenceToMongoDB(ModuleWithMastersInfo module, string moduleSolutionFile)
private void ChangeDomainTestReferenceToMongoDB(ModuleWithMastersInfo module, string moduleSolutionFile)
{
var testPath = Path.Combine(Path.GetDirectoryName(moduleSolutionFile), "test");
@ -235,7 +239,7 @@ namespace Volo.Abp.Cli.ProjectModification
return;
}
var projectFolderPath = Directory.GetDirectories(testPath).FirstOrDefault(d=> d.EndsWith("Domain.Tests"));
var projectFolderPath = Directory.GetDirectories(testPath).FirstOrDefault(d => d.EndsWith("Domain.Tests"));
if (projectFolderPath == null)
{
@ -250,10 +254,10 @@ namespace Volo.Abp.Cli.ProjectModification
return;
}
File.WriteAllText(csprojFile, File.ReadAllText(csprojFile).Replace("EntityFrameworkCore","MongoDB"));
File.WriteAllText(csprojFile, File.ReadAllText(csprojFile).Replace("EntityFrameworkCore", "MongoDB"));
File.WriteAllText(moduleFile, File.ReadAllText(moduleFile)
.Replace(".EntityFrameworkCore;",".MongoDB;")
.Replace("EntityFrameworkCoreTestModule","MongoDbTestModule"));
.Replace(".EntityFrameworkCore;", ".MongoDB;")
.Replace("EntityFrameworkCoreTestModule", "MongoDbTestModule"));
}
private async Task AddAngularPackages(string solutionFilePath, ModuleWithMastersInfo module)
@ -355,9 +359,9 @@ namespace Volo.Abp.Cli.ProjectModification
);
}
await DeleteRedundantHostProjects(targetModuleFolder,"app");
await DeleteRedundantHostProjects(targetModuleFolder,"demo");
await DeleteRedundantHostProjects(targetModuleFolder,"host");
await DeleteRedundantHostProjects(targetModuleFolder, "app");
await DeleteRedundantHostProjects(targetModuleFolder, "demo");
await DeleteRedundantHostProjects(targetModuleFolder, "host");
if (module.MasterModuleInfos == null)
{
@ -501,7 +505,7 @@ namespace Volo.Abp.Cli.ProjectModification
}
}
protected virtual async Task RunMigrator(string[] projectFiles)
protected virtual void RunMigrator(string[] projectFiles)
{
var dbMigratorProject = projectFiles.FirstOrDefault(p => p.EndsWith(".DbMigrator.csproj"));
@ -516,15 +520,14 @@ namespace Volo.Abp.Cli.ProjectModification
{
if (newTemplate || newProTemplate)
{
return await GetEmptyModuleProjectInfoAsync(moduleName, newProTemplate);
return GetEmptyModuleProjectInfo(moduleName, newProTemplate);
}
using (var client = new CliHttpClient())
{
var url = $"{CliUrls.WwwAbpIo}api/app/module/byNameWithDetails/?name=" + moduleName;
var response = await client.GetAsync(url);
var url = $"{CliUrls.WwwAbpIo}api/app/module/byNameWithDetails/?name=" + moduleName;
var client = _cliHttpClientFactory.CreateClient();
using (var response = await client.GetAsync(url, _cliHttpClientFactory.GetCancellationToken()))
{
if (!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.NotFound)
@ -540,7 +543,7 @@ namespace Volo.Abp.Cli.ProjectModification
}
}
private async Task<ModuleWithMastersInfo> GetEmptyModuleProjectInfoAsync(string moduleName,
private ModuleWithMastersInfo GetEmptyModuleProjectInfo(string moduleName,
bool newProTemplate = false)
{
var module = new ModuleWithMastersInfo
@ -625,7 +628,7 @@ namespace Volo.Abp.Cli.ProjectModification
protected virtual async Task<bool> IsProjectTiered(string[] projectFiles)
{
return projectFiles.Select(ProjectFileNameHelper.GetAssemblyNameFromProjectPath)
.Any(p =>p.EndsWith(".HttpApi.Host"))
.Any(p => p.EndsWith(".HttpApi.Host"))
&& projectFiles.Select(ProjectFileNameHelper.GetAssemblyNameFromProjectPath)
.Any(p => p.EndsWith(".IdentityServer"));
}

23
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Utils/CmdHelper.cs

@ -1,4 +1,5 @@
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace Volo.Abp.Cli.Utils
@ -103,14 +104,28 @@ namespace Volo.Abp.Cli.Utils
public static string GetFileName()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
//Windows
return "cmd.exe";
}
//Linux or OSX
if (File.Exists("/bin/bash"))
{
//TODO: Test this. it should work for both operation systems.
return "/bin/bash";
}
//Windows default.
return "cmd.exe";
if (File.Exists("/bin/sh"))
{
return "/bin/sh"; //some Linux distributions like Alpine doesn't have bash
}
throw new AbpException($"Cannot determine shell command for this OS! " +
$"Running on OS: {System.Runtime.InteropServices.RuntimeInformation.OSDescription} | " +
$"OS Architecture: {System.Runtime.InteropServices.RuntimeInformation.OSArchitecture} | " +
$"Framework: {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription} | " +
$"Process Architecture{System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}");
}
}
}

8
framework/src/Volo.Abp.Core/Volo/Abp/Modularity/PlugIns/FolderPlugInSource.cs

@ -18,7 +18,7 @@ namespace Volo.Abp.Modularity.PlugIns
public Func<string, bool> Filter { get; set; }
public FolderPlugInSource(
[NotNull] string folder,
[NotNull] string folder,
SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
Check.NotNull(folder, nameof(folder));
@ -52,7 +52,7 @@ namespace Volo.Abp.Modularity.PlugIns
return modules.ToArray();
}
private IEnumerable<Assembly> GetAssemblies()
private List<Assembly> GetAssemblies()
{
var assemblyFiles = AssemblyHelper.GetAssemblyFiles(Folder, SearchOption);
@ -61,7 +61,7 @@ namespace Volo.Abp.Modularity.PlugIns
assemblyFiles = assemblyFiles.Where(Filter);
}
return assemblyFiles.Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);
return assemblyFiles.Select(AssemblyLoadContext.Default.LoadFromAssemblyPath).ToList();
}
}
}
}

9
framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDataModule.cs

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Volo.Abp.Modularity;
using Volo.Abp.ObjectExtending;
using Volo.Abp.Uow;
@ -27,6 +28,14 @@ namespace Volo.Abp.Data
context.Services.AddSingleton(typeof(IDataFilter<>), typeof(DataFilter<>));
}
public override void PostConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpDbConnectionOptions>(options =>
{
options.Databases.RefreshIndexes();
});
}
private static void AutoAddDataSeedContributors(IServiceCollection services)
{
var contributors = new List<Type>();

28
framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDatabaseInfo.cs

@ -0,0 +1,28 @@
using System.Collections.Generic;
namespace Volo.Abp.Data
{
public class AbpDatabaseInfo
{
public string DatabaseName { get; set; }
/// <summary>
/// List of connection names mapped to this database.
/// </summary>
public HashSet<string> MappedConnections { get; }
/// <summary>
/// Is this database used by tenants. Set this to true if this database
/// can't owned by tenants.
///
/// Default: true.
/// </summary>
public bool IsUsedByTenants { get; set; } = true;
internal AbpDatabaseInfo(string databaseName)
{
DatabaseName = databaseName;
MappedConnections = new HashSet<string>();
}
}
}

58
framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDatabaseInfoDictionary.cs

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Volo.Abp.Data
{
public class AbpDatabaseInfoDictionary : Dictionary<string, AbpDatabaseInfo>
{
private Dictionary<string, AbpDatabaseInfo> ConnectionIndex { get; set; }
public AbpDatabaseInfoDictionary()
{
ConnectionIndex = new Dictionary<string, AbpDatabaseInfo>();
}
[CanBeNull]
public AbpDatabaseInfo GetMappedDatabaseOrNull(string connectionStringName)
{
return ConnectionIndex.GetOrDefault(connectionStringName);
}
public AbpDatabaseInfoDictionary Configure(string databaseName, Action<AbpDatabaseInfo> configureAction)
{
var databaseInfo = this.GetOrAdd(
databaseName,
() => new AbpDatabaseInfo(databaseName)
);
configureAction(databaseInfo);
return this;
}
/// <summary>
/// This method should be called if this dictionary changes.
/// It refreshes indexes for quick access to the connection informations.
/// </summary>
public void RefreshIndexes()
{
ConnectionIndex = new Dictionary<string, AbpDatabaseInfo>();
foreach (var databaseInfo in Values)
{
foreach (var mappedConnection in databaseInfo.MappedConnections)
{
if (ConnectionIndex.ContainsKey(mappedConnection))
{
throw new AbpException(
$"A connection name can not map to multiple databases: {mappedConnection}."
);
}
ConnectionIndex[mappedConnection] = databaseInfo;
}
}
}
}
}

44
framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDbConnectionOptions.cs

@ -1,12 +1,54 @@
namespace Volo.Abp.Data
using System;
using System.Collections.Generic;
namespace Volo.Abp.Data
{
public class AbpDbConnectionOptions
{
public ConnectionStrings ConnectionStrings { get; set; }
public AbpDatabaseInfoDictionary Databases { get; set; }
public AbpDbConnectionOptions()
{
ConnectionStrings = new ConnectionStrings();
Databases = new AbpDatabaseInfoDictionary();
}
public string GetConnectionStringOrNull(
string connectionStringName,
bool fallbackToDatabaseMappings = true,
bool fallbackToDefault = true)
{
var connectionString = ConnectionStrings.GetOrDefault(connectionStringName);
if (!connectionString.IsNullOrEmpty())
{
return connectionString;
}
if (fallbackToDatabaseMappings)
{
var database = Databases.GetMappedDatabaseOrNull(connectionStringName);
if (database != null)
{
connectionString = ConnectionStrings.GetOrDefault(database.DatabaseName);
if (!connectionString.IsNullOrEmpty())
{
return connectionString;
}
}
}
if (fallbackToDefault)
{
connectionString = ConnectionStrings.Default;
if (!connectionString.IsNullOrWhiteSpace())
{
return connectionString;
}
}
return null;
}
}
}

25
framework/src/Volo.Abp.Data/Volo/Abp/Data/DefaultConnectionStringResolver.cs

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
@ -10,7 +9,8 @@ namespace Volo.Abp.Data
{
protected AbpDbConnectionOptions Options { get; }
public DefaultConnectionStringResolver(IOptionsSnapshot<AbpDbConnectionOptions> options)
public DefaultConnectionStringResolver(
IOptionsSnapshot<AbpDbConnectionOptions> options)
{
Options = options.Value;
}
@ -28,18 +28,19 @@ namespace Volo.Abp.Data
private string ResolveInternal(string connectionStringName)
{
//Get module specific value if provided
if (!connectionStringName.IsNullOrEmpty())
if (connectionStringName == null)
{
var moduleConnString = Options.ConnectionStrings.GetOrDefault(connectionStringName);
if (!moduleConnString.IsNullOrEmpty())
{
return moduleConnString;
}
return Options.ConnectionStrings.Default;
}
var connectionString = Options.GetConnectionStringOrNull(connectionStringName);
if (!connectionString.IsNullOrEmpty())
{
return connectionString;
}
//Get default value
return Options.ConnectionStrings.Default;
return null;
}
}
}
}

38
framework/src/Volo.Abp.Ddd.Domain/Microsoft/Extensions/DependencyInjection/ServiceCollectionRepositoryExtensions.cs

@ -7,32 +7,36 @@ namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionRepositoryExtensions
{
public static IServiceCollection AddDefaultRepository(this IServiceCollection services, Type entityType, Type repositoryImplementationType)
public static IServiceCollection AddDefaultRepository(
this IServiceCollection services,
Type entityType,
Type repositoryImplementationType,
bool replaceExisting = false)
{
//IReadOnlyBasicRepository<TEntity>
var readOnlyBasicRepositoryInterface = typeof(IReadOnlyBasicRepository<>).MakeGenericType(entityType);
if (readOnlyBasicRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(readOnlyBasicRepositoryInterface, repositoryImplementationType);
RegisterService(services, readOnlyBasicRepositoryInterface, repositoryImplementationType, replaceExisting);
//IReadOnlyRepository<TEntity>
var readOnlyRepositoryInterface = typeof(IReadOnlyRepository<>).MakeGenericType(entityType);
if (readOnlyRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(readOnlyRepositoryInterface, repositoryImplementationType);
RegisterService(services, readOnlyRepositoryInterface, repositoryImplementationType, replaceExisting);
}
//IBasicRepository<TEntity>
var basicRepositoryInterface = typeof(IBasicRepository<>).MakeGenericType(entityType);
if (basicRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(basicRepositoryInterface, repositoryImplementationType);
RegisterService(services, basicRepositoryInterface, repositoryImplementationType, replaceExisting);
//IRepository<TEntity>
var repositoryInterface = typeof(IRepository<>).MakeGenericType(entityType);
if (repositoryInterface.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(repositoryInterface, repositoryImplementationType);
RegisterService(services, repositoryInterface, repositoryImplementationType, replaceExisting);
}
}
}
@ -44,26 +48,26 @@ namespace Microsoft.Extensions.DependencyInjection
var readOnlyBasicRepositoryInterfaceWithPk = typeof(IReadOnlyBasicRepository<,>).MakeGenericType(entityType, primaryKeyType);
if (readOnlyBasicRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(readOnlyBasicRepositoryInterfaceWithPk, repositoryImplementationType);
RegisterService(services, readOnlyBasicRepositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);
//IReadOnlyRepository<TEntity, TKey>
var readOnlyRepositoryInterfaceWithPk = typeof(IReadOnlyRepository<,>).MakeGenericType(entityType, primaryKeyType);
if (readOnlyRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(readOnlyRepositoryInterfaceWithPk, repositoryImplementationType);
RegisterService(services, readOnlyRepositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);
}
//IBasicRepository<TEntity, TKey>
var basicRepositoryInterfaceWithPk = typeof(IBasicRepository<,>).MakeGenericType(entityType, primaryKeyType);
if (basicRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(basicRepositoryInterfaceWithPk, repositoryImplementationType);
RegisterService(services, basicRepositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);
//IRepository<TEntity, TKey>
var repositoryInterfaceWithPk = typeof(IRepository<,>).MakeGenericType(entityType, primaryKeyType);
if (repositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
{
services.TryAddTransient(repositoryInterfaceWithPk, repositoryImplementationType);
RegisterService(services, repositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);
}
}
}
@ -71,5 +75,21 @@ namespace Microsoft.Extensions.DependencyInjection
return services;
}
private static void RegisterService(
IServiceCollection services,
Type serviceType,
Type implementationType,
bool replaceExisting)
{
if (replaceExisting)
{
services.Replace(ServiceDescriptor.Transient(serviceType, implementationType));
}
else
{
services.TryAddTransient(serviceType, implementationType);
}
}
}
}

20
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/DependencyInjection/AbpCommonDbContextRegistrationOptions.cs

@ -117,25 +117,5 @@ namespace Volo.Abp.DependencyInjection
CustomRepositories[entityType] = repositoryType;
}
public bool ShouldRegisterDefaultRepositoryFor(Type entityType)
{
if (!RegisterDefaultRepositories)
{
return false;
}
if (CustomRepositories.ContainsKey(entityType))
{
return false;
}
if (!IncludeAllEntitiesForDefaultRepositories && !typeof(IAggregateRoot).IsAssignableFrom(entityType))
{
return false;
}
return true;
}
}
}

13
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/EntityHelper.cs

@ -1,7 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
@ -15,6 +13,17 @@ namespace Volo.Abp.Domain.Entities
/// </summary>
public static class EntityHelper
{
public static bool IsMultiTenant<TEntity>()
where TEntity : IEntity
{
return IsMultiTenant(typeof(TEntity));
}
public static bool IsMultiTenant(Type type)
{
return typeof(IMultiTenant).IsAssignableFrom(type);
}
public static bool EntityEquals(IEntity entity1, IEntity entity2)
{
if (entity1 == null || entity2 == null)

3
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/AbpRepositoryConventionalRegistrar.cs

@ -6,6 +6,9 @@ using Volo.Abp.DependencyInjection;
namespace Volo.Abp.Domain.Repositories
{
/* Repositories are not injected by class by default.
* This class specializes repository registration to apply this rule.
*/
public class AbpRepositoryConventionalRegistrar : DefaultConventionalRegistrar
{
public static bool ExposeRepositoryClasses { get; set; }

17
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/IRepository.cs

@ -20,8 +20,10 @@ namespace Volo.Abp.Domain.Repositories
{
/// <summary>
/// Get a single entity by the given <paramref name="predicate"/>.
/// It returns null if no entity with the given <paramref name="predicate"/>.
/// <para>
/// It returns null if there is no entity with the given <paramref name="predicate"/>.
/// It throws <see cref="InvalidOperationException"/> if there are multiple entities with the given <paramref name="predicate"/>.
/// </para>
/// </summary>
/// <param name="predicate">A condition to find the entity</param>
/// <param name="includeDetails">Set true to include all children of this entity</param>
@ -34,8 +36,10 @@ namespace Volo.Abp.Domain.Repositories
/// <summary>
/// Get a single entity by the given <paramref name="predicate"/>.
/// <para>
/// It throws <see cref="EntityNotFoundException"/> if there is no entity with the given <paramref name="predicate"/>.
/// It throws <see cref="InvalidOperationException"/> if there are multiple entities with the given <paramref name="predicate"/>.
/// </para>
/// </summary>
/// <param name="predicate">A condition to filter entities</param>
/// <param name="includeDetails">Set true to include all children of this entity</param>
@ -47,10 +51,11 @@ namespace Volo.Abp.Domain.Repositories
);
/// <summary>
/// Deletes many entities by function.
/// Notice that: All entities fits to given predicate are retrieved and deleted.
/// This may cause major performance problems if there are too many entities with
/// given predicate.
/// Deletes many entities by the given <paramref name="predicate"/>.
/// <para>
/// Please note: This may cause major performance problems if there are too many entities returned for a
/// given predicate and the database provider doesn't have a way to efficiently delete many entities.
/// </para>
/// </summary>
/// <param name="predicate">A condition to filter entities</param>
/// <param name="autoSave">
@ -69,4 +74,4 @@ namespace Volo.Abp.Domain.Repositories
where TEntity : class, IEntity<TKey>
{
}
}
}

2
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryRegistrarBase.cs

@ -20,7 +20,7 @@ namespace Volo.Abp.Domain.Repositories
{
foreach (var customRepository in Options.CustomRepositories)
{
Options.Services.AddDefaultRepository(customRepository.Key, customRepository.Value);
Options.Services.AddDefaultRepository(customRepository.Key, customRepository.Value, replaceExisting: true);
}
if (Options.RegisterDefaultRepositories)

2
framework/src/Volo.Abp.EntityFrameworkCore.Oracle/Volo.Abp.EntityFrameworkCore.Oracle.csproj

@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
<!--<PackageReference Include="Oracle.EntityFrameworkCore" Version="3.19.80" />-->
<PackageReference Include="Oracle.EntityFrameworkCore" Version="5.21.1" />
</ItemGroup>
</Project>

59
framework/src/Volo.Abp.EntityFrameworkCore.Oracle/Volo/Abp/EntityFrameworkCore/AbpDbContextConfigurationContextOracleExtensions.cs

@ -1,26 +1,33 @@
// using JetBrains.Annotations;
// using Microsoft.EntityFrameworkCore;
// using System;
// using Oracle.EntityFrameworkCore.Infrastructure;
// using Volo.Abp.EntityFrameworkCore.DependencyInjection;
//
// namespace Volo.Abp.EntityFrameworkCore
// {
// public static class AbpDbContextConfigurationContextOracleExtensions
// {
// public static DbContextOptionsBuilder UseOracle(
// [NotNull] this AbpDbContextConfigurationContext context,
// [CanBeNull] Action<OracleDbContextOptionsBuilder> oracleOptionsAction = null)
// {
// TODO: UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
// if (context.ExistingConnection != null)
// {
// return context.DbContextOptions.UseOracle(context.ExistingConnection, oracleOptionsAction);
// }
// else
// {
// return context.DbContextOptions.UseOracle(context.ConnectionString, oracleOptionsAction);
// }
// }
// }
// }
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using System;
using Oracle.EntityFrameworkCore.Infrastructure;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
namespace Volo.Abp.EntityFrameworkCore
{
public static class AbpDbContextConfigurationContextOracleExtensions
{
public static DbContextOptionsBuilder UseOracle(
[NotNull] this AbpDbContextConfigurationContext context,
[CanBeNull] Action<OracleDbContextOptionsBuilder> oracleOptionsAction = null)
{
if (context.ExistingConnection != null)
{
return context.DbContextOptions.UseOracle(context.ExistingConnection, optionsBuilder =>
{
optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
oracleOptionsAction?.Invoke(optionsBuilder);
});
}
else
{
return context.DbContextOptions.UseOracle(context.ConnectionString, optionsBuilder =>
{
optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
oracleOptionsAction?.Invoke(optionsBuilder);
});
}
}
}
}

60
framework/src/Volo.Abp.EntityFrameworkCore.Oracle/Volo/Abp/EntityFrameworkCore/AbpDbContextOptionsOracleExtensions.cs

@ -1,30 +1,30 @@
// using JetBrains.Annotations;
// using System;
// using Oracle.EntityFrameworkCore.Infrastructure;
//
// namespace Volo.Abp.EntityFrameworkCore
// {
// public static class AbpDbContextOptionsOracleExtensions
// {
// public static void UseOracle(
// [NotNull] this AbpDbContextOptions options,
// [CanBeNull] Action<OracleDbContextOptionsBuilder> oracleOptionsAction = null)
// {
// options.Configure(context =>
// {
// context.UseOracle(oracleOptionsAction);
// });
// }
//
// public static void UseOracle<TDbContext>(
// [NotNull] this AbpDbContextOptions options,
// [CanBeNull] Action<OracleDbContextOptionsBuilder> oracleOptionsAction = null)
// where TDbContext : AbpDbContext<TDbContext>
// {
// options.Configure<TDbContext>(context =>
// {
// context.UseOracle(oracleOptionsAction);
// });
// }
// }
// }
using JetBrains.Annotations;
using System;
using Oracle.EntityFrameworkCore.Infrastructure;
namespace Volo.Abp.EntityFrameworkCore
{
public static class AbpDbContextOptionsOracleExtensions
{
public static void UseOracle(
[NotNull] this AbpDbContextOptions options,
[CanBeNull] Action<OracleDbContextOptionsBuilder> oracleOptionsAction = null)
{
options.Configure(context =>
{
context.UseOracle(oracleOptionsAction);
});
}
public static void UseOracle<TDbContext>(
[NotNull] this AbpDbContextOptions options,
[CanBeNull] Action<OracleDbContextOptionsBuilder> oracleOptionsAction = null)
where TDbContext : AbpDbContext<TDbContext>
{
options.Configure<TDbContext>(context =>
{
context.UseOracle(oracleOptionsAction);
});
}
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save