Browse Source

Merge remote-tracking branch 'abpframework/dev' into dev

pull/3525/head
liangshiwei 7 years ago
parent
commit
1bf69b57b1
  1. 7
      abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json
  2. 5
      docs/en/Best-Practices/Entity-Framework-Core-Integration.md
  3. 33
      docs/en/Customizing-Application-Modules-Extending-Entities.md
  4. 11
      docs/en/Entities.md
  5. 104
      docs/en/Entity-Framework-Core-Migrations.md
  6. 111
      docs/en/Entity-Framework-Core.md
  7. 20
      docs/en/Exception-Handling.md
  8. 6
      docs/en/Getting-Started-With-Startup-Templates.md
  9. 15
      docs/en/Startup-Templates/Application.md
  10. 4
      docs/en/UI/Angular/Config-State.md
  11. 1284
      docs/en/UI/Angular/Linked-List.md
  12. 2
      docs/en/UI/Angular/Permission-Management.md
  13. 67
      docs/en/UI/Angular/Service-Proxies.md
  14. 3
      docs/en/UI/Angular/Track-By-Service.md
  15. BIN
      docs/en/UI/Angular/images/generated-files-via-generate-proxy.png
  16. 2
      docs/en/UI/AspNetCore/Tag-Helpers/Tabs.md
  17. 9
      docs/en/docs-nav.json
  18. 7
      docs/zh-Hans/Best-Practices/Entity-Framework-Core-Integration.md
  19. 30
      docs/zh-Hans/Customizing-Application-Modules-Extending-Entities.md
  20. 9
      docs/zh-Hans/Entities.md
  21. 99
      docs/zh-Hans/Entity-Framework-Core-Migrations.md
  22. 107
      docs/zh-Hans/Entity-Framework-Core.md
  23. 80
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Alerts.md
  24. 4
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Buttons.md
  25. 180
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Cards.md
  26. 90
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Collapse.md
  27. 93
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Dropdowns.md
  28. 273
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Grids.md
  29. 12
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Index.md
  30. 76
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/List-Groups.md
  31. 79
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Modals.md
  32. 55
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Paginator.md
  33. 68
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Progress-Bars.md
  34. 91
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Tabs.md
  35. 33
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Tooltips.md
  36. BIN
      docs/zh-Hans/UI/AspNetCore/Tag-Helpers/fa-address-card.png
  37. 11
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/Controllers/ErrorController.cs
  38. 18
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ExceptionHandling/AbpExceptionFilter.cs
  39. 8
      framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/ExceptionHandling/AbpExceptionHandlingMiddleware.cs
  40. 6
      framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/BackgroundJobExecuter.cs
  41. 6
      framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/JobQueue.cs
  42. 19
      framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AsyncPeriodicBackgroundWorkerBase.cs
  43. 18
      framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/PeriodicBackgroundWorkerBase.cs
  44. 44
      framework/src/Volo.Abp.Caching/Volo/Abp/Caching/DistributedCache.cs
  45. 43
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateProxyCommand.cs
  46. 7
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs
  47. 51
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/AbpIoSourceCodeStore.cs
  48. 40
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Analyticses/CliAnalyticsCollect.cs
  49. 4
      framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/ExposedServiceExplorer.cs
  50. 32
      framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotificationContext.cs
  51. 41
      framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotifier.cs
  52. 27
      framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotifierExtensions.cs
  53. 11
      framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionSubscriber.cs
  54. 10
      framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/IExceptionNotifier.cs
  55. 10
      framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/IExceptionSubscriber.cs
  56. 73
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs
  57. 14
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/EntityExtensionInfo.cs
  58. 133
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/EntityExtensionManager.cs
  59. 17
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/PropertyExtensionInfo.cs
  60. 9
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Modeling/AbpEntityTypeBuilderExtensions.cs
  61. 16
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/ValueConverters/AbpJsonValueConverter.cs
  62. 41
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/ValueConverters/ExtraPropertiesValueConverter.cs
  63. 15
      framework/src/Volo.Abp.Ldap/Volo/Abp/Ldap/LdapManager.cs
  64. 11
      framework/src/Volo.Abp.RabbitMQ/Volo/Abp/RabbitMQ/RabbitMqMessageConsumer.cs
  65. 20
      framework/src/Volo.Abp.Threading/Volo/Abp/Threading/AbpTimer.cs
  66. 23
      framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/ExceptionHandling/ExceptionTestController_Tests.cs
  67. 6
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AbpEntityFrameworkCoreTestModule.cs
  68. 25
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Domain/ExtraProperties_Tests.cs
  69. 22
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Domain/TestEntityExtensionConfigurator.cs
  70. 3
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/TestMigrationsDbContext.cs
  71. 3
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs
  72. 4
      framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/TestDataBuilder.cs
  73. 1
      framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Testing/ExtraProperties_Tests.cs
  74. 8
      modules/audit-logging/src/Volo.Abp.AuditLogging.EntityFrameworkCore/Volo/Abp/AuditLogging/EntityFrameworkCore/AbpAuditLoggingDbContextModelBuilderExtensions.cs
  75. 3
      modules/background-jobs/src/Volo.Abp.BackgroundJobs.EntityFrameworkCore/Volo/Abp/BackgroundJobs/EntityFrameworkCore/BackgroundJobsDbContextModelCreatingExtensions.cs
  76. 12
      modules/blogging/src/Volo.Blogging.EntityFrameworkCore/Volo/Blogging/EntityFrameworkCore/BloggingDbContextModelBuilderExtensions.cs
  77. 2
      modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContextModelBuilderExtensions.cs
  78. 47
      modules/docs/src/Volo.Docs.Web/Markdown/MarkdownDocumentToHtmlConverter.cs
  79. 3
      modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/FeatureManagementDbContextModelCreatingExtensions.cs
  80. 22
      modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContextModelBuilderExtensions.cs
  81. 286
      modules/identityserver/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/IdentityServerDbContextModelCreatingExtensions.cs
  82. 3
      modules/permission-management/src/Volo.Abp.PermissionManagement.EntityFrameworkCore/Volo/Abp/PermissionManagement/EntityFrameworkCore/AbpPermissionManagementDbContextModelBuilderExtensions.cs
  83. 2
      modules/setting-management/src/Volo.Abp.SettingManagement.EntityFrameworkCore/Volo/Abp/SettingManagement/EntityFrameworkCore/SettingManagementDbContextModelBuilderExtensions.cs
  84. 4
      modules/tenant-management/src/Volo.Abp.TenantManagement.EntityFrameworkCore/Volo/Abp/TenantManagement/EntityFrameworkCore/AbpTenantManagementDbContextModelCreatingExtensions.cs
  85. 3
      npm/ng-packs/.gitignore
  86. 11
      npm/ng-packs/angular.json
  87. 4
      npm/ng-packs/package.json
  88. 9
      npm/ng-packs/packages/account/src/lib/services/account.service.ts
  89. 12
      npm/ng-packs/packages/core/src/lib/services/application-configuration.service.ts
  90. 3
      npm/ng-packs/packages/core/src/lib/services/index.ts
  91. 18
      npm/ng-packs/packages/core/src/lib/services/profile.service.ts
  92. 4
      npm/ng-packs/packages/core/src/lib/states/config.state.ts
  93. 1532
      npm/ng-packs/packages/core/src/lib/tests/linked-list.spec.ts
  94. 1
      npm/ng-packs/packages/core/src/lib/utils/index.ts
  95. 396
      npm/ng-packs/packages/core/src/lib/utils/linked-list.ts
  96. 8
      npm/ng-packs/packages/feature-management/src/lib/services/feature-management.service.ts
  97. 34
      npm/ng-packs/packages/identity/src/lib/services/identity.service.ts
  98. 15
      npm/ng-packs/packages/permission-management/src/lib/services/permission-management.service.ts
  99. 28
      npm/ng-packs/packages/tenant-management/src/lib/services/tenant-management.service.ts
  100. 6
      npm/ng-packs/scripts/install-new-dependencies.ts

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

@ -86,6 +86,11 @@
"AreYouSureYouWantToDeleteAllComputers": "Are you sure you want to delete all computers?", "AreYouSureYouWantToDeleteAllComputers": "Are you sure you want to delete all computers?",
"DeleteAll": "Delete all", "DeleteAll": "Delete all",
"DoYouWantToCreateNewUser": "Do you want to create new user?", "DoYouWantToCreateNewUser": "Do you want to create new user?",
"MasterModules": "Master Modules" "MasterModules": "Master Modules",
"OrganizationName": "Organization name",
"OrganizationNamePlaceholder": "Organization name...",
"UsernameOrEmail": "Username or email",
"UsernameOrEmailPlaceholder": "Username or email...",
"Member": "Member"
} }
} }

5
docs/en/Best-Practices/Entity-Framework-Core-Integration.md

@ -89,13 +89,15 @@ public static class IdentityDbContextModelBuilderExtensions
builder.Entity<IdentityUser>(b => builder.Entity<IdentityUser>(b =>
{ {
b.ToTable(options.TablePrefix + "Users", options.Schema); b.ToTable(options.TablePrefix + "Users", options.Schema);
b.ConfigureByConvention();
//code omitted for brevity //code omitted for brevity
}); });
builder.Entity<IdentityUserClaim>(b => builder.Entity<IdentityUserClaim>(b =>
{ {
b.ToTable(options.TablePrefix + "UserClaims", options.Schema); b.ToTable(options.TablePrefix + "UserClaims", options.Schema);
b.ConfigureByConvention();
//code omitted for brevity //code omitted for brevity
}); });
@ -104,6 +106,7 @@ public static class IdentityDbContextModelBuilderExtensions
} }
```` ````
* **Do** call `b.ConfigureByConvention();` for each entity mapping (as shown above).
* **Do** create a **configuration options** class by inheriting from the `ModelBuilderConfigurationOptions`. Example: * **Do** create a **configuration options** class by inheriting from the `ModelBuilderConfigurationOptions`. Example:
````C# ````C#

33
docs/en/Customizing-Application-Modules-Extending-Entities.md

@ -4,7 +4,7 @@ In some cases, you may want to add some additional properties (and database fiel
## Extra Properties ## Extra Properties
[Extra properties](Entities.md) is a way of storing some additional data on an entity without changing it. The entity should implement the `IHasExtraProperties` interface to allow it. All the aggregate root entities defined in the pre-built modules implement the `IHasExtraProperties` interface, so you can store extra properties on these entities. [Extra properties](Entities.md) is a way of storing some additional data on an entity without changing it. The entity should implement the `IHasExtraProperties` interface to allow it. All the aggregate root entities defined in the pre-built modules implement the `IHasExtraProperties` interface, so you can store extra properties on these objects.
Example: Example:
@ -25,7 +25,35 @@ Extra properties are stored as a single `JSON` formatted string value in the dat
See the [entities document](Entities.md) for more about the extra properties system. See the [entities document](Entities.md) for more about the extra properties system.
> It is possible to perform a **business logic** based on the value of an extra property. You can **override** a service method and get or set the value as shown above. Overriding services will be discussed below. > It is possible to perform a **business logic** based on the value of an extra property. You can [override a service method](Customizing-Application-Modules-Overriding-Services.md), then get or set the value as shown above.
## Entity Extensions (EF Core)
As mentioned above, all extra properties of an entity are stored as a single JSON object in the database table. This is not so natural especially when you want to;
* Create **indexes** and **foreign keys** for an extra property.
* Write **SQL** or **LINQ** using the extra property (search table by the property value, for example).
* Creating your **own entity** maps to the same table, but defines an extra property as a **regular property** in the entity (see the [EF Core migration document](Entity-Framework-Core-Migrations.md) for more).
To overcome the difficulties described above, ABP Framework entity extension system for the Entity Framework Core that allows you to use the same extra properties API defined above, but store a desired property as a separate field in the database table.
Assume that you want to add a `SocialSecurityNumber` to the `IdentityUser` entity of the [Identity Module](Modules/Identity.md). You can use the `EntityExtensionManager` static class:
````csharp
EntityExtensionManager.AddProperty<IdentityUser, string>(
"SocialSecurityNumber",
b => { b.HasMaxLength(32); }
);
````
* You provide the `IdentityUser` as the entity name, `string` as the type of the new property, `SocialSecurityNumber` as the property name (also, the field name in the database table).
* You also need to provide an action that defines the database mapping properties using the [EF Core Fluent API](https://docs.microsoft.com/en-us/ef/core/modeling/entity-properties).
> This code part must be executed before the related `DbContext` used. The [application startup template](Startup-Templates/Application.md) defines a static class named `YourProjectNameEntityExtensions`. You can define your extensions in this class to ensure that it is executed in the proper time. Otherwise, you should handle it yourself.
Once you define an entity extension, you then need to use the standard [Add-Migration](https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#add-migration) and [Update-Database](https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#update-database) commands of the EF Core to create a code first migration class and update your database.
You can then use the same extra properties system defined in the previous section to manipulate the property over the entity.
## Creating a New Entity Maps to the Same Database Table/Collection ## Creating a New Entity Maps to the Same Database Table/Collection
@ -146,4 +174,5 @@ public class MyDistributedIdentityUserCreatedEventHandler :
## See Also ## See Also
* [Migration System for the EF Core](Entity-Framework-Core-Migrations.md)
* [Customizing the Existing Modules](Customizing-Application-Modules-Guide.md) * [Customizing the Existing Modules](Customizing-Application-Modules-Guide.md)

11
docs/en/Entities.md

@ -373,16 +373,19 @@ So, you can directly use the `ExtraProperties` property to use the dictionary A
The way to store this dictionary in the database depends on the database provider you're using. The way to store this dictionary in the database depends on the database provider you're using.
* For [Entity Framework Core](Entity-Framework-Core.md), it is stored in a single `ExtraProperties` field as a `JSON` string. Serializing to `JSON` and deserializing from the `JSON` are automatically done by the ABP Framework using the [value conversions](https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions) system of the EF Core. * For [Entity Framework Core](Entity-Framework-Core.md), here are two type of configurations;
* By default, it is stored in a single `ExtraProperties` field as a `JSON` string (that means all extra properties stored in a single database table field). Serializing to `JSON` and deserializing from the `JSON` are automatically done by the ABP Framework using the [value conversions](https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions) system of the EF Core.
* If you want, you can use the `EntityExtensionManager` to define a separate table field for a desired extra property. Properties those are not configured through the `EntityExtensionManager` will continue to use a single `JSON` field as described above. This feature is especially useful when you are using a pre-built [application module](Modules/Index.md) and want to [extend its entities](Customizing-Application-Modules-Extending-Entities.md). See the [EF Core integration document](Entity-Framework-Core.md) to learn how to use the `EntityExtensionManager`.
* For [MongoDB](MongoDB.md), it is stored as a **regular field**, since MongoDB naturally supports this kind of [extra elements](https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/#supporting-extra-elements) system. * For [MongoDB](MongoDB.md), it is stored as a **regular field**, since MongoDB naturally supports this kind of [extra elements](https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/#supporting-extra-elements) system.
### Discussion for the Extra Properties ### Discussion for the Extra Properties
Extra Properties system is especially useful if you are using a **re-usable module** that defines an entity inside and you want to get/set some data related to this entity in an easy way. You normally **don't need** to this system for your own entities, because it has the following drawbacks: Extra Properties system is especially useful if you are using a **re-usable module** that defines an entity inside and you want to get/set some data related to this entity in an easy way.
* It is **not fully type safe**. You normally **don't need** to this system for your own entities, because it has the following drawbacks:
* It is **not fully type safe** since it works with strings as property names.
* It is **not easy to [auto map](Object-To-Object-Mapping.md)** these properties from/to other objects. * It is **not easy to [auto map](Object-To-Object-Mapping.md)** these properties from/to other objects.
* It **doesn't create fields** in the database table for EF Core, so it will not be easy to create indexes or search/order by this field in the database side.
### Extra Properties Behind Entities ### Extra Properties Behind Entities

104
docs/en/Entity-Framework-Core-Migrations.md

@ -93,7 +93,7 @@ From the database point of view, there are three important projects those will b
This project has the `DbContext` class (`BookStoreDbContext` for this sample) of your application. This project has the `DbContext` class (`BookStoreDbContext` for this sample) of your application.
**Every module uses its own `DbContext` class** to access to the database. Likewise, your application has its own `DbContext`. You typically use this `DbContext` in your application code (in your custom [repositories](Repositories.md) if you follow the best practices). It is almost an empty `DbContext` since your application don't have any entities at the beginning, except the pre-defined `AppUser` entity: **Every module uses its own `DbContext` class** to access to the database. Likewise, your application has its own `DbContext`. You typically use this `DbContext` in your application code (in your [repositories](Repositories.md) if you follow the best practices). It is almost an empty `DbContext` since your application don't have any entities at the beginning, except the pre-defined `AppUser` entity:
````csharp ````csharp
[ConnectionStringName("Default")] [ConnectionStringName("Default")]
@ -117,15 +117,15 @@ public class BookStoreDbContext : AbpDbContext<BookStoreDbContext>
builder.Entity<AppUser>(b => builder.Entity<AppUser>(b =>
{ {
//Sharing the same table "AbpUsers" with the IdentityUser //Sharing the same Users table with the IdentityUser
b.ToTable("AbpUsers"); b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "Users");
//Configure base properties
b.ConfigureByConvention(); b.ConfigureByConvention();
b.ConfigureAbpUser(); b.ConfigureAbpUser();
//Moved customization of the "AbpUsers" table to an extension method /* Configure mappings for your additional properties
b.ConfigureCustomUserProperties(); * Also see the MyProjectNameEntityExtensions class
*/
}); });
/* Configure your own tables/entities inside the ConfigureBookStore method */ /* Configure your own tables/entities inside the ConfigureBookStore method */
@ -188,12 +188,6 @@ public class BookStoreMigrationsDbContext : AbpDbContext<BookStoreMigrationsDbCo
builder.ConfigureFeatureManagement(); builder.ConfigureFeatureManagement();
builder.ConfigureTenantManagement(); builder.ConfigureTenantManagement();
/* Configure customizations for entities from the modules included */
builder.Entity<IdentityUser>(b =>
{
b.ConfigureCustomUserProperties();
});
/* Configure your own tables/entities inside the ConfigureBookStore method */ /* Configure your own tables/entities inside the ConfigureBookStore method */
builder.ConfigureBookStore(); builder.ConfigureBookStore();
} }
@ -274,7 +268,7 @@ In this way, the mapping configuration of a module can be shared between `DbCont
You may want to **reuse a table** of a depended module in your application. In this case, you have two options: You may want to **reuse a table** of a depended module in your application. In this case, you have two options:
1. You can **directly use the entity** defined by the module. 1. You can **directly use the entity** defined by the module (you can still [extend the entity](Customizing-Application-Modules-Extending-Entities.md) in some level).
2. You can **create a new entity** mapping to the same database table. 2. You can **create a new entity** mapping to the same database table.
###### Use the Entity Defined by a Module ###### Use the Entity Defined by a Module
@ -376,10 +370,8 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<AppRole>(b => builder.Entity<AppRole>(b =>
{ {
b.ToTable("AbpRoles"); b.ToTable("AbpRoles");
b.ConfigureByConvention(); b.ConfigureByConvention();
b.Property(x => x.Title).HasMaxLength(128);
b.ConfigureCustomRoleProperties();
}); });
... ...
@ -395,69 +387,44 @@ We added the following lines:
````csharp ````csharp
builder.Entity<AppRole>(b => builder.Entity<AppRole>(b =>
{ {
b.ToTable("AbpRoles"); b.ToTable("AbpRoles");
b.ConfigureByConvention(); b.ConfigureByConvention();
b.Property(x => x.Title).HasMaxLength(128);
b.ConfigureCustomRoleProperties();
}); });
```` ````
* It maps to the same `AbpRoles` table shared with the `IdentityRole` entity. * It maps to the same `AbpRoles` table shared with the `IdentityRole` entity.
* `ConfigureByConvention()` configures the standard/base properties (like `TenantId`) and recommended to always call it. * `ConfigureByConvention()` configures the standard/base properties (like `TenantId`) and recommended to always call it.
`ConfigureCustomRoleProperties()` has not exists yet. Define it inside the `BookStoreDbContextModelCreatingExtensions` class (near to your `DbContext` in the `.EntityFrameworkCore` project): You've configured the custom property for your `DbContext` that is used by your application on the runtime. We also need to configure the `MigrationsDbContext`.
````csharp
public static void ConfigureCustomRoleProperties<TRole>(this EntityTypeBuilder<TRole> b)
where TRole : class, IEntity<Guid>
{
b.Property<string>(nameof(AppRole.Title)).HasMaxLength(128);
}
````
* This method only defines the **custom properties** of your entity.
* Unfortunately, we can not utilize the fully **type safety** here (by referencing the `AppRole` entity). The best we can do is to use the `Title` name as type safe. This is because of EF Core migration system can not map two unrelated entity classes to the same database table.
You've configured the custom property for your `DbContext` used by your application on the runtime. We also need to configure the `MigrationsDbContext`. Instead of directly changing the `MigrationsDbContext`, we should use the entity extension system of the ABP Framework. Find the `YourProjectNameEntityExtensions` class in the `.EntityFrameworkCore` project of your solution (`BookStoreEntityExtensions` for this example) and change it as shown below:
Open the `MigrationsDbContext` (`BookStoreMigrationsDbContext` for this example) and change as shown below:
````csharp ````csharp
protected override void OnModelCreating(ModelBuilder builder) public static class MyProjectNameEntityExtensions
{ {
base.OnModelCreating(builder); private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
/* Include modules to your migration db context */ public static void Configure()
...
/* Configure customizations for entities from the modules included */
//CONFIGURE THE CUSTOM ROLE PROPERTIES
builder.Entity<IdentityRole>(b =>
{ {
b.ConfigureCustomRoleProperties(); OneTimeRunner.Run(() =>
}); {
EntityExtensionManager.AddProperty<IdentityRole, string>(
... "Title",
b => { b.HasMaxLength(128); }
/* Configure your own tables/entities inside the ConfigureBookStore method */ );
});
builder.ConfigureBookStore(); }
} }
```` ````
Only added the following lines: > Instead of hard-coded "Title" string, we suggest to use `nameof(AppRole.Title)`.
````csharp `EntityExtensionManager` is used to add properties to existing entities. Since `EntityExtensionManager` is static, we should call it once. `OneTimeRunner` is a simple utility class defined by the ABP Framework.
builder.Entity<IdentityRole>(b =>
{ See the [EF Core integration documentation](Entity-Framework-Core.md) for more about the entity extension system.
b.ConfigureCustomRoleProperties();
});
````
In this way, we re-used the extension method that is used to configure custom property mappings for the role. But, this time, did the same customization for the `IdentityRole` entity. > We've repeated a similar database mapping code, like `HasMaxLength(128)`, in both classes.
Now, you can add a new EF Core database migration using the standard `Add-Migration` command in the Package Manager Console (remember to select `.EntityFrameworkCore.DbMigrations` as the Default Project in the PMC and make sure that the `.Web` project is still the startup project): Now, you can add a new EF Core database migration using the standard `Add-Migration` command in the Package Manager Console (remember to select `.EntityFrameworkCore.DbMigrations` as the Default Project in the PMC and make sure that the `.Web` project is still the startup project):
@ -536,7 +503,7 @@ Instead of creating a new entity class to add a custom property, you can use the
###### Using the ExtraProperties ###### Using the ExtraProperties
All entities derived from the `AggregateRoot ` class can store name-value pairs in their `ExtraProperties` property, which is a `Dictionary<string, object>` serialized to JSON in the database table. So, you can add values to this dictionary and query again without changing the entity. All entities derived from the `AggregateRoot ` class can store name-value pairs in their `ExtraProperties` property (because they implement the `IHasExtraProperties` interface), which is a `Dictionary<string, object>` serialized to JSON in the database table. So, you can add values to this dictionary and query again without changing the entity.
For example, you can store query the title Property inside an `IdentityRole` instead of creating a new entity. Example: For example, you can store query the title Property inside an `IdentityRole` instead of creating a new entity. Example:
@ -553,16 +520,13 @@ public class IdentityRoleExtendingService : ITransientDependency
public async Task<string> GetTitleAsync(Guid id) public async Task<string> GetTitleAsync(Guid id)
{ {
var role = await _identityRoleRepository.GetAsync(id); var role = await _identityRoleRepository.GetAsync(id);
return role.GetProperty<string>("Title"); return role.GetProperty<string>("Title");
} }
public async Task SetTitleAsync(Guid id, string newTitle) public async Task SetTitleAsync(Guid id, string newTitle)
{ {
var role = await _identityRoleRepository.GetAsync(id); var role = await _identityRoleRepository.GetAsync(id);
role.SetProperty("Title", newTitle); role.SetProperty("Title", newTitle);
await _identityRoleRepository.UpdateAsync(role); await _identityRoleRepository.UpdateAsync(role);
} }
} }
@ -575,12 +539,20 @@ In this way, you can easily attach any type of value to an entity of a depended
* All the extra properties are stored as **a single JSON object** in the database. They are not stored as new table fields, as you may expect. Creating database table indexes and using SQL queries against these properties will be harder compared to simple table fields. * All the extra properties are stored as **a single JSON object** in the database. They are not stored as new table fields, as you may expect. Creating database table indexes and using SQL queries against these properties will be harder compared to simple table fields.
* Property names are strings, so they are **not type safe**. It is recommended to define constants for these kind of properties to prevent typo errors. * Property names are strings, so they are **not type safe**. It is recommended to define constants for these kind of properties to prevent typo errors.
###### Using the Entity Extensions System
Entity extension system solves the main problem of the extra properties: It can store an extra property in a **standard table field** in the database.
All you need to do is to use the `EntityExtensionManager` to define the extra property as explained above, in the `AppRole` example. Then you can continue to use the same `GetProperty` and `SetProperty` methods defined above to get/set the related property on the entity, but this time stored as a separate field in the database.
###### Creating a New Table ###### Creating a New Table
Instead of creating a new entity and mapping to the same table, you can also create **your own table** to store your properties. You typically duplicate some values of the original entity. For example, you can add `Name` field to your own table which is a duplication of the `Name` field in the original table. Instead of creating a new entity and mapping to the same table, you can also create **your own table** to store your properties. You typically duplicate some values of the original entity. For example, you can add `Name` field to your own table which is a duplication of the `Name` field in the original table.
In this case, you don't deal with migration problems, however you need to deal with the problems of data duplication. When the duplicated value changes, you should reflect the same change in your table. You can use local or distributed [event bus](Event-Bus.md) to subscribe to the change events for the original entity. This is the recommended way of depending on a microservice's data from another microservice, especially if they have separate physical databases (you can search on the web on data sharing on a microservice design, it is a wide topic to cover here). In this case, you don't deal with migration problems, however you need to deal with the problems of data duplication. When the duplicated value changes, you should reflect the same change in your table. You can use local or distributed [event bus](Event-Bus.md) to subscribe to the change events for the original entity. This is the recommended way of depending on a microservice's data from another microservice, especially if they have separate physical databases (you can search on the web on data sharing on a microservice design, it is a wide topic to cover here).
> See the "[extending entities](Customizing-Application-Modules-Extending-Entities.md)" guide for more details on extending entities, including data duplication and synchronization tips.
#### Discussion of an Alternative Scenario: Every Module Manages Its Own Migration Path #### Discussion of an Alternative Scenario: Every Module Manages Its Own Migration Path
As mentioned before, `.EntityFrameworkCore.DbMigrations` merges all the database mappings of all the modules (plus your application's mappings) to create a unified migration path. As mentioned before, `.EntityFrameworkCore.DbMigrations` merges all the database mappings of all the modules (plus your application's mappings) to create a unified migration path.

111
docs/en/Entity-Framework-Core.md

@ -58,6 +58,53 @@ namespace MyCompany.MyProject
} }
```` ````
### About the EF Core Fluent Mapping
The [application startup template](Startup-Templates/Application.md) has been configured to use the [EF Core fluent configuration API](https://docs.microsoft.com/en-us/ef/core/modeling/) to map your entities to your database tables.
You can still use the **data annotation attributes** (like `[Required]`) on the properties of your entity while the ABP documentation generally follows the **fluent mapping API** approach. It is up to you.
ABP Framework has some **base entity classes** and **conventions** (see the [entities document](Entities.md)) and it provides some useful **extension methods** to configure the properties inherited from the base entity classes.
#### ConfigureByConvention Method
`ConfigureByConvention()` is the main extension method that **configures all the base properties** and conventions for your entities. So, it is a **best practice** to call this method for all your entities, in your fluent mapping code.
**Example**: Assume that you've a `Book` entity derived from `AggregateRoot<Guid>` base class:
````csharp
public class Book : AuditedAggregateRoot<Guid>
{
public string Name { get; set; }
}
````
You can override the `OnModelCreating` method in your `DbContext` and configure the mapping as shown below:
````csharp
protected override void OnModelCreating(ModelBuilder builder)
{
//Always call the base method
base.OnModelCreating(builder);
builder.Entity<Book>(b =>
{
b.ToTable("Books");
//Configure the base properties
b.ConfigureByConvention();
//Configure other properties (if you are using the fluent API)
b.Property(x => x.Name).IsRequired().HasMaxLength(128);
});
}
````
* Calling `b.ConfigureByConvention()` is important here to properly **configure the base properties**.
* You can configure the `Name` property here or you can use the **data annotation attributes** (see the [EF Core document](https://docs.microsoft.com/en-us/ef/core/modeling/entity-properties)).
> While there are many extension methods to configure your base properties, `ConfigureByConvention()` internally calls them if necessary. So, it is enough to call it.
### Configure the Connection String Selection ### Configure the Connection String Selection
If you have multiple databases in your application, you can configure the connection string name for your DbContext using the `[ConnectionStringName]` attribute. Example: If you have multiple databases in your application, you can configure the connection string name for your DbContext using the `[ConnectionStringName]` attribute. Example:
@ -225,7 +272,7 @@ public override async Task DeleteAsync(
} }
```` ````
### Access to the EF Core API ## Access to the EF Core API
In most cases, you want to hide EF Core APIs behind a repository (this is the main purpose of the repository pattern). However, if you want to access the `DbContext` instance over the repository, you can use `GetDbContext()` or `GetDbSet()` extension methods. Example: In most cases, you want to hide EF Core APIs behind a repository (this is the main purpose of the repository pattern). However, if you want to access the `DbContext` instance over the repository, you can use `GetDbContext()` or `GetDbSet()` extension methods. Example:
@ -251,9 +298,59 @@ public class BookService
> Important: You must reference to the `Volo.Abp.EntityFrameworkCore` package from the project you want to access to the DbContext. This breaks encapsulation, but this is what you want in that case. > Important: You must reference to the `Volo.Abp.EntityFrameworkCore` package from the project you want to access to the DbContext. This breaks encapsulation, but this is what you want in that case.
### Advanced Topics ## Extra Properties & Entity Extension Manager
Extra Properties system allows you to set/get dynamic properties to entities those implement the `IHasExtraProperties` interface. It is especially useful when you want to add custom properties to the entities defined in an [application module](Modules/Index.md), when you use the module as package reference.
By default, all the extra properties of an entity are stored as a single `JSON` object in the database. Entity extension system allows you to to store desired extra properties in separate fields in the related database table.
#### Set Default Repository Classes For more information about the extra properties & the entity extension system, see the following documents:
* [Customizing the Application Modules: Extending Entities](Customizing-Application-Modules-Extending-Entities.md)
* [Entities](Entities.md)
This section only explains the `EntityExtensionManager` and its usage.
### AddProperty Method
`AddProperty` method of the `EntityExtensionManager` allows you to define additional properties for an entity type.
**Example**: Add `Title` property (database field) to the `IdentityRole` entity:
````csharp
EntityExtensionManager.AddProperty<IdentityRole, string>(
"Title",
b => { b.HasMaxLength(128); }
);
````
If the related module has implemented this feature (by using the `ConfigureExtensions` explained below), then the new property is added to the model. Then you need to run the standard `Add-Migration` and `Update-Database` commands to update your database to add the new field.
>`AddProperty` method must be called before using the related `DbContext`. It is a static method. The best way is to use it in your application as earlier as possible. The application startup template has a `YourProjectNameEntityExtensions` class that is safe to use this method inside.
### ConfigureExtensions
If you are building a reusable module and want to allow application developers to add properties to your entities, you can use the `ConfigureExtensions` extension method in your entity mapping:
````csharp
builder.Entity<YourEntity>(b =>
{
b.ConfigureExtensions();
//...
});
````
If you call `ConfigureByConvention()` extension method (like `b.ConfigureByConvention()` in this example), ABP Framework internally calls the `ConfigureExtensions` method. It is a **best practice** to use the `ConfigureByConvention()` method since it also configures database mapping for base properties by convention.
See the "*ConfigureByConvention Method*" section above for more information.
### GetPropertyNames
`EntityExtensionManager.GetPropertyNames` static method can be used the names of the extension properties defined for this entity. It is normally not needed by an application code, but used by the ABP Framework internally.
## Advanced Topics
### Set Default Repository Classes
Default generic repositories are implemented by `EfCoreRepository` class by default. You can create your own implementation and use it for all the default repository implementations. Default generic repositories are implemented by `EfCoreRepository` class by default. You can create your own implementation and use it for all the default repository implementations.
@ -299,7 +396,7 @@ context.Services.AddAbpDbContext<BookStoreDbContext>(options =>
}); });
``` ```
#### Set Base DbContext Class or Interface for Default Repositories ### Set Base DbContext Class or Interface for Default Repositories
If your DbContext inherits from another DbContext or implements an interface, you can use that base class or interface as DbContext for default repositories. Example: If your DbContext inherits from another DbContext or implements an interface, you can use that base class or interface as DbContext for default repositories. Example:
@ -331,7 +428,7 @@ public class BookRepository : EfCoreRepository<IBookStoreDbContext, Book, Guid>,
One advantage of using an interface for a DbContext is then it will be replaceable by another implementation. One advantage of using an interface for a DbContext is then it will be replaceable by another implementation.
#### Replace Other DbContextes ### Replace Other DbContextes
Once you properly define and use an interface for DbContext, then any other implementation can replace it using the `ReplaceDbContext` option: Once you properly define and use an interface for DbContext, then any other implementation can replace it using the `ReplaceDbContext` option:
@ -344,3 +441,7 @@ context.Services.AddAbpDbContext<OtherDbContext>(options =>
```` ````
In this example, `OtherDbContext` implements `IBookStoreDbContext`. This feature allows you to have multiple DbContext (one per module) on development, but single DbContext (implements all interfaces of all DbContexts) on runtime. In this example, `OtherDbContext` implements `IBookStoreDbContext`. This feature allows you to have multiple DbContext (one per module) on development, but single DbContext (implements all interfaces of all DbContexts) on runtime.
## See Also
* [Entities](Entities.md)

20
docs/en/Exception-Handling.md

@ -291,6 +291,26 @@ services.Configure<AbpExceptionHttpStatusCodeOptions>(options =>
}); });
```` ````
## Subscribing to the Exceptions
It is possible to be informed when the ABP Framework **handles an exception**. It automatically **logs** all the exceptions to the standard [logger](Logging.md), but you may want to do more.
In this case, create a class derived from the `ExceptionSubscriber` class in your application:
````csharp
public class MyExceptionSubscriber : ExceptionSubscriber
{
public override async Task HandleAsync(ExceptionNotificationContext context)
{
//TODO...
}
}
````
The `context` object contains necessary information about the exception occurred.
> You can have multiple subscribers, each gets a copy of the exception. Exceptions thrown by your subscriber is ignored (but still logged).
## Built-In Exceptions ## Built-In Exceptions
Some exception types are automatically thrown by the framework: Some exception types are automatically thrown by the framework:

6
docs/en/Getting-Started-With-Startup-Templates.md

@ -0,0 +1,6 @@
# Getting Started with the Startup Templates
See the following tutorials to learn how to get started with the ABP Framework using the pre-built application startup templates:
* [Getting Started With the ASP.NET Core MVC / Razor Pages UI](Getting-Started-AspNetCore-MVC-Template.md)
* [Getting Started with the Angular UI](Getting-Started-Angular-Template.md)

15
docs/en/Startup-Templates/Application.md

@ -2,11 +2,12 @@
## Introduction ## Introduction
This template provides a layered application structure based on the [Domain Driven Design](../Domain-Driven-Design.md) (DDD) practices. This document explains the solution structure and projects in details. If you want to start quickly, follow the guides below: This template provides a layered application structure based on the [Domain Driven Design](../Domain-Driven-Design.md) (DDD) practices.
* See [Getting Started With the ASP.NET Core MVC Template](../Getting-Started-AspNetCore-MVC-Template.md) to create a new solution and run it for this template (uses MVC as the UI framework and Entity Framework Core as the database provider). This document explains **the solution structure** and projects in details. If you want to start quickly, follow the guides below:
* See the [ASP.NET Core MVC Application Development Tutorial](../Tutorials/Part-1.md?UI=MVC) to learn how to develop applications using this template (uses MVC as the UI framework and Entity Framework Core as the database provider).
* See the [Angular Application Development Tutorial](../Tutorials/Part-1.md?UI=NG) to learn how to develop applications using this template (uses Angular as the UI framework and MongoDB as the database provider). * [The getting started document](../Getting-Started-With-Startup-Templates.md) explains how to create a new application in a few minutes.
* [The application development tutorial](../Tutorials/Part-1) explains step by step application development.
## How to Start With? ## How to Start With?
@ -123,6 +124,8 @@ Notice that the migration `DbContext` is only used for database migrations and *
* Depends on the `.EntityFrameworkCore` project since it re-uses the configuration defined for the `DbContext` of the application. * Depends on the `.EntityFrameworkCore` project since it re-uses the configuration defined for the `DbContext` of the application.
> This project is available only if you are using EF Core as the database provider. > This project is available only if you are using EF Core as the database provider.
>
> See the [Entity Framework Core Migrations Guide](../Entity-Framework-Core-Migrations.md) to understand this project in details.
#### .DbMigrator Project #### .DbMigrator Project
@ -269,5 +272,5 @@ The files under the `angular/src/environments` folder has the essential configur
## What's Next? ## What's Next?
- See [Getting Started With the ASP.NET Core MVC Template](../Getting-Started-AspNetCore-MVC-Template.md) to create a new solution and run it for this template. - [The getting started document](../Getting-Started-With-Startup-Templates.md) explains how to create a new application in a few minutes.
- See the [ASP.NET Core MVC Tutorial](../Tutorials/Part-1.md) to learn how to develop applications using this template. - [The application development tutorial](../Tutorials/Part-1) explains step by step application development.

4
docs/en/UI/Angular/Config-State.md

@ -288,3 +288,7 @@ Note that **you do not have to call this method at application initiation**, bec
#### Environment Properties #### Environment Properties
Please refer to `Config.Environment` type for all the properties you can pass to `dispatchSetEnvironment` as parameter. It can be found in the [config.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L13). Please refer to `Config.Environment` type for all the properties you can pass to `dispatchSetEnvironment` as parameter. It can be found in the [config.ts file](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/config.ts#L13).
## What's Next?
* [Component Replacement](./Component-Replacement.md)

1284
docs/en/UI/Angular/Linked-List.md

File diff suppressed because it is too large

2
docs/en/UI/Angular/Permission-Management.md

@ -76,4 +76,4 @@ Granted Policies are stored in the `auth` property of `ConfigState`.
## What's Next? ## What's Next?
* [Component Replacement](./Component-Replacement.md) * [Config State](./Config-State.md)

67
docs/en/UI/Angular/Service-Proxies.md

@ -0,0 +1,67 @@
## Service Proxies
It is common to call a REST endpoint in the server from our Angular applications. In this case, we generally create **services** (those have methods for each service method on the server side) and **model objects** (matches to [DTOs](../../Data-Transfer-Objects) in the server side).
In addition to manually creating such server-interacting services, we could use tools like [NSWAG](https://github.com/RicoSuter/NSwag) to generate service proxies for us. But NSWAG has the following problems we've experienced:
* It generates a **big, single** .ts file which has some problems;
* It get **too large** when your application grows.
* It doesn't fit into the **[modular](../../Module-Development-Basics) approach** of the ABP framework.
* It creates a bit **ugly code**. We want to have a clean code (just like if we write manually).
* It can not generate the same **method signature** declared in the server side (because swagger.json doesn't exactly reflect the method signature of the backend service). We've created an endpoint that exposes server side method contacts to allow clients generate a better aligned client proxies.
ABP CLI `generate-proxies` command automatically generates the typescript client proxies by creating folders which separated by module names in the `src/app` folder.
Run the following command in the **root folder** of the angular application:
```bash
abp generate-proxy
```
It only creates proxies only for your own application's services. It doesn't create proxies for the services of the application modules you're using (by default). There are several options. See the [CLI documentation](../../CLI).
The files generated with the `--module all` option like below:
![generated-files-via-generate-proxy](./images/generated-files-via-generate-proxy.png)
### Services
Each generated service matches a back-end controller. The services methods call back-end APIs via [RestService](./Http-Requests.md#restservice).
A variable named `apiName` (available as of v2.4) is defined in each service. `apiName` matches the module's RemoteServiceName. This variable passes to the `RestService` as a parameter at each request. If there is no microservice API defined in the environment, `RestService` uses the default. See [getting a specific API endpoint from application config](./Http-Requests.md#how-to-get-a-specific-api-endpoint-from-application-config)
The `providedIn` property of the services is defined as `'root'`. Therefore no need to add a service as a provider to a module. You can use a service by injecting it into a constructor as shown below:
```js
import { AbpApplicationConfigurationService } from '../app/shared/services';
//...
export class HomeComponent{
constructor(private appConfigService: AbpApplicationConfigurationService) {}
ngOnInit() {
this.appConfigService.get().subscribe()
}
}
```
The Angular compiler removes the services that have not been injected anywhere from the final output. See the [tree-shakable providers documentation](https://angular.io/guide/dependency-injection-providers#tree-shakable-providers).
### Models
The generated models match the DTOs in the back-end. Each model is generated as a class under the `src/app/*/shared/models` folder.
There are a few [base classes](https://github.com/abpframework/abp/blob/dev/npm/ng-packs/packages/core/src/lib/models/dtos.ts) in the `@abp/ng.core` package. Some models extend these classes.
A class instance can be created as shown below:
```js
import { IdentityRoleCreateDto } from '../identity/shared/models';
//...
const instance = new IdentityRoleCreateDto({name: 'Role 1', isDefault: false, isPublic: true})
```
Initial values ​​can optionally be passed to each class constructor.
## What's Next?
* [HTTP Requests](./Http-Requests.md)

3
docs/en/UI/Angular/Track-By-Service.md

@ -112,3 +112,6 @@ class DemoComponent {
} }
``` ```
## What's Next?
* [Linked List (Doubly)](./Linked-List.md)

BIN
docs/en/UI/Angular/images/generated-files-via-generate-proxy.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

2
docs/en/UI/AspNetCore/Tag-Helpers/Tabs.md

@ -30,7 +30,7 @@ Basic usage:
## Demo ## Demo
See the [cards demo page](https://bootstrap-taghelpers.abp.io/Components/Cards) to see it in action. See the [tabs demo page](https://bootstrap-taghelpers.abp.io/Components/Tabs) to see it in action.
## abp-tab Attributes ## abp-tab Attributes

9
docs/en/docs-nav.json

@ -5,6 +5,7 @@
"items": [ "items": [
{ {
"text": "From Startup Templates", "text": "From Startup Templates",
"path": "Getting-Started-With-Startup-Templates.md",
"items": [ "items": [
{ {
"text": "Application with MVC (Razor Pages) UI", "text": "Application with MVC (Razor Pages) UI",
@ -312,6 +313,10 @@
{ {
"text": "Angular", "text": "Angular",
"items": [ "items": [
{
"text": "Service Proxies",
"path": "UI/Angular/Service-Proxies.md"
},
{ {
"text": "HTTP Requests", "text": "HTTP Requests",
"path": "UI/Angular/HTTP-Requests.md" "path": "UI/Angular/HTTP-Requests.md"
@ -339,6 +344,10 @@
{ {
"text": "TrackByService", "text": "TrackByService",
"path": "UI/Angular/Track-By-Service.md" "path": "UI/Angular/Track-By-Service.md"
},
{
"text": "Linked List (Doubly)",
"path": "UI/Angular/Linked-List.md"
} }
] ]
} }

7
docs/zh-Hans/Best-Practices/Entity-Framework-Core-Integration.md

@ -89,20 +89,23 @@ public static class IdentityDbContextModelBuilderExtensions
builder.Entity<IdentityUser>(b => builder.Entity<IdentityUser>(b =>
{ {
b.ToTable(options.TablePrefix + "Users", options.Schema); b.ToTable(options.TablePrefix + "Users", options.Schema);
b.ConfigureByConvention();
//code omitted for brevity //code omitted for brevity
}); });
builder.Entity<IdentityUserClaim>(b => builder.Entity<IdentityUserClaim>(b =>
{ {
b.ToTable(options.TablePrefix + "UserClaims", options.Schema); b.ToTable(options.TablePrefix + "UserClaims", options.Schema);
b.ConfigureByConvention();
//code omitted for brevity //code omitted for brevity
}); });
//code omitted for brevity //code omitted for brevity
} }
} }
```` ````
* **推荐** 为每个Enttiy映射调用 `b.ConfigureByConvention();`(如上所示).
* **推荐** 通过继承 `ModelBuilderConfigurationOptions` 来创建 **configuration Options** 类. 例如: * **推荐** 通过继承 `ModelBuilderConfigurationOptions` 来创建 **configuration Options** 类. 例如:
````C# ````C#

30
docs/zh-Hans/Customizing-Application-Modules-Extending-Entities.md

@ -25,7 +25,35 @@ return user.GetProperty<string>("Title");
参阅[实体文档](Entities.md)了解更多关于额外系统. 参阅[实体文档](Entities.md)了解更多关于额外系统.
> 可以基于额外的属性执行**业务逻辑**. 你可以**override**服务方法获取或设置值. 重写服务在下面进行讨论. > 可以基于额外的属性执行**业务逻辑**. 你可以[重写服务方法](Customizing-Application-Modules-Overriding-Services.md). 然后获取或设置如上所示的值.
## 实体扩展 (EF Core)
如上所述,实体所有的额外属性都作为单个JSON对象存储在数据库表中. 它不适用复杂的场景,特别是在你需要的时候.
* 使用额外属性创建**索引**和**外键**.
* 使用额外属性编写**SQL**或**LINQ**(例如根据属性值搜索).
* 创建你**自己的实体**映射到相同的表,但在实体中定义一个额外属性做为 **常规属性**(参阅 [EF Core迁移文档](Entity-Framework-Core-Migrations.md)了解更多).
为了解决上面的问题,用于EF Core的ABP框架实体扩展系统允许你使用上面定义相同的额外属性API,但将所需的属性存储在单独的数据库表字段中.
假设你想要添加 `SocialSecurityNumber` 到[身份模块](Modules/Identity.md)的 `IdentityUser` 实体. 你可以使用 `EntityExtensionManager` 静态类:
````csharp
EntityExtensionManager.AddProperty<IdentityUser, string>(
"SocialSecurityNumber",
b => { b.HasMaxLength(32); }
);
````
* 你提供了 `IdentityUser` 作为实体名(泛型参数), `string` 做为新属性的类型, `SocialSecurityNumber` 做为属性名(也是数据库表的字段名).
* 你还需要提供一个使用[EF Core Fluent API](https://docs.microsoft.com/en-us/ef/core/modeling/entity-properties)定义数据库映射属性的操作.
> 必须在使用相关的 `DbContext` 之前执行此代码. 应用程序启动模板定义了一个名为 `YourProjectNameEntityExtensions` 的静态类. 你可以在此类中定义扩展确保在正确的时间执行它. 否则你需要自己处理.
定义实体扩展后你需要使用EF Core的[Add-Migration](https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#add-migration)和[Update-Database](https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#update-database)命令来创建code first迁移类并更新数据库.
然后你可以使用上一部分中定义的相同额外属性系统来操纵实体上的属性.
## 创建新实体映射到同一个数据库表/Collection ## 创建新实体映射到同一个数据库表/Collection

9
docs/zh-Hans/Entities.md

@ -365,14 +365,17 @@ public static class IdentityUserExtensions
存储字典的方式取决于你使用的数据库提供程序. 存储字典的方式取决于你使用的数据库提供程序.
* 对于 [Entity Framework Core](Entity-Framework-Core.md), 它以 `JSON` 字符串形式存储在 `ExtraProperties` 字段中. 序列化到 `JSON` 和反序列化到 `JSON` 由ABP使用EF Core的[值转换](https://docs.microsoft.com/zh-cn/ef/core/modeling/value-conversions)系统自动完成. * 对于 [Entity Framework Core](Entity-Framework-Core.md),这是两种类型的配置;
* 默认它以 `JSON` 字符串形式存储在 `ExtraProperties` 字段中. 序列化到 `JSON` 和反序列化到 `JSON` 由ABP使用EF Core的[值转换](https://docs.microsoft.com/zh-cn/ef/core/modeling/value-conversions)系统自动完成.
* 如果需要,你可以使用 `EntityExtensionManager` 为所需的额外属性定义一个单独的数据库字段. 那些使用 `EntityExtensionManager` 配置的属性继续使用单个 `JSON` 字段. 当你使用预构建的[应用模块](Modules/Index.md)并且想要[扩展模块的实体](Customizing-Application-Modules-Extending-Entities.md). 参阅[EF Core迁移文档](Entity-Framework-Core.md)了解如何使用 `EntityExtensionManager`.
* 对于 [MongoDB](MongoDB.md), 它以 **常规字段** 存储, 因为 MongoDB 天生支持这种 [额外](https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/#supporting-extra-elements) 系统. * 对于 [MongoDB](MongoDB.md), 它以 **常规字段** 存储, 因为 MongoDB 天生支持这种 [额外](https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/#supporting-extra-elements) 系统.
### 讨论额外的属性 ### 讨论额外的属性
如果你使用**可重复使用的模块**,其中定义了一个实体,你想使用简单的方式get/set此实体相关的一些数据,那么额外的属性系统是非常有用的. 通常 **不需要** 为自己的实体使用这个系统,是因为它有以下缺点: 如果你使用**可重复使用的模块**,其中定义了一个实体,你想使用简单的方式get/set此实体相关的一些数据,那么额外的属性系统是非常有用的.
你通常 **不需要** 为自己的实体使用这个系统,是因为它有以下缺点:
* 它不是**完全类型安全的**. * 它不是**完全类型安全的**,因为它使用字符串用作属性名称.
* 这些属性**不容易[自动映射](Object-To-Object-Mapping.md)到其他对象**. * 这些属性**不容易[自动映射](Object-To-Object-Mapping.md)到其他对象**.
* 它**不会**为EF Core在数据库表中**创建字段**,因此在数据库中针对这个字段创建索引或搜索/排序并不容易. * 它**不会**为EF Core在数据库表中**创建字段**,因此在数据库中针对这个字段创建索引或搜索/排序并不容易.

99
docs/zh-Hans/Entity-Framework-Core-Migrations.md

@ -95,7 +95,7 @@ Volo.Abp.IdentityServer.AbpIdentityServerDbProperties.DbTablePrefix = "Ids";
这个项目有应用程序的 `DbContext`类(本例中的 `BookStoreDbContex` ). 这个项目有应用程序的 `DbContext`类(本例中的 `BookStoreDbContex` ).
**每个模块都使用自己的 `DbContext` 类**来访问数据库。同样你的应用程序有它自己的 `DbContext`. 通常在应用程序中使用这个 `DbContet`(如果你遵循最佳实践,应该在自定义[仓储](Repositories.md)中使用). 它几乎是一个空的 `DbContext`,因为你的应用程序在一开始没有任何实体,除了预定义的 `AppUser` 实体: **每个模块都使用自己的 `DbContext` 类**来访问数据库。同样你的应用程序有它自己的 `DbContext`. 通常在应用程序中使用这个 `DbContet`(如果你遵循最佳实践,应该在[仓储](Repositories.md)中使用). 它几乎是一个空的 `DbContext`,因为你的应用程序在一开始没有任何实体,除了预定义的 `AppUser` 实体:
````csharp ````csharp
[ConnectionStringName("Default")] [ConnectionStringName("Default")]
@ -119,15 +119,15 @@ public class BookStoreDbContext : AbpDbContext<BookStoreDbContext>
builder.Entity<AppUser>(b => builder.Entity<AppUser>(b =>
{ {
//Sharing the same table "AbpUsers" with the IdentityUser //Sharing the same Users table with the IdentityUser
b.ToTable("AbpUsers"); b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "Users");
//Configure base properties
b.ConfigureByConvention(); b.ConfigureByConvention();
b.ConfigureAbpUser(); b.ConfigureAbpUser();
//Moved customization of the "AbpUsers" table to an extension method /* Configure mappings for your additional properties
b.ConfigureCustomUserProperties(); * Also see the MyProjectNameEntityExtensions class
*/
}); });
/* Configure your own tables/entities inside the ConfigureBookStore method */ /* Configure your own tables/entities inside the ConfigureBookStore method */
@ -190,12 +190,6 @@ public class BookStoreMigrationsDbContext : AbpDbContext<BookStoreMigrationsDbCo
builder.ConfigureFeatureManagement(); builder.ConfigureFeatureManagement();
builder.ConfigureTenantManagement(); builder.ConfigureTenantManagement();
/* Configure customizations for entities from the modules included */
builder.Entity<IdentityUser>(b =>
{
b.ConfigureCustomUserProperties();
});
/* Configure your own tables/entities inside the ConfigureBookStore method */ /* Configure your own tables/entities inside the ConfigureBookStore method */
builder.ConfigureBookStore(); builder.ConfigureBookStore();
} }
@ -276,7 +270,7 @@ public class BackgroundJobsDbContext
您可能想在应用程序中**重用依赖模块的表**. 在这种情况下你有两个选择: 您可能想在应用程序中**重用依赖模块的表**. 在这种情况下你有两个选择:
1. 你可以**直接使用模块定义的实体**. 1. 你可以**直接使用模块定义的实体**(你仍然可以在某种程度上[扩展实体](Customizing-Application-Modules-Extending-Entities.md)).
2. 你可以**创建一个新的实体**映射到同一个数据库表。 2. 你可以**创建一个新的实体**映射到同一个数据库表。
###### 使用由模块定义的实体 ###### 使用由模块定义的实体
@ -379,10 +373,8 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<AppRole>(b => builder.Entity<AppRole>(b =>
{ {
b.ToTable("AbpRoles"); b.ToTable("AbpRoles");
b.ConfigureByConvention(); b.ConfigureByConvention();
b.Property(x => x.Title).HasMaxLength(128);
b.ConfigureCustomRoleProperties();
}); });
... ...
@ -399,68 +391,42 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<AppRole>(b => builder.Entity<AppRole>(b =>
{ {
b.ToTable("AbpRoles"); b.ToTable("AbpRoles");
b.ConfigureByConvention(); b.ConfigureByConvention();
b.Property(x => x.Title).HasMaxLength(128);
b.ConfigureCustomRoleProperties();
}); });
```` ````
* 它映射到 `AbpRoles` 表,与 `IdentityRole` 实体共享. * 它映射到 `AbpRoles` 表,与 `IdentityRole` 实体共享.
* `ConfigureByConvention()` 配置了标准/基本属性(像`TenantId`),建议总是调用它. * `ConfigureByConvention()` 配置了标准/基本属性(像`TenantId`),建议总是调用它.
`ConfigureCustomRoleProperties()` 还不存在. 在 `BookStoreDbContextModelCreatingExtensions` 类中定义它 (在 `.EntityFrameworkCore` 项目的 `DbContext` 附近): 你已经为你的 `DbContext` 配置自定义属性,该属性在应用程序运行时使用.
与其直接更改 `MigrationsDbContext`,我们应该使用ABP框架的实体扩展系统,在解决方案的 `.EntityFrameworkCore` 项目中找到 `YourProjectNameEntityExtensions` 类(本示例中是 `BookStoreEntityExtensions`)并且进行以下更改:
````csharp ````csharp
public static void ConfigureCustomRoleProperties<TRole>(this EntityTypeBuilder<TRole> b) public static class MyProjectNameEntityExtensions
where TRole : class, IEntity<Guid>
{ {
b.Property<string>(nameof(AppRole.Title)).HasMaxLength(128); private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
}
````
* 这个方法只定义实体的**自定义属性**.
* 遗憾的是,我们不能在这里充分的利用**类型安全**(通过引用`AppRole`实体). 我们能做的最好就是使用 `Title` 名称做为类型安全。
你已经为运行应用程序使用的 `DbContext` 配置了自定义属性. 我们还需要配置 `MigrationsDbContext`.
打开`MigrationsDbContext`(本例是 `BookStoreMigrationsDbContext`)进行以下更改:
````csharp
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
/* Include modules to your migration db context */
...
/* Configure customizations for entities from the modules included */
//CONFIGURE THE CUSTOM ROLE PROPERTIES public static void Configure()
builder.Entity<IdentityRole>(b =>
{ {
b.ConfigureCustomRoleProperties(); OneTimeRunner.Run(() =>
}); {
EntityExtensionManager.AddProperty<IdentityRole, string>(
... "Title",
b => { b.HasMaxLength(128); }
/* Configure your own tables/entities inside the ConfigureBookStore method */ );
});
builder.ConfigureBookStore(); }
} }
```` ````
只增加下面几行: > 我们建议使用 `nameof(AppRole.Title)` 而不是硬编码 "Title" 字符串
````csharp `EntityExtensionManager` 用于添加属性到现有的实体. 由于 `EntityExtensionManager` 是静态的,因此应调用一次. `OneTimeRunner` 是ABP框架定义简单的工具类.
builder.Entity<IdentityRole>(b =>
{
b.ConfigureCustomRoleProperties();
});
````
通过这种方式,我们重用了用于为角色配置自定义属性映射的扩展方法. 但是对 `IdentityRole` 实体进行了相同的自定义. 参阅[EF Core集成文档](Entity-Framework-Core.md)了解更多关于实体扩展系统.
我们在两个类中都重复了类似的数据库映射代码,例如 `HasMaxLength(128)`.
现在你可以在包管理控制台(记得选择 `.EntityFrameworkCore.DbMigrations` 做为PMC的默认项目并将 `.Web` 项目设置为启动项目)使用标准的 `Add-Migration` 命令添加一个新的EF Core数据库迁移. 现在你可以在包管理控制台(记得选择 `.EntityFrameworkCore.DbMigrations` 做为PMC的默认项目并将 `.Web` 项目设置为启动项目)使用标准的 `Add-Migration` 命令添加一个新的EF Core数据库迁移.
@ -540,7 +506,7 @@ public class AppRoleAppService : ApplicationService, IAppRoleAppService
###### 使用ExtraProperties ###### 使用ExtraProperties
所有从 `AggregateRoot` 派生的实体都可以在 `ExtraProperties` 属性中存储键值对, 它是 `Dictionary<string, object>` 类型在数据库中被序列化为JSON. 所以你可以在字典中添加值用于查询,无需更改实体. 所有从 `AggregateRoot` 派生的实体都可以在 `ExtraProperties` 属性(因为它们都实现了 `IHasExtraProperties` 接口)中存储键值对, 它是 `Dictionary<string, object>` 类型在数据库中被序列化为JSON. 所以你可以在字典中添加值用于查询,无需更改实体.
例如你可以将查询属性 `Title` 存储在 `IdentityRole` 中,而不是创建一个新的实体. 例如你可以将查询属性 `Title` 存储在 `IdentityRole` 中,而不是创建一个新的实体.
例: 例:
@ -558,16 +524,13 @@ public class IdentityRoleExtendingService : ITransientDependency
public async Task<string> GetTitleAsync(Guid id) public async Task<string> GetTitleAsync(Guid id)
{ {
var role = await _identityRoleRepository.GetAsync(id); var role = await _identityRoleRepository.GetAsync(id);
return role.GetProperty<string>("Title"); return role.GetProperty<string>("Title");
} }
public async Task SetTitleAsync(Guid id, string newTitle) public async Task SetTitleAsync(Guid id, string newTitle)
{ {
var role = await _identityRoleRepository.GetAsync(id); var role = await _identityRoleRepository.GetAsync(id);
role.SetProperty("Title", newTitle); role.SetProperty("Title", newTitle);
await _identityRoleRepository.UpdateAsync(role); await _identityRoleRepository.UpdateAsync(role);
} }
} }
@ -580,6 +543,12 @@ public class IdentityRoleExtendingService : ITransientDependency
* 所有的额外属性都存储在数据库中的一个**JSON对象**,它们不是作为表的字段存储,与简单的表字段相比创建索引和针对此属性使用SQL查询将更加困难. * 所有的额外属性都存储在数据库中的一个**JSON对象**,它们不是作为表的字段存储,与简单的表字段相比创建索引和针对此属性使用SQL查询将更加困难.
* 属性名称是字符串,他们**不是类型安全的**. 建议这些类型的属性定义常量,以防止拼写错误. * 属性名称是字符串,他们**不是类型安全的**. 建议这些类型的属性定义常量,以防止拼写错误.
###### 使用实体扩展系统
实体扩展系统解决了额外属性主要的问题: 它可以将额外属性做为**标准表字段**存储到数据库.
你需要做的就是如上所诉使用 `EntityExtensionManager` 定义额外属性, 然后你就可以使得 `GetProperty` 和 `SetProperty` 方法对实体的属性进行get/set,但是这时它存储在数据库表的单独字段中.
###### 创建新表 ###### 创建新表
你可以创建**自己的表**来存储属性,而不是创建新实体并映射到同一表. 你通常复制原始实体的一些值. 例如可以将 `Name` 字段添加到你自己的表中,它是原表中 `Name` 字段的副本. 你可以创建**自己的表**来存储属性,而不是创建新实体并映射到同一表. 你通常复制原始实体的一些值. 例如可以将 `Name` 字段添加到你自己的表中,它是原表中 `Name` 字段的副本.

107
docs/zh-Hans/Entity-Framework-Core.md

@ -58,6 +58,53 @@ namespace MyCompany.MyProject
} }
```` ````
### 关于EF Core Fluent Mapping
[应用程序启动模板](Startup-Templates/Application.md)已配置使用[EF Core fluent configuration API](https://docs.microsoft.com/en-us/ef/core/modeling/)映射你的实体到数据库表.
你依然为你的实体属性使用**data annotation attributes**(像`[Required]`),而ABP文档通常遵循**fluent mapping API** approach方法. 如何使用取决与你.
ABP框架有一些**实体基类**和**约定**(参阅[实体文档](Entities.md))提供了一些有用的扩展方法来配置从基本实体类继承的属性.
#### ConfigureByConvention 方法
`ConfigureByConvention()` 是主要的扩展方法,它对你的实体**配置所有的基本属性**和约定. 所以在你的流利映射代码中为你所有的实体调用这个方法是 **最佳实践**,
**示例**: 假设你有一个直接继承 `AggregateRoot<Guid>` 基类的 `Book` 实体:
````csharp
public class Book : AuditedAggregateRoot<Guid>
{
public string Name { get; set; }
}
````
你可以在你的 `DbContext` 重写 `OnModelCreating` 方法并且做以下配置:
````csharp
protected override void OnModelCreating(ModelBuilder builder)
{
//Always call the base method
base.OnModelCreating(builder);
builder.Entity<Book>(b =>
{
b.ToTable("Books");
//Configure the base properties
b.ConfigureByConvention();
//Configure other properties (if you are using the fluent API)
b.Property(x => x.Name).IsRequired().HasMaxLength(128);
});
}
````
* 这里调用了 `b.ConfigureByConvention()` 它对于**配置基本属性**非常重要.
* 你可以在这里配置 `Name` 属性或者使用**data annotation attributes**(参阅[EF Core 文档](https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties)).
> 尽管有许多扩展方法可以配置基本属性,但如果需要 `ConfigureByConvention()` 内部会调用它们. 因此仅调用它就足够了.
### 配置连接字符串选择 ### 配置连接字符串选择
如果你的应用程序有多个数据库,你可以使用 `connectionStringName]` Attribute为你的DbContext配置连接字符串名称. 如果你的应用程序有多个数据库,你可以使用 `connectionStringName]` Attribute为你的DbContext配置连接字符串名称.
@ -225,7 +272,7 @@ public override async Task DeleteAsync(
} }
```` ````
### 访问 EF Core API ## 访问 EF Core API
大多数情况下应该隐藏仓储后面的EF Core API(这也是仓储的设计目地). 但是如果想要通过仓储访问DbContext实现,则可以使用`GetDbContext()`或`GetDbSet()`扩展方法. 例: 大多数情况下应该隐藏仓储后面的EF Core API(这也是仓储的设计目地). 但是如果想要通过仓储访问DbContext实现,则可以使用`GetDbContext()`或`GetDbSet()`扩展方法. 例:
@ -251,9 +298,59 @@ public class BookService
> 要点: 你必须在使用`DbContext`的项目里引用`Volo.Abp.EntityFrameworkCore`包. 这会破坏封装,但在这种情况下,这就是你需要的. > 要点: 你必须在使用`DbContext`的项目里引用`Volo.Abp.EntityFrameworkCore`包. 这会破坏封装,但在这种情况下,这就是你需要的.
### 高级主题 ## Extra Properties & Entity Extension Manager
额外属性系统允许你为实现了 `IHasExtraProperties` 的实体set/get动态属性. 当你想将自定义属性添加到[应用程序模块](Modules/Index.md)中定义的实体时,它特别有用.
默认,实体的所有额外属性存储在数据库的一个 `JSON` 对象中. 实体扩展系统允许你存储额外属性在数据库的单独字段中.
#### 设置默认仓储类 有关额外属性和实体扩展系统的更多信息,请参阅下列文档:
* [自定义应用模块: 扩展实体](Customizing-Application-Modules-Extending-Entities.md)
* [实体](Entities.md)
本节只解释了 `EntityExtensionManager` 及其用法.
### AddProperty 方法
`EntityExtensionManager` 的 `AddProperty` 方法允许你实体定义附加的属性.
**示例**: 添加 `Title` 属性 (数据库字段)到 `IdentityRole` 实体:
````csharp
EntityExtensionManager.AddProperty<IdentityRole, string>(
"Title",
b => { b.HasMaxLength(128); }
);
````
如果相关模块已实现此功能(通过使用下面说明的 `ConfigureExtensions`)则将新属性添加到模型中. 然后你需要运行标准的 `Add-Migration` 和 `Update-Database` 命令更新数据库以添加新字段.
>`AddProperty` 方法必须在使用相关的 `DbContext` 之前调用,它是一个静态方法. 最好的方法是尽早的应用程序中使用它. 应用程序启动模板含有 `YourProjectNameEntityExtensions` 类,可以在放心的在此类中使用此方法.
### ConfigureExtensions
如果你正在开发一个可重用使用的模块,并允许应用程序开发人员将属性添加到你的实体,你可以在实体映射使用 `ConfigureExtensions` 扩展方法:
````csharp
builder.Entity<YourEntity>(b =>
{
b.ConfigureExtensions();
//...
});
````
如果你调用 `ConfigureByConvention()` 扩展方法(在此示例中 `b.ConfigureByConvention`),ABP框架内部会调用 `ConfigureExtensions` 方法. 使用 `ConfigureByConvention` 方法是**最佳实践**,因为它还按照约定配置基本属性的数据库映射.
参阅上面提到的 "*ConfigureByConvention 方法*" 了解更多信息.
### GetPropertyNames
`EntityExtensionManager.GetPropertyNames` 静态方法可以用作为此实体定义的扩展属性的名称. 应用程序代码通常不需要,但是ABP框架在内部使用它.
## 高级主题
### 设置默认仓储类
默认的通用仓储的默认实现是`EfCoreRepository`类,你可以创建自己的实现,并将其做为默认实现 默认的通用仓储的默认实现是`EfCoreRepository`类,你可以创建自己的实现,并将其做为默认实现
@ -343,3 +440,7 @@ context.Services.AddAbpDbContext<OtherDbContext>(options =>
```` ````
在这个例子中,`OtherDbContext`实现了`IBookStoreDbContext`. 此功能允许你在开发时使用多个DbContext(每个模块一个),但在运行时可以使用单个DbContext(实现所有DbContext的所有接口). 在这个例子中,`OtherDbContext`实现了`IBookStoreDbContext`. 此功能允许你在开发时使用多个DbContext(每个模块一个),但在运行时可以使用单个DbContext(实现所有DbContext的所有接口).
## 另请参阅
* [实体](Entities.md)

80
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Alerts.md

@ -0,0 +1,80 @@
# Alerts
## 介绍
`abp-alert` 是创建alert的主要元素.
基本用法:
````xml
<abp-alert alert-type="Primary">
A simple primary alert—check it out!
</abp-alert>
````
## Demo
参阅[alerts demo页面](https://bootstrap-taghelpers.abp.io/Components/Alerts)查看示例.
## Attributes
### alert-type
值做为alert的Type,应为以下值之一:
* `Default` (默认值)
* `Primary`
* `Secondary`
* `Success`
* `Danger`
* `Warning`
* `Info`
* `Light`
* `Dark`
示例:
````xml
<abp-alert alert-type="Warning">
A simple warning alert—check it out!
</abp-alert>
````
### alert-link
alert的链接.
示例:
````xml
<abp-alert alert-type="Danger">
A simple danger alert with <a abp-alert-link href="#">an example link</a>. Give it a click if you like.
</abp-alert>
````
### dismissible
使alert可被忽略:
示例:
````xml
<abp-alert alert-type="Warning" dismissible="true">
Holy guacamole! You should check in on some of those fields below.
</abp-alert>
````
### Additional content
`abp-alert`还可以包含其他HTML元素,例如标题,段落和分隔符.
示例:
````xml
<abp-alert alert-type="Success">
<h4>Well done!</h4>
<p>Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content.</p>
<hr>
<p class="mb-0">Whenever you need to, be sure to use margin utilities to keep things nice and tidy.</p>
</abp-alert>
````

4
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Buttons.md

@ -12,7 +12,7 @@
## Demo ## Demo
参阅 [按钮Demo页面](https://bootstrap-taghelpers.abp.io/Components/Buttons) 查看示例. 参阅[按钮Demo页面](https://bootstrap-taghelpers.abp.io/Components/Buttons)查看示例.
## Attributes ## Attributes
@ -20,7 +20,7 @@
指定按钮的主样式/类型. 应为以下值之一: 指定按钮的主样式/类型. 应为以下值之一:
* `Default` (default value) * `Default` (默认值)
* `Primary` * `Primary`
* `Secondary` * `Secondary`
* `Success` * `Success`

180
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Cards.md

@ -0,0 +1,180 @@
# 卡片
## 介绍
`abp-card` 是从bootstrap card元素派生的内容容器.
基本用法:
````xml
<abp-card style="width: 18rem;">
<img abp-card-image="Top" src="~/imgs/demo/300x200.png"/>
<abp-card-body>
<abp-card-title>Card Title</abp-card-title>
<abp-card-text>Some quick example text to build on the card title and make up the bulk of the card's content.</abp-card-text>
<a abp-button="Primary" href="#"> Go somewhere</a>
</abp-card-body>
</abp-card>
````
##### 使用标题,文本和链接:
`abp-card` 可以使用以下标签
* `abp-card-title`
* `abp-card-subtitle`
* `a abp-card-link`
示例:
````xml
<abp-card style="width: 18rem;">
<abp-card-body>
<abp-card-title>Card title</abp-card-title>
<abp-card-subtitle class="mb-2 text-muted">Card subtitle</abp-card-subtitle>
<abp-card-text>Some quick example text to build on the card title and make up the bulk of the card's content.</abp-card-text>
<a abp-card-link href="#">Card link</a>
<a abp-card-link href="#">Another link</a>
</abp-card-body>
</abp-card>
````
##### 使用列表组:
* `abp-list-group flush="true"` : `flush` 属性渲染到 bootstrap `list-group-flush` 的 calss 中,该类用于删除边界和圆角以使列表组项在父容器中并排显示.
* `abp-list-group-item`
示例:
````xml
<abp-card style="width: 18rem;">
<img abp-card-image="Top" src="~/imgs/demo/300x200.png" />
<abp-card-body>
<abp-card-title>Card Title</abp-card-title>
<abp-card-text>Some quick example text to build on the card title and make up the bulk of the card's content.</abp-card-text>
</abp-card-body>
<abp-list-group flush="true">
<abp-list-group-item>Cras justo odio</abp-list-group-item>
<abp-list-group-item>Dapibus ac facilisis in</abp-list-group-item>
<abp-list-group-item>Vestibulum at eros</abp-list-group-item>
</abp-list-group>
<abp-card-body>
<a abp-card-link href="#">Card link</a>
<a abp-card-link href="#">Another link</a>
</abp-card-body>
</abp-card>
````
##### 使用页眉,页脚和块引用:
* `abp-card-header`
* `abp-card-footer`
* `abp-blockquote`
示例:
```xml
<abp-card style="width: 18rem;">
<abp-card-header>Featured</abp-card-header>
<abp-card-body>
<abp-card-title> Special title treatment</abp-card-title>
<abp-card-text>With supporting text below as a natural lead-in to additional content.</abp-card-text>
<a abp-button="Primary" href="#"> Go somewhere</a>
</abp-card-body>
</abp-card>
```
引用示例:
```xml
<abp-card>
<abp-card-header>Quote</abp-card-header>
<abp-card-body>
<abp-blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p>
<footer>Someone famous in Source Title</footer>
</abp-blockquote>
</abp-card-body>
</abp-card>
```
页脚示例:
```xml
<abp-card class="text-center">
<abp-card-header>Featured</abp-card-header>
<abp-card-body>
<abp-blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p>
<footer>Someone famous in Source Title</footer>
</abp-blockquote>
</abp-card-body>
<abp-card-footer class="text-muted"> 2 days ago</abp-card-footer>
</abp-card>
```
## Demo
参阅[卡片demo页面](https://bootstrap-taghelpers.abp.io/Components/Cards)查看示例.
## abp-card Attributes
- **background:** 值指定卡片背景的颜色.
- **text-color**: 值指定卡片内文本的颜色.
- **border:** 值指定卡片边框的颜色.
应为以下值之一:
* `Default` (默认值)
* `Primary`
* `Secondary`
* `Success`
* `Danger`
* `Warning`
* `Info`
* `Light`
* `Dark`
示例:
````xml
<abp-card background="Success" text-color="Danger" border="Dark">
````
### sizing
卡片的默认值为100%,可以使用自定义CSS,栅格类,栅格Sass mixins或[utilities](https://getbootstrap.com/docs/4.0/utilities/sizing/)进行更改.
````xml
<abp-card style="width: 18rem;">
````
### card-deck 和 card-columns
`abp-card` 可以在 `card-deck` 或 `card-columns` 里使用.
````xml
<div class="card-deck">
<abp-card background="Primary">
<abp-card-header>First Deck</abp-card-header>
<abp-card-body>
<abp-card-title> Ace </abp-card-title>
<abp-card-text>Here is the content for Ace.</abp-card-text>
</abp-card-body>
</abp-card>
<abp-card background="Info">
<abp-card-header>Second Deck</abp-card-header>
<abp-card-body>
<abp-card-title> Beta </abp-card-title>
<abp-card-text>Beta content.</abp-card-text>
</abp-card-body>
</abp-card>
<abp-card background="Warning">
<abp-card-header>Third Deck</abp-card-header>
<abp-card-body>
<abp-card-title> Epsilon </abp-card-title>
<abp-card-text>Content for Epsilon.</abp-card-text>
</abp-card-body>
</abp-card>
</div>
````

90
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Collapse.md

@ -0,0 +1,90 @@
# Collapse
## 介绍
`abp-collapse-body` 是显示和隐藏内容的主要容器. `abp-collapse-id` 用于显示和隐藏内容容器. 可以通过 `abp-button` 和 `a` 标签触发.
基本用法:
````xml
<abp-button button-type="Primary" abp-collapse-id="collapseExample" text="Button with data-target" />
<a abp-button="Primary" abp-collapse-id="collapseExample"> Link with href </a>
<abp-collapse-body id="collapseExample">
Anim pariatur wolf moon tempor,,, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</abp-collapse-body>
````
## Demo
参阅[collapse demo 页面](https://bootstrap-taghelpers.abp.io/Components/Collapse)查看示例.
## Attributes
### show
指定折叠主体初始化时是折叠还是展开. 应为以下值之一:
* `false` (默认值)
* `true`
### multi
指定 `abp-collapse-body` 是否可以通过显示/隐藏多个折叠体的元素显示或隐藏. 此属性做为 "multi-collapse" class 添加到 `abp-collapse-body`. 应为以下值之一:
* `false` (默认值)
* `true`
示例:
````xml
<a abp-button="Primary" abp-collapse-id="FirstCollapseExample"> Toggle first element </a>
<abp-button button-type="Primary" abp-collapse-id="SecondCollapseExample" text="Toggle second element" />
<abp-button button-type="Primary" abp-collapse-id="FirstCollapseExample SecondCollapseExample" text="Toggle both elements" />
<abp-row class="mt-3">
<abp-column size-sm="_6">
<abp-collapse-body id="FirstCollapseExample" multi="true">
Curabitur porta porttitor libero eu luctus. Praesent ultrices mattis commodo. Integer sodales massa risus, in molestie enim sagittis blandit
</abp-collapse-body>
</abp-column>
<abp-column size-sm="_6">
<abp-collapse-body id="SecondCollapseExample" multi="true">
Anim pariatur wolf moon tempor,,, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et.
</abp-collapse-body>
</abp-column>
</abp-row>
````
## 手风琴示例
`abp-accordion` 是手风琴项的主容器.
基本用法:
````xml
<abp-accordion>
<abp-accordion-item title="Collapsible Group Item #1">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry rtat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</abp-accordion-item>
<abp-accordion-item title="Collapsible Group Item #2">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</abp-accordion-item>
<abp-accordion-item title="Collapsible Group Item #3">
Anim pariatur wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</abp-accordion-item>
</abp-accordion>
````
## Attributes
### active
指定手风琴项目在初始化时是显示还是隐藏. 应为以下值之一:
* `false` (默认值)
* `true`
### title
指定手风琴项的标题. 应为字符串类型的值.

93
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Dropdowns.md

@ -0,0 +1,93 @@
# 下拉菜单
## 介绍
`abp-dropdown` 是下拉菜单的主要容器.
基本用法:
````xml
<abp-dropdown>
<abp-dropdown-button text="Dropdown button" />
<abp-dropdown-menu>
<abp-dropdown-item href="#">Action</abp-dropdown-item>
<abp-dropdown-item href="#">Another action</abp-dropdown-item>
<abp-dropdown-item href="#">Something else here</abp-dropdown-item>
</abp-dropdown-menu>
</abp-dropdown>
````
## Demo
参阅 [下拉菜单demo页面](https://bootstrap-taghelpers.abp.io/Components/Dropdowns)查看示例.
## Attributes
### direction
指定下拉菜单的方向. 应为以下值之一:
* `Down` (默认值)
* `Up`
* `Right`
* `Left`
### dropdown-style
指定 `abp-dropdown-button` 是否具有用于拆分的拆分图标. 应为以下值之一:
* `Single` (默认值)
* `Split`
## Menu items
`abp-dropdown-menu` 下拉菜单项的主要容器.
基本用法:
````xml
<abp-dropdown>
<abp-dropdown-button button-type="Secondary" text="Dropdown"/>
<abp-dropdown-menu>
<abp-dropdown-header>Dropdown Header</abp-dropdown-header>
<abp-dropdown-item href="#">Action</abp-dropdown-item>
<abp-dropdown-item active="true" href="#">Active action</abp-dropdown-item>
<abp-dropdown-item disabled="true" href="#">Disabled action</abp-dropdown-item>
<abp-dropdown-divider/>
<abp-dropdown-item-text>Dropdown Item Text</abp-dropdown-item-text>
<abp-dropdown-item href="#">Something else here</abp-dropdown-item>
</abp-dropdown-menu>
</abp-dropdown>
````
## Attributes
### align
指定 `abp-dropdown-menu` 在哪个方向对齐. 应为以下值之一:
* `Left` (默认值)
* `Right`
### Additional content
`abp-dropdown-menu` 也可以包含其他HTML元素,例如标题,段落,分隔符或form元素.
示例:
````xml
<abp-dropdown >
<abp-dropdown-button button-type="Secondary" text="Dropdown With Form"/>
<abp-dropdown-menu>
<form class="px-4 py-3">
<abp-input asp-for="EmailAddress"></abp-input>
<abp-input asp-for="Password"></abp-input>
<abp-input asp-for="RememberMe"></abp-input>
<abp-button button-type="Primary" text="Sign In" type="submit" />
</form>
<abp-dropdown-divider></abp-dropdown-divider>
<abp-dropdown-item href="#">New around here? Sign up</abp-dropdown-item>
<abp-dropdown-item href="#">Forgot password?</abp-dropdown-item>
</abp-dropdown-menu>
</abp-dropdown>
````

273
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Grids.md

@ -0,0 +1,273 @@
# 栅格
## 介绍
ABP标签助手基于bootstrap栅格系统.
## Demo
参阅[网络demo页面](https://bootstrap-taghelpers.abp.io/Components/Grids)查看示例.
### Sizing
**等宽:** 创建等宽的列.
示例:
````xml
<abp-container>
<abp-row>
<abp-column abp-border="Info">1 of 2</abp-column>
<abp-column abp-border="Danger">2 of 2</abp-column>
</abp-row>
<abp-row>
<abp-column abp-border="Primary">1 of 3</abp-column>
<abp-column abp-border="Secondary">2 of 3</abp-column>
<abp-column abp-border="Dark">3 of 3</abp-column>
</abp-row>
</abp-container>
````
**列中断:** `abp-column-breaker` 用于中断当前行的自动放置宽度,然后在新行中开始.
示例:
````xml
<abp-container>
<abp-row>
<abp-column>column</abp-column>
<abp-column>column</abp-column>
<abp-column-breaker/>
<abp-column>column</abp-column>
<abp-column>column</abp-column>
</abp-row>
</abp-container>
````
**设置列宽度:** size属性用于设置特定列的宽度.
示例:
```xml
<abp-container>
<abp-row>
<abp-column>1 of 3</abp-column>
<abp-column size="_6">2 of 3 (wider)</abp-column>
<abp-column>3 of 3</abp-column>
</abp-row>
<abp-row>
<abp-column>1 of 3</abp-column>
<abp-column size="_5">2 of 3 (wider)</abp-column>
<abp-column>3 of 3</abp-column>
</abp-row>
</abp-container>
```
**可变宽度内容:** 根据内容自动调整列的大小.
```xml
<abp-container>
<abp-row h-align="Center">
<abp-column size-lg="_2" abp-border="Info">1 of 3</abp-column>
<abp-column size-md="Auto" abp-border="Danger">Contrary to popular belief, Lorem Ipsum is not simply random text.</abp-column>
<abp-column size-lg="_2" abp-border="Warning">3 of 3</abp-column>
</abp-row>
<abp-row>
<abp-column>1 of 3</abp-column>
<abp-column size-md="Auto">Variable width content</abp-column>
<abp-column size-lg="_2">3 of 3</abp-column>
</abp-row>
</abp-container>
```
### 响应类
响应式类可以在abp标签中强类型使用.
```xml
<abp-row>
<abp-column size-sm="_8">col-sm-8</abp-column>
<abp-column size-sm="_4">col-sm-4</abp-column>
</abp-row>
<abp-row>
<abp-column size-sm="_">col-sm</abp-column>
<abp-column size-sm="_">col-sm</abp-column>
<abp-column size-sm="_">col-sm</abp-column>
<abp-column size-sm="_">col-sm</abp-column>
</abp-row>
<!-- Stack the columns on mobile by making one full-width and the other half-width -->
<abp-row>
<abp-column size="_12" size-md="_8">.col-12 .col-md-8</abp-column>
<abp-column size="_6" size-md="_4">.col-6 .col-md-4</abp-column>
</abp-row>
<!-- Columns start at 50% wide on mobile and bump up to 33.3% wide on desktop -->
<abp-row>
<abp-column size="_6" size-md="_4">.col-6 .col-md-4</abp-column>
<abp-column size="_6" size-md="_4">.col-6 .col-md-4</abp-column>
<abp-column size="_6" size-md="_4">.col-6 .col-md-4</abp-column>
</abp-row>
<!-- Columns are always 50% wide, on mobile and desktop -->
<abp-row>
<abp-column size="_6">.col-6</abp-column>
<abp-column size="_6">.col-6</abp-column>
</abp-row>
```
### 对齐
可以使用强类型的abp标签在垂直和水平方向上进行列对齐.
**垂直对齐**: `v-align` 属性值用于对垂直齐列.
示例:
```xml
<abp-container>
<abp-row v-align="Start">
<abp-column>column</abp-column>
<abp-column>column</abp-column>
<abp-column>column</abp-column>
</abp-row>
<abp-row v-align="Center">
<abp-column>column</abp-column>
<abp-column>column</abp-column>
<abp-column>column</abp-column>
</abp-row>
<abp-row v-align="End">
<abp-column>column</abp-column>
<abp-column>column</abp-column>
<abp-column>column</abp-column>
</abp-row>
</abp-container>
```
**水平对齐**: `h-align` 属性值用于对水平齐列.
示例:
```xml
<abp-container>
<abp-row h-align="Start">
<abp-column size="_4">One of two columns</abp-column>
<abp-column size="_4">One of two columns</abp-column>
</abp-row>
<abp-row h-align="Center">
<abp-column size="_4">One of two columns</abp-column>
<abp-column size="_4">One of two columns</abp-column>
</abp-row>
<abp-row h-align="End">
<abp-column size="_4">One of two columns</abp-column>
<abp-column size="_4">One of two columns</abp-column>
</abp-row>
<abp-row h-align="Around">
<abp-column size="_4">One of two columns</abp-column>
<abp-column size="_4">One of two columns</abp-column>
</abp-row>
<abp-row h-align="Between">
<abp-column size="_4">One of two columns</abp-column>
<abp-column size="_4">One of two columns</abp-column>
</abp-row>
</abp-container>
```
**无间隙**: 可以使用 `gutters="false"` 删除预定义栅格类中列之间的栅格线. 这会从 `abp-row` 中消除负边距,并从所有直接子列中消除水平边距.
示例:
```xml
<abp-row gutters="false">
<abp-column size="_8">One of two columns</abp-column>
<abp-column size="_4">One of two columns</abp-column>
</abp-row>
```
**列包装**: 如果在一行中放置超过12列,则将每组额外的列作为一个单元包装到新行上.
示例:
```xml
<abp-row>
<abp-column size="_9">.col-9</abp-column>
<abp-column size="_4">.col-4<br>Since 9 + 4 = 13 &gt; 12, this 4-column-wide div gets wrapped onto a new line as one contiguous unit.</abp-column>
<abp-column size="_6">.col-6<br>Subsequent columns continue along the new line.s</abp-column>
</abp-row>
```
### 重新排序
**Order类**: `order` 属性用于控制内容的视觉顺序.
示例:
```xml
<abp-container>
<abp-row>
<abp-column order="_12">First, but Last</abp-column>
<abp-column>Second, but unordered</abp-column>
<abp-column order="_6">Third, but Second</abp-column>
</abp-row>
</abp-container>
```
**偏移列**: `offset` 属性用于设置栅格列的偏移量.
示例:
```xml
<abp-container>
<abp-row>
<abp-column size-md="_4">.col-md-4</abp-column>
<abp-column size-md="_4" offset-md="_4">.col-md-4 .offset-md-4</abp-column>
</abp-row>
<abp-row>
<abp-column size-md="_3" offset-md="_3">.col-md-3 .offset-md-3</abp-column>
<abp-column size-md="_3" offset-md="_3">.col-md-3 .offset-md-3</abp-column>
</abp-row>
<abp-row>
<abp-column size-md="_6" offset-md="_3">.col-md-6 .offset-md-3</abp-column>
</abp-row>
<abp-row>
<abp-column size-sm="_5" size-md="_6">.col-sm-5 .col-md-6</abp-column>
<abp-column size-sm="_5" offset-sm="_2" size-md="_6" offset-md="_">.col-sm-5 .offset-sm-2 .col-md-6 .offset-md-0</abp-column>
</abp-row>
<abp-row>
<abp-column size-sm="_6" size-md="_5" size-lg="_6">col-sm-6 .col-md-5 .col-lg-6</abp-column>
<abp-column size-sm="_6" size-md="_5" offset-md="_2" size-lg="_6" offset-lg="_">.col-sm-6 .col-md-5 .offset-md-2 .col-lg-6 .offset-lg-0</abp-column>
</abp-row>
</abp-container>
```
## abp-row Attributes
- **v-align:** 指定包含列的垂直位置. 应为以下值之一:
* `Default` (默认值)
* `Start`
* `Center`
* `End`
- **h-align**: 指定包含列的水平位置. 应为以下值之一:
* `Default` (默认值)
* `Start`
* `Center`
* `Around`
* `Between`
* `End`
- **gutter**: 指定是否将从所有子列中删除负边距和水平填充. 如果未设置,默认为 `true`. 应为以下值之一:
* `true`
* `false`
## abp-column Attributes
- **size:** 指定列的宽度: `_`, `Undefined`, `_1`..`_12`, `Auto`. 或者可以与预定义值一起使用,例如:
- `size-sm`
- `size-md`
- `size-lg`
- `size-xl`
- **order**: 指定列的顺序: `Undefined`, `_1`..`_12`, `First` 和 `Last`.
- **offset:** 指定列的偏移量: `_`, `Undefined`, `_1`..`_12`, `Auto`. 或者可以与预定义值一起使用,例如:
- `offset-sm`
- `offset-md`
- `offset-lg`
- `offset-xl`

12
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Index.md

@ -13,6 +13,18 @@ ABP框架还向标准bootstrap组件添加了一些**实用的功能**.
这里是ABP框架包装的组件列表: 这里是ABP框架包装的组件列表:
* [Buttons](Buttons.md) * [Buttons](Buttons.md)
* [Cards](Cards.md)
* [Alerts](Alerts.md)
* [Tabs](Tabs.md)
* [Grids](Grids.md)
* [Modals](Modals.md)
* [Collapse](Collapse.md)
* [Dropdowns](Dropdowns.md)
* [List Groups](List-Groups.md)
* [Paginator](Paginator.md)
* [Popovers](Popovers.md)
* [Progress Bars](Progress-Bars.md)
* [Tooltips](Tooltips.md)
* ... * ...
> 在为所有的标签助手完成文档之前,你可以访问 https://bootstrap-taghelpers.abp.io/ 查看在线示例. > 在为所有的标签助手完成文档之前,你可以访问 https://bootstrap-taghelpers.abp.io/ 查看在线示例.

76
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/List-Groups.md

@ -0,0 +1,76 @@
# 列表组
## 介绍
`abp-list-group` 是列表组内容的主要容器.
基本用法:
````xml
<abp-list-group>
<abp-list-group-item>Cras justo odio</abp-list-group-item>
<abp-list-group-item>Dapibus ac facilisis in</abp-list-group-item>
<abp-list-group-item>Morbi leo risus</abp-list-group-item>
<abp-list-group-item>Vestibulum at eros</abp-list-group-item>
</abp-list-group>
````
## Demo
参阅[列表组demo页面](https://bootstrap-taghelpers.abp.io/Components/ListGroups)查看示例.
## Attributes
### flush
指定 `abp-list-group` 项可删除某些边框和圆角,以在父容器中无边框呈现列表组项. 应为以下值之一:
* `false` (默认值)
* `true`
### active
指定 `abp-list-group-item` 是否处于active. 应为以下值之一:
* `false` (默认值)
* `true`
### disabled
指定 `abp-list-group-item` 是否被禁用. 应为以下值之一:
* `false` (默认值)
* `true`
### href
指定 `abp-list-group-item` 是否含有链接. 应该是一个字符串链接值.
### type
指定 `abp-list-group-item` 具有状态背景和颜色的样式类. 应为以下值之一:
* `Default` (默认值)
* `Primary`
* `Secondary`
* `Success`
* `Danger`
* `Warning`
* `Info`
* `Light`
* `Dark`
* `Link`
### Additional content
`abp-list-group-item` 还可以包含其他HTML元素(例如span).
示例:
````xml
<abp-list-group>
<abp-list-group-item>Cras justo odio <span abp-badge-pill="Primary">14</span></abp-list-group-item>
<abp-list-group-item>Dapibus ac facilisis in <span abp-badge-pill="Primary">2</span></abp-list-group-item>
<abp-list-group-item>Morbi leo risus <span abp-badge-pill="Primary">1</span></abp-list-group-item>
</abp-list-group>
````

79
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Modals.md

@ -0,0 +1,79 @@
# 模态框
## 介绍
`abp-modal` 是创建模态框的主要元素.
基本用法:
````xml
<abp-button button-type="Primary" data-toggle="modal" data-target="#myModal">Launch modal</abp-button>
<abp-modal centered="true" size="Large" id="myModal">
<abp-modal-header title="Modal title"></abp-modal-header>
<abp-modal-body>
Woohoo, you're reading this text in a modal!
</abp-modal-body>
<abp-modal-footer buttons="Close"></abp-modal-footer>
</abp-modal>
````
## Demo
参阅[模态框demo页面](https://bootstrap-taghelpers.abp.io/Components/Modals)查看示例.
## Attributes
### centered
指定模态框的位置. 应为以下值之一:
* `false` (默认值)
* `true`
### size
指定模态框的大小. 应为以下值之一:
* `Default` (默认值)
* `Small`
* `Large`
* `ExtraLarge`
### static
指定模态框是否是静态的. 应为以下值之一:
* `false` (默认值)
* `true`
### Additional content
`abp-modal-footer` 可以有多个带有对齐选项的按钮.
添加 `@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal` 到你的页面.
示例:
````xml
<abp-button button-type="Primary" data-toggle="modal" data-target="#myModal">Launch modal</abp-button>
<abp-modal centered="true" size="Large" id="myModal" static="true">
<abp-modal-header title="Modal title"></abp-modal-header>
<abp-modal-body>
Woohoo, you're reading this text in a modal!
</abp-modal-body>
<abp-modal-footer buttons="@(AbpModalButtons.Save|AbpModalButtons.Close)" button-alignment="Between"></abp-modal-footer>
</abp-modal>
````
### button-alignment
指定模态页脚按钮的位置. 应为以下值之一:
* `Default` (默认值)
* `Start`
* `Center`
* `Around`
* `Between`
* `End`

55
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Paginator.md

@ -0,0 +1,55 @@
# 分页器
## 介绍
`abp-paginator` 是分页器的abp标签. 需要 `Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Pagination.PagerModel` 类型的模型.
基本用法:
````xml
<abp-paginator model="Model.PagerModel" show-info="true"></abp-paginator>
````
模型:
````csharp
using Microsoft.AspNetCore.Mvc.RazorPages;
using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Pagination;
namespace Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.Demo.Pages.Components
{
public class PaginatorModel : PageModel
{
public PagerModel PagerModel { get; set; }
public void OnGet(int currentPage, string sort)
{
PagerModel = new PagerModel(100, 10, currentPage, 10, "Paginator", sort);
}
}
}
````
## Demo
参阅[分页器demo页面](https://bootstrap-taghelpers.abp.io/Components/Paginator)查看示例.
## Attributes
### model
`Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Pagination.PagerModel` 类型模型可以用以下数据初始化:
* `totalCount`
* `shownItemsCount`
* `currentPage`
* `pageSize`
* `pageUrl`
* `sort` (默认值为null)
### show-info
指定是否显示开始,结束和总记录的其他信息. 应为以下值之一:
* `false` (默认值)
* `true`

68
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Progress-Bars.md

@ -0,0 +1,68 @@
# 进度条
## 介绍
`abp-progress-bar` 是进度条状态的abp标签.
基本用法:
````xml
<abp-progress-bar value="70" />
<abp-progress-bar type="Warning" value="25"> %25 </abp-progress-bar>
<abp-progress-bar type="Success" value="40" strip="true"/>
<abp-progress-bar type="Dark" value="10" min-value="5" max-value="15" strip="true"> %50 </abp-progress-bar>
<abp-progress-group>
<abp-progress-part type="Success" value="25"/>
<abp-progress-part type="Danger" value="10" strip="true"> %10 </abp-progress-part>
<abp-progress-part type="Primary" value="50" animation="true" strip="true" />
</abp-progress-group>
````
## Demo
参阅[进度条demo页面](https://bootstrap-taghelpers.abp.io/Components/Progress-Bars)查看示例.
## Attributes
### value
指定当前进度条的进度.
### type
指定进度条的背景颜色. 应为下列值之一:
* `Default` (默认值)
* `Secondary`
* `Success`
* `Danger`
* `Warning`
* `Info`
* `Light`
* `Dark`
### min-value
进度条的最小值. 默认值是0。
### max-value
进度条的最大值. 默认值是100.
### strip
指定进度条的背景样式是否被去除. 应为以下值之一:
* `false` (默认值)
* `true`
### animation
指定进度条的背景样式是否为动画. 应为以下值之一:
* `false` (默认值)
* `true`

91
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Tabs.md

@ -0,0 +1,91 @@
# 标签页
## 介绍
`abp-tab` 是从引导标签元素派生的基本标签导航内容容器.
基本用法:
````xml
<abp-tabs>
<abp-tab title="Home">
Content_Home
</abp-tab>
<abp-tab-link title="Link" href="#" />
<abp-tab title="profile">
Content_Profile
</abp-tab>
<abp-tab-dropdown title="Contact" name="ContactDropdown">
<abp-tab title="Contact 1" parent-dropdown-name="ContactDropdown">
Content_1_Content
</abp-tab>
<abp-tab title="Contact 2" parent-dropdown-name="ContactDropdown">
Content_2_Content
</abp-tab>
</abp-tab-dropdown>
</abp-tabs>
````
## Demo
参阅[标签页demo页面](https://bootstrap-taghelpers.abp.io/Components/Tabs)查看示例.
## abp-tab Attributes
- **title**: 设置标签页菜单文字.
- **name:** 设置生成元素的"id"属性. 默认值为Guid. 除非使用Jquery更改或修改了选项卡,否则不需要.
- **active**: 设置active标签页.
示例:
````xml
<abp-tabs name="TabId">
<abp-tab name="nav-home" title="Home">
Content_Home
</abp-tab>
<abp-tab name="nav-profile" active="true" title="profile">
Content_Profile
</abp-tab>
<abp-tab name="nav-contact" title="Contact">
Content_Contact
</abp-tab>
</abp-tabs>
````
### Pills
示例:
````xml
<abp-tabs tab-style="Pill">
<abp-tab title="Home">
Content_Home
</abp-tab>
<abp-tab title="profile">
Content_Profile
</abp-tab>
<abp-tab title="Contact">
Content_Contact
</abp-tab>
</abp-tabs>
````
### Vertical
**vertical-header-size**: 设置标签标题的列宽.
示例:
````xml
<abp-tabs tab-style="PillVertical" vertical-header-size="_2" >
<abp-tab active="true" title="Home">
Content_Home
</abp-tab>
<abp-tab title="profile">
Content_Profile
</abp-tab>
<abp-tab title="Contact">
Content_Contact
</abp-tab>
</abp-tabs>
````

33
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/Tooltips.md

@ -0,0 +1,33 @@
# 提示工具
## 介绍
`abp-tooltip` 是提示工具的abp标签.
基本用法:
````xml
<abp-button abp-tooltip="Tooltip">
Tooltip Default
</abp-button>
<abp-button abp-tooltip-top="Tooltip">
Tooltip on top
</abp-button>
<abp-button abp-tooltip-right="Tooltip">
Tooltip on right
</abp-button>
<abp-button abp-tooltip-bottom="Tooltip">
Tooltip on bottom
</abp-button>
<abp-button disabled="true" abp-tooltip="Tooltip">
Disabled button Tooltip
</abp-button>
````
## Demo
参阅[提示工具demo页面](https://bootstrap-taghelpers.abp.io/Components/Tooltips)查看示例.

BIN
docs/zh-Hans/UI/AspNetCore/Tag-Helpers/fa-address-card.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

11
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/Controllers/ErrorController.cs

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using Localization.Resources.AbpUi; using Localization.Resources.AbpUi;
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -7,6 +8,7 @@ using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Volo.Abp.AspNetCore.ExceptionHandling; using Volo.Abp.AspNetCore.ExceptionHandling;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Views.Error; using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Views.Error;
using Volo.Abp.ExceptionHandling;
namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Controllers namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Controllers
{ {
@ -16,20 +18,23 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Controllers
private readonly IHttpExceptionStatusCodeFinder _statusCodeFinder; private readonly IHttpExceptionStatusCodeFinder _statusCodeFinder;
private readonly IStringLocalizer<AbpUiResource> _localizer; private readonly IStringLocalizer<AbpUiResource> _localizer;
private readonly AbpErrorPageOptions _abpErrorPageOptions; private readonly AbpErrorPageOptions _abpErrorPageOptions;
private readonly IExceptionNotifier _exceptionNotifier;
public ErrorController( public ErrorController(
IExceptionToErrorInfoConverter exceptionToErrorInfoConverter, IExceptionToErrorInfoConverter exceptionToErrorInfoConverter,
IHttpExceptionStatusCodeFinder httpExceptionStatusCodeFinder, IHttpExceptionStatusCodeFinder httpExceptionStatusCodeFinder,
IOptions<AbpErrorPageOptions> abpErrorPageOptions, IOptions<AbpErrorPageOptions> abpErrorPageOptions,
IStringLocalizer<AbpUiResource> localizer) IStringLocalizer<AbpUiResource> localizer,
IExceptionNotifier exceptionNotifier)
{ {
_errorInfoConverter = exceptionToErrorInfoConverter; _errorInfoConverter = exceptionToErrorInfoConverter;
_statusCodeFinder = httpExceptionStatusCodeFinder; _statusCodeFinder = httpExceptionStatusCodeFinder;
_localizer = localizer; _localizer = localizer;
_exceptionNotifier = exceptionNotifier;
_abpErrorPageOptions = abpErrorPageOptions.Value; _abpErrorPageOptions = abpErrorPageOptions.Value;
} }
public IActionResult Index(int httpStatusCode) public async Task<IActionResult> Index(int httpStatusCode)
{ {
var exHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>(); var exHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
@ -37,6 +42,8 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Controllers
? exHandlerFeature.Error ? exHandlerFeature.Error
: new Exception(_localizer["UnhandledException"]); : new Exception(_localizer["UnhandledException"]);
await _exceptionNotifier.NotifyAsync(new ExceptionNotificationContext(exception));
var errorInfo = _errorInfoConverter.Convert(exception); var errorInfo = _errorInfoConverter.Convert(exception);
if (httpStatusCode == 0) if (httpStatusCode == 0)

18
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ExceptionHandling/AbpExceptionFilter.cs

@ -1,18 +1,21 @@
using System; using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.AspNetCore.ExceptionHandling; using Volo.Abp.AspNetCore.ExceptionHandling;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Http; using Volo.Abp.Http;
using Volo.Abp.Json; using Volo.Abp.Json;
namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling
{ {
public class AbpExceptionFilter : IExceptionFilter, ITransientDependency public class AbpExceptionFilter : IAsyncExceptionFilter, ITransientDependency
{ {
public ILogger<AbpExceptionFilter> Logger { get; set; } public ILogger<AbpExceptionFilter> Logger { get; set; }
@ -32,14 +35,14 @@ namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling
Logger = NullLogger<AbpExceptionFilter>.Instance; Logger = NullLogger<AbpExceptionFilter>.Instance;
} }
public virtual void OnException(ExceptionContext context) public async Task OnExceptionAsync(ExceptionContext context)
{ {
if (!ShouldHandleException(context)) if (!ShouldHandleException(context))
{ {
return; return;
} }
HandleAndWrapException(context); await HandleAndWrapException(context);
} }
protected virtual bool ShouldHandleException(ExceptionContext context) protected virtual bool ShouldHandleException(ExceptionContext context)
@ -65,7 +68,7 @@ namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling
return false; return false;
} }
protected virtual void HandleAndWrapException(ExceptionContext context) protected virtual async Task HandleAndWrapException(ExceptionContext context)
{ {
//TODO: Trigger an AbpExceptionHandled event or something like that. //TODO: Trigger an AbpExceptionHandled event or something like that.
@ -82,6 +85,13 @@ namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling
Logger.LogWithLevel(logLevel, _jsonSerializer.Serialize(remoteServiceErrorInfo, indented: true)); Logger.LogWithLevel(logLevel, _jsonSerializer.Serialize(remoteServiceErrorInfo, indented: true));
Logger.LogException(context.Exception, logLevel); Logger.LogException(context.Exception, logLevel);
await context.HttpContext
.RequestServices
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(
new ExceptionNotificationContext(context.Exception)
);
context.Exception = null; //Handled! context.Exception = null; //Handled!
} }
} }

8
framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/ExceptionHandling/AbpExceptionHandlingMiddleware.cs

@ -7,6 +7,7 @@ using Microsoft.Net.Http.Headers;
using Volo.Abp.AspNetCore.Mvc; using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Uow; using Volo.Abp.AspNetCore.Uow;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Http; using Volo.Abp.Http;
using Volo.Abp.Json; using Volo.Abp.Json;
@ -73,6 +74,13 @@ namespace Volo.Abp.AspNetCore.ExceptionHandling
) )
) )
); );
await httpContext
.RequestServices
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(
new ExceptionNotificationContext(exception)
);
} }
private Task ClearCacheHeaders(object state) private Task ClearCacheHeaders(object state)

6
framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/BackgroundJobExecuter.cs

@ -3,7 +3,9 @@ using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
namespace Volo.Abp.BackgroundJobs namespace Volo.Abp.BackgroundJobs
{ {
@ -51,6 +53,10 @@ namespace Volo.Abp.BackgroundJobs
{ {
Logger.LogException(ex); Logger.LogException(ex);
await context.ServiceProvider
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(new ExceptionNotificationContext(ex));
throw new BackgroundJobExecutionException("A background job execution is failed. See inner exception for details.", ex) throw new BackgroundJobExecutionException("A background job execution is failed. See inner exception for details.", ex)
{ {
JobType = context.JobType.AssemblyQualifiedName, JobType = context.JobType.AssemblyQualifiedName,

6
framework/src/Volo.Abp.BackgroundJobs.RabbitMQ/Volo/Abp/BackgroundJobs/RabbitMQ/JobQueue.cs

@ -9,6 +9,7 @@ using Microsoft.Extensions.Options;
using Nito.AsyncEx; using Nito.AsyncEx;
using RabbitMQ.Client; using RabbitMQ.Client;
using RabbitMQ.Client.Events; using RabbitMQ.Client.Events;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.RabbitMQ; using Volo.Abp.RabbitMQ;
using Volo.Abp.Threading; using Volo.Abp.Threading;
@ -31,6 +32,7 @@ namespace Volo.Abp.BackgroundJobs.RabbitMQ
protected IRabbitMqSerializer Serializer { get; } protected IRabbitMqSerializer Serializer { get; }
protected IBackgroundJobExecuter JobExecuter { get; } protected IBackgroundJobExecuter JobExecuter { get; }
protected IServiceScopeFactory ServiceScopeFactory { get; } protected IServiceScopeFactory ServiceScopeFactory { get; }
protected IExceptionNotifier ExceptionNotifier { get; }
protected SemaphoreSlim SyncObj = new SemaphoreSlim(1, 1); protected SemaphoreSlim SyncObj = new SemaphoreSlim(1, 1);
protected bool IsDiposed { get; private set; } protected bool IsDiposed { get; private set; }
@ -41,13 +43,15 @@ namespace Volo.Abp.BackgroundJobs.RabbitMQ
IChannelPool channelPool, IChannelPool channelPool,
IRabbitMqSerializer serializer, IRabbitMqSerializer serializer,
IBackgroundJobExecuter jobExecuter, IBackgroundJobExecuter jobExecuter,
IServiceScopeFactory serviceScopeFactory) IServiceScopeFactory serviceScopeFactory,
IExceptionNotifier exceptionNotifier)
{ {
AbpBackgroundJobOptions = backgroundJobOptions.Value; AbpBackgroundJobOptions = backgroundJobOptions.Value;
AbpRabbitMqBackgroundJobOptions = rabbitMqAbpBackgroundJobOptions.Value; AbpRabbitMqBackgroundJobOptions = rabbitMqAbpBackgroundJobOptions.Value;
Serializer = serializer; Serializer = serializer;
JobExecuter = jobExecuter; JobExecuter = jobExecuter;
ServiceScopeFactory = serviceScopeFactory; ServiceScopeFactory = serviceScopeFactory;
ExceptionNotifier = exceptionNotifier;
ChannelPool = channelPool; ChannelPool = channelPool;
JobConfiguration = AbpBackgroundJobOptions.GetJob(typeof(TArgs)); JobConfiguration = AbpBackgroundJobOptions.GetJob(typeof(TArgs));

19
framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/AsyncPeriodicBackgroundWorkerBase.cs

@ -3,6 +3,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Threading; using Volo.Abp.Threading;
namespace Volo.Abp.BackgroundWorkers namespace Volo.Abp.BackgroundWorkers
@ -35,18 +36,24 @@ namespace Volo.Abp.BackgroundWorkers
private void Timer_Elapsed(object sender, System.EventArgs e) private void Timer_Elapsed(object sender, System.EventArgs e)
{ {
try using (var scope = ServiceScopeFactory.CreateScope())
{ {
using (var scope = ServiceScopeFactory.CreateScope()) try
{ {
AsyncHelper.RunSync( AsyncHelper.RunSync(
() => DoWorkAsync(new PeriodicBackgroundWorkerContext(scope.ServiceProvider)) () => DoWorkAsync(new PeriodicBackgroundWorkerContext(scope.ServiceProvider))
); );
} }
} catch (Exception ex)
catch (Exception ex) {
{ AsyncHelper.RunSync(
Logger.LogException(ex); () => scope.ServiceProvider
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(new ExceptionNotificationContext(ex))
);
Logger.LogException(ex);
}
} }
} }

18
framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/PeriodicBackgroundWorkerBase.cs

@ -3,6 +3,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Threading; using Volo.Abp.Threading;
namespace Volo.Abp.BackgroundWorkers namespace Volo.Abp.BackgroundWorkers
@ -38,16 +39,21 @@ namespace Volo.Abp.BackgroundWorkers
private void Timer_Elapsed(object sender, System.EventArgs e) private void Timer_Elapsed(object sender, System.EventArgs e)
{ {
try using (var scope = ServiceScopeFactory.CreateScope())
{ {
using (var scope = ServiceScopeFactory.CreateScope()) try
{ {
DoWork(new PeriodicBackgroundWorkerContext(scope.ServiceProvider)); DoWork(new PeriodicBackgroundWorkerContext(scope.ServiceProvider));
} }
} catch (Exception ex)
catch (Exception ex) {
{ scope.ServiceProvider
Logger.LogException(ex); .GetRequiredService<IExceptionNotifier>()
.NotifyAsync(new ExceptionNotificationContext(ex));
Logger.LogException(ex);
}
} }
} }

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

@ -2,10 +2,13 @@
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Nito.AsyncEx; using Nito.AsyncEx;
using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
using Volo.Abp.Threading; using Volo.Abp.Threading;
@ -23,12 +26,14 @@ namespace Volo.Abp.Caching
IDistributedCache cache, IDistributedCache cache,
ICancellationTokenProvider cancellationTokenProvider, ICancellationTokenProvider cancellationTokenProvider,
IDistributedCacheSerializer serializer, IDistributedCacheSerializer serializer,
IDistributedCacheKeyNormalizer keyNormalizer) : base( IDistributedCacheKeyNormalizer keyNormalizer,
IHybridServiceScopeFactory serviceScopeFactory) : base(
distributedCacheOption: distributedCacheOption, distributedCacheOption: distributedCacheOption,
cache: cache, cache: cache,
cancellationTokenProvider: cancellationTokenProvider, cancellationTokenProvider: cancellationTokenProvider,
serializer: serializer, serializer: serializer,
keyNormalizer: keyNormalizer) keyNormalizer: keyNormalizer,
serviceScopeFactory: serviceScopeFactory)
{ {
} }
@ -56,6 +61,8 @@ namespace Volo.Abp.Caching
protected IDistributedCacheKeyNormalizer KeyNormalizer { get; } protected IDistributedCacheKeyNormalizer KeyNormalizer { get; }
protected IHybridServiceScopeFactory ServiceScopeFactory { get; }
protected SemaphoreSlim SyncSemaphore { get; } protected SemaphoreSlim SyncSemaphore { get; }
protected DistributedCacheEntryOptions DefaultCacheOptions; protected DistributedCacheEntryOptions DefaultCacheOptions;
@ -67,7 +74,8 @@ namespace Volo.Abp.Caching
IDistributedCache cache, IDistributedCache cache,
ICancellationTokenProvider cancellationTokenProvider, ICancellationTokenProvider cancellationTokenProvider,
IDistributedCacheSerializer serializer, IDistributedCacheSerializer serializer,
IDistributedCacheKeyNormalizer keyNormalizer) IDistributedCacheKeyNormalizer keyNormalizer,
IHybridServiceScopeFactory serviceScopeFactory)
{ {
_distributedCacheOption = distributedCacheOption.Value; _distributedCacheOption = distributedCacheOption.Value;
Cache = cache; Cache = cache;
@ -75,6 +83,7 @@ namespace Volo.Abp.Caching
Logger = NullLogger<DistributedCache<TCacheItem, TCacheKey>>.Instance; Logger = NullLogger<DistributedCache<TCacheItem, TCacheKey>>.Instance;
Serializer = serializer; Serializer = serializer;
KeyNormalizer = keyNormalizer; KeyNormalizer = keyNormalizer;
ServiceScopeFactory = serviceScopeFactory;
SyncSemaphore = new SemaphoreSlim(1, 1); SyncSemaphore = new SemaphoreSlim(1, 1);
@ -139,7 +148,7 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); AsyncHelper.RunSync(() => HandleExceptionAsync(ex));
return null; return null;
} }
@ -181,7 +190,7 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); await HandleExceptionAsync(ex);
return null; return null;
} }
@ -298,7 +307,7 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); AsyncHelper.RunSync(() => HandleExceptionAsync(ex));
return; return;
} }
@ -337,7 +346,7 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); await HandleExceptionAsync(ex);
return; return;
} }
@ -364,7 +373,7 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); AsyncHelper.RunSync(() => HandleExceptionAsync(ex));
return; return;
} }
@ -393,7 +402,7 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); await HandleExceptionAsync(ex);
return; return;
} }
@ -420,7 +429,8 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); AsyncHelper.RunSync(() => HandleExceptionAsync(ex));
return;
} }
throw; throw;
@ -449,12 +459,24 @@ namespace Volo.Abp.Caching
{ {
if (hideErrors == true) if (hideErrors == true)
{ {
Logger.LogException(ex, LogLevel.Warning); await HandleExceptionAsync(ex);
return; return;
} }
throw; throw;
} }
} }
protected virtual async Task HandleExceptionAsync(Exception ex)
{
Logger.LogException(ex, LogLevel.Warning);
using (var scope = ServiceScopeFactory.CreateScope())
{
await scope.ServiceProvider
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(new ExceptionNotificationContext(ex, LogLevel.Warning));
}
}
} }
} }

43
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateProxyCommand.cs

@ -57,9 +57,19 @@ namespace Volo.Abp.Cli.Commands
var uiFramework = GetUiFramework(commandLineArgs); var uiFramework = GetUiFramework(commandLineArgs);
WebClient client = new WebClient(); WebClient client = new WebClient();
string json = client.DownloadString(apiUrl); string json = "";
//var sr = File.OpenText("api-definition.json"); try
//var json = sr.ReadToEnd(); {
json = client.DownloadString(apiUrl);
}
catch (Exception ex)
{
throw new CliUsageException(
"Cannot connect to the host {" + apiUrl + "}! Check that the host is up and running." +
Environment.NewLine + Environment.NewLine +
GetUsageInfo()
);
}
Logger.LogInformation("Downloading api definition..."); Logger.LogInformation("Downloading api definition...");
Logger.LogInformation("Api Url: " + apiUrl); Logger.LogInformation("Api Url: " + apiUrl);
@ -107,7 +117,7 @@ namespace Volo.Abp.Cli.Commands
serviceFileText.AppendLine(""); serviceFileText.AppendLine("");
serviceFileText.AppendLine("@Injectable({providedIn: 'root'})"); serviceFileText.AppendLine("@Injectable({providedIn: 'root'})");
serviceFileText.AppendLine("export class [controllerName]Service {"); serviceFileText.AppendLine("export class [controllerName]Service {");
serviceFileText.AppendLine(" apiName = '"+ apiName + "';"); serviceFileText.AppendLine(" apiName = '" + apiName + "';");
serviceFileText.AppendLine(""); serviceFileText.AppendLine("");
serviceFileText.AppendLine(" constructor(private restService: RestService) {}"); serviceFileText.AppendLine(" constructor(private restService: RestService) {}");
serviceFileText.AppendLine(""); serviceFileText.AppendLine("");
@ -125,7 +135,7 @@ namespace Volo.Abp.Cli.Commands
actionName = (char.ToLower(actionName[0]) + actionName.Substring(1)).Replace("Async", "").Replace("Controller", ""); actionName = (char.ToLower(actionName[0]) + actionName.Substring(1)).Replace("Async", "").Replace("Controller", "");
var returnValueType = (string)action["returnValue"]["type"]; var returnValueType = (string)action["returnValue"]["type"];
var parameters = action["parameters"]; var parameters = action["parameters"];
var parametersText = new StringBuilder(); var parametersText = new StringBuilder();
@ -140,7 +150,7 @@ namespace Volo.Abp.Cli.Commands
var bindingSourceId = (string)parameter["bindingSourceId"]; var bindingSourceId = (string)parameter["bindingSourceId"];
bindingSourceId = char.ToLower(bindingSourceId[0]) + bindingSourceId.Substring(1); bindingSourceId = char.ToLower(bindingSourceId[0]) + bindingSourceId.Substring(1);
var name = (string)parameter["name"]; var name = (string)parameter["name"];
var typeSimple = (string)parameter["typeSimple"]; var typeSimple = (string)parameter["typeSimple"];
var typeArray = ((string)parameter["type"]).Split("."); var typeArray = ((string)parameter["type"]).Split(".");
var type = (typeArray[typeArray.Length - 1]).TrimEnd('>'); var type = (typeArray[typeArray.Length - 1]).TrimEnd('>');
@ -201,7 +211,8 @@ namespace Volo.Abp.Cli.Commands
{ {
secondTypeList.Add(type); secondTypeList.Add(type);
} }
else { else
{
firstTypeList.Add(type); firstTypeList.Add(type);
} }
break; break;
@ -217,7 +228,7 @@ namespace Volo.Abp.Cli.Commands
var parameterItemModelPath = $"src/app/{rootPath}/shared/models/{parameterItemModelName}"; var parameterItemModelPath = $"src/app/{rootPath}/shared/models/{parameterItemModelName}";
if (parameterItem.BindingSourceId == "body" && !File.Exists(parameterItemModelPath)) if (parameterItem.BindingSourceId == "body" && !File.Exists(parameterItemModelPath))
{ {
parameterItem.Type = "any"; parameterItem.Type = "any";
} }
parametersIndex++; parametersIndex++;
@ -248,7 +259,7 @@ namespace Volo.Abp.Cli.Commands
var firstType = firstTypeArray[firstTypeArray.Length - 1]; var firstType = firstTypeArray[firstTypeArray.Length - 1];
var secondTypeArray = returnValueType.Split("<")[1].Split("."); var secondTypeArray = returnValueType.Split("<")[1].Split(".");
var secondType = secondTypeArray[secondTypeArray.Length - 1].TrimEnd('>'); var secondType = secondTypeArray[secondTypeArray.Length - 1].TrimEnd('>');
var secondTypeModelName = secondType.PascalToKebabCase() + ".ts"; var secondTypeModelName = secondType.PascalToKebabCase() + ".ts";
var secondTypeModelPath = $"src/app/{rootPath}/shared/models/{secondTypeModelName}"; var secondTypeModelPath = $"src/app/{rootPath}/shared/models/{secondTypeModelName}";
@ -405,7 +416,7 @@ namespace Volo.Abp.Cli.Commands
} }
private static string CreateType(JObject data, string returnValueType, string rootPath, List<string> modelIndexList) private static string CreateType(JObject data, string returnValueType, string rootPath, List<string> modelIndexList)
{ {
var type = data["types"][returnValueType]; var type = data["types"][returnValueType];
if (type == null) if (type == null)
@ -435,9 +446,9 @@ namespace Volo.Abp.Cli.Commands
} }
var typeModelName = typeName.Replace("<", "").Replace(">", "").Replace("?","").PascalToKebabCase() + ".ts"; var typeModelName = typeName.Replace("<", "").Replace(">", "").Replace("?", "").PascalToKebabCase() + ".ts";
var path = $"src/app/{rootPath}/shared/models/{typeModelName}"; var path = $"src/app/{rootPath}/shared/models/{typeModelName}";
var modelFileText = new StringBuilder(); var modelFileText = new StringBuilder();
@ -474,7 +485,7 @@ namespace Volo.Abp.Cli.Commands
if (!string.IsNullOrWhiteSpace(modelIndex)) if (!string.IsNullOrWhiteSpace(modelIndex))
{ {
modelIndexList.Add(modelIndex); modelIndexList.Add(modelIndex);
} }
} }
} }
@ -501,7 +512,7 @@ namespace Volo.Abp.Cli.Commands
{ {
var propertyName = (string)property["name"]; var propertyName = (string)property["name"];
propertyName = (char.ToLower(propertyName[0]) + propertyName.Substring(1)); propertyName = (char.ToLower(propertyName[0]) + propertyName.Substring(1));
var typeSimple = (string)property["typeSimple"]; var typeSimple = (string)property["typeSimple"];
var modelIndex = CreateType(data, (string)property["type"], rootPath, modelIndexList); var modelIndex = CreateType(data, (string)property["type"], rootPath, modelIndexList);
@ -536,11 +547,11 @@ namespace Volo.Abp.Cli.Commands
) )
{ {
var typeSimpleModelName = typeSimple.PascalToKebabCase() + ".ts"; var typeSimpleModelName = typeSimple.PascalToKebabCase() + ".ts";
var modelPath = $"src/app/{rootPath}/shared/models/{typeSimpleModelName}"; var modelPath = $"src/app/{rootPath}/shared/models/{typeSimpleModelName}";
if (!File.Exists(modelPath)) if (!File.Exists(modelPath))
{ {
typeSimple = "any" + (typeSimple.Contains("[]") ? "[]" : ""); typeSimple = "any" + (typeSimple.Contains("[]") ? "[]" : "");
} }
} }
if (propertyList.Any(p => p.Key == baseTypeName && p.Value.Any(q => q.Key == propertyName && q.Value == typeSimple))) if (propertyList.Any(p => p.Key == baseTypeName && p.Value.Any(q => q.Key == propertyName && q.Value == typeSimple)))

7
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs

@ -94,7 +94,7 @@ namespace Volo.Abp.Cli.Commands
var createSolutionFolder = (commandLineArgs.Options.GetOrNull(Options.CreateSolutionFolder.Short, Options.CreateSolutionFolder.Long) ?? "true").ToLowerInvariant() != "false"; var createSolutionFolder = (commandLineArgs.Options.GetOrNull(Options.CreateSolutionFolder.Short, Options.CreateSolutionFolder.Long) ?? "true").ToLowerInvariant() != "false";
if (!createSolutionFolder) if (!createSolutionFolder)
{ {
Logger.LogInformation("Create Solution Folder: false"); Logger.LogInformation("Create Solution Folder: no");
} }
var outputFolder = commandLineArgs.Options.GetOrNull(Options.OutputFolder.Short, Options.OutputFolder.Long); var outputFolder = commandLineArgs.Options.GetOrNull(Options.OutputFolder.Short, Options.OutputFolder.Long);
@ -106,10 +106,7 @@ namespace Volo.Abp.Cli.Commands
Path.Combine(outputFolderRoot, SolutionName.Parse(projectName).FullName) : Path.Combine(outputFolderRoot, SolutionName.Parse(projectName).FullName) :
outputFolderRoot; outputFolderRoot;
if (!Directory.Exists(outputFolder)) Volo.Abp.IO.DirectoryHelper.CreateIfNotExists(outputFolder);
{
Directory.CreateDirectory(outputFolder);
}
Logger.LogInformation("Output folder: " + outputFolder); Logger.LogInformation("Output folder: " + outputFolder);

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

@ -2,11 +2,16 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Cli.Http; using Volo.Abp.Cli.Http;
using Volo.Abp.Cli.ProjectBuilding.Templates.App;
using Volo.Abp.Cli.ProjectBuilding.Templates.MvcModule;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.Http; using Volo.Abp.Http;
using Volo.Abp.IO; using Volo.Abp.IO;
@ -48,16 +53,33 @@ namespace Volo.Abp.Cli.ProjectBuilding
string templateSource = null) string templateSource = null)
{ {
DirectoryHelper.CreateIfNotExists(CliPaths.TemplateCache);
var latestVersion = await GetLatestSourceCodeVersionAsync(name, type); var latestVersion = await GetLatestSourceCodeVersionAsync(name, type);
if (version == null) if (version == null)
{ {
if (latestVersion == null)
{
Logger.LogWarning("The remote service is currently unavailable, please specify the version.");
Logger.LogWarning(string.Empty);
Logger.LogWarning("Find the following template in your cache directory: ");
Logger.LogWarning("\t Template Name\tVersion");
var templateList = GetLocalTemplates();
foreach (var cacheFile in templateList)
{
Logger.LogWarning($"\t {cacheFile.TemplateName}\t\t{cacheFile.Version}");
}
Logger.LogWarning(string.Empty);
throw new CliUsageException("Use command: abp new Acme.BookStore -v version");
}
version = latestVersion; version = latestVersion;
} }
var nugetVersion = (await GetTemplateNugetVersionAsync(name, type, version)) ?? version; var nugetVersion = (await GetTemplateNugetVersionAsync(name, type, version)) ?? version;
DirectoryHelper.CreateIfNotExists(CliPaths.TemplateCache);
if (!string.IsNullOrWhiteSpace(templateSource) && !IsNetworkSource(templateSource)) if (!string.IsNullOrWhiteSpace(templateSource) && !IsNetworkSource(templateSource))
{ {
Logger.LogInformation("Using local " + type + ": " + name + ", version: " + version); Logger.LogInformation("Using local " + type + ": " + name + ", version: " + version);
@ -122,7 +144,7 @@ namespace Volo.Abp.Cli.ProjectBuilding
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Error occured while getting the latest version from {0} : {1}", url, ex.Message); Console.WriteLine("Error occured while getting the latest version from {0} : {1}", url, ex.Message);
throw; return null;
} }
} }
@ -195,11 +217,30 @@ namespace Volo.Abp.Cli.ProjectBuilding
} }
} }
private static bool IsNetworkSource(string source) private bool IsNetworkSource(string source)
{ {
return source.ToLower().StartsWith("http"); return source.ToLower().StartsWith("http");
} }
private List<(string TemplateName, string Version)> GetLocalTemplates()
{
var templateList = new List<(string TemplateName, string Version)>();
var stringBuilder = new StringBuilder();
foreach (var cacheFile in Directory.GetFiles(CliPaths.TemplateCache))
{
stringBuilder.AppendLine(cacheFile);
}
var matches = Regex.Matches(stringBuilder.ToString(),$"({AppTemplate.TemplateName}|{AppProTemplate.TemplateName}|{ModuleTemplate.TemplateName}|{ModuleProTemplate.TemplateName})-(.+).zip");
foreach (Match match in matches)
{
templateList.Add((match.Groups[1].Value, match.Groups[2].Value));
}
return templateList;
}
public class SourceCodeDownloadInputDto public class SourceCodeDownloadInputDto
{ {
public string Name { get; set; } public string Name { get; set; }

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

@ -1,4 +1,5 @@
using System.Net.Http; using System;
using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -32,27 +33,36 @@ namespace Volo.Abp.Cli.ProjectBuilding.Analyticses
public async Task CollectAsync(CliAnalyticsCollectInputDto input) public async Task CollectAsync(CliAnalyticsCollectInputDto input)
{ {
var postData = _jsonSerializer.Serialize(input); var postData = _jsonSerializer.Serialize(input);
using (var client = new CliHttpClient()) var url = $"{CliUrls.WwwAbpIo}api/clianalytics/collect";
try
{ {
var responseMessage = await client.PostAsync( using (var client = new CliHttpClient())
$"{CliUrls.WwwAbpIo}api/clianalytics/collect",
new StringContent(postData, Encoding.UTF8, MimeTypes.Application.Json),
_cancellationTokenProvider.Token
);
if (!responseMessage.IsSuccessStatusCode)
{ {
var exceptionMessage = "Remote server returns '" + (int)responseMessage.StatusCode + "-" + responseMessage.ReasonPhrase + "'. "; var responseMessage = await client.PostAsync(
var remoteServiceErrorMessage = await _remoteServiceExceptionHandler.GetAbpRemoteServiceErrorAsync(responseMessage); url,
new StringContent(postData, Encoding.UTF8, MimeTypes.Application.Json),
_cancellationTokenProvider.Token
);
if (remoteServiceErrorMessage != null) if (!responseMessage.IsSuccessStatusCode)
{ {
exceptionMessage += remoteServiceErrorMessage; var exceptionMessage = "Remote server returns '" + (int)responseMessage.StatusCode + "-" + responseMessage.ReasonPhrase + "'. ";
} var remoteServiceErrorMessage = await _remoteServiceExceptionHandler.GetAbpRemoteServiceErrorAsync(responseMessage);
if (remoteServiceErrorMessage != null)
{
exceptionMessage += remoteServiceErrorMessage;
}
_logger.LogInformation(exceptionMessage); _logger.LogInformation(exceptionMessage);
}
} }
} }
catch (Exception ex)
{
// ignored
}
} }
} }
} }

4
framework/src/Volo.Abp.Core/Volo/Abp/DependencyInjection/ExposedServiceExplorer.cs

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection;
namespace Volo.Abp.DependencyInjection namespace Volo.Abp.DependencyInjection
{ {
@ -17,10 +16,11 @@ namespace Volo.Abp.DependencyInjection
public static List<Type> GetExposedServices(Type type) public static List<Type> GetExposedServices(Type type)
{ {
return type return type
.GetCustomAttributes() .GetCustomAttributes(true)
.OfType<IExposedServiceTypesProvider>() .OfType<IExposedServiceTypesProvider>()
.DefaultIfEmpty(DefaultExposeServicesAttribute) .DefaultIfEmpty(DefaultExposeServicesAttribute)
.SelectMany(p => p.GetExposedServiceTypes(type)) .SelectMany(p => p.GetExposedServiceTypes(type))
.Distinct()
.ToList(); .ToList();
} }
} }

32
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotificationContext.cs

@ -0,0 +1,32 @@
using System;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
namespace Volo.Abp.ExceptionHandling
{
public class ExceptionNotificationContext
{
/// <summary>
/// The exception object.
/// </summary>
[NotNull]
public Exception Exception { get; }
public LogLevel LogLevel { get; }
/// <summary>
/// True, if it is handled.
/// </summary>
public bool Handled { get; }
public ExceptionNotificationContext(
[NotNull] Exception exception,
LogLevel? logLevel = null,
bool handled = true)
{
Exception = Check.NotNull(exception, nameof(exception));
LogLevel = logLevel ?? exception.GetLogLevel();
Handled = handled;
}
}
}

41
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotifier.cs

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.ExceptionHandling
{
public class ExceptionNotifier : IExceptionNotifier, ITransientDependency
{
public ILogger<ExceptionNotifier> Logger { get; set; }
protected IEnumerable<IExceptionSubscriber> ExceptionSubscribers { get; }
public ExceptionNotifier(IEnumerable<IExceptionSubscriber> exceptionSubscribers)
{
ExceptionSubscribers = exceptionSubscribers;
Logger = NullLogger<ExceptionNotifier>.Instance;
}
public virtual async Task NotifyAsync([NotNull] ExceptionNotificationContext context)
{
Check.NotNull(context, nameof(context));
foreach (var exceptionSubscriber in ExceptionSubscribers)
{
try
{
await exceptionSubscriber.HandleAsync(context);
}
catch (Exception e)
{
Logger.LogWarning($"Exception subscriber of type {exceptionSubscriber.GetType().AssemblyQualifiedName} has thrown an exception!");
Logger.LogException(e, LogLevel.Warning);
}
}
}
}
}

27
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotifierExtensions.cs

@ -0,0 +1,27 @@
using System;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
namespace Volo.Abp.ExceptionHandling
{
public static class ExceptionNotifierExtensions
{
public static Task NotifyAsync(
[NotNull] this IExceptionNotifier exceptionNotifier,
[NotNull] Exception exception,
LogLevel? logLevel = null,
bool handled = true)
{
Check.NotNull(exceptionNotifier, nameof(exceptionNotifier));
return exceptionNotifier.NotifyAsync(
new ExceptionNotificationContext(
exception,
logLevel,
handled
)
);
}
}
}

11
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionSubscriber.cs

@ -0,0 +1,11 @@
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.ExceptionHandling
{
[ExposeServices(typeof(IExceptionSubscriber))]
public abstract class ExceptionSubscriber : IExceptionSubscriber, ITransientDependency
{
public abstract Task HandleAsync(ExceptionNotificationContext context);
}
}

10
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/IExceptionNotifier.cs

@ -0,0 +1,10 @@
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Volo.Abp.ExceptionHandling
{
public interface IExceptionNotifier
{
Task NotifyAsync([NotNull] ExceptionNotificationContext context);
}
}

10
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/IExceptionSubscriber.cs

@ -0,0 +1,10 @@
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Volo.Abp.ExceptionHandling
{
public interface IExceptionSubscriber
{
Task HandleAsync([NotNull] ExceptionNotificationContext context);
}
}

73
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs

@ -18,6 +18,7 @@ using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Entities.Events; using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
using Volo.Abp.EntityFrameworkCore.EntityHistory; using Volo.Abp.EntityFrameworkCore.EntityHistory;
using Volo.Abp.EntityFrameworkCore.Extensions;
using Volo.Abp.EntityFrameworkCore.Modeling; using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.EntityFrameworkCore.ValueConverters; using Volo.Abp.EntityFrameworkCore.ValueConverters;
using Volo.Abp.Guids; using Volo.Abp.Guids;
@ -155,6 +156,50 @@ namespace Volo.Abp.EntityFrameworkCore
ChangeTracker.CascadeDeleteTiming = CascadeTiming.OnSaveChanges; ChangeTracker.CascadeDeleteTiming = CascadeTiming.OnSaveChanges;
ChangeTracker.DeleteOrphansTiming = CascadeTiming.OnSaveChanges; ChangeTracker.DeleteOrphansTiming = CascadeTiming.OnSaveChanges;
ChangeTracker.Tracked += ChangeTracker_Tracked;
}
protected virtual void ChangeTracker_Tracked(object sender, EntityTrackedEventArgs e)
{
FillExtraPropertiesForTrackedEntities(e);
}
protected virtual void FillExtraPropertiesForTrackedEntities(EntityTrackedEventArgs e)
{
var entityType = e.Entry.Metadata.ClrType;
if (entityType == null)
{
return;
}
if (!(e.Entry.Entity is IHasExtraProperties entity))
{
return;
}
if (!e.FromQuery)
{
return;
}
var propertyNames = EntityExtensionManager.GetPropertyNames(entityType);
foreach (var propertyName in propertyNames)
{
/* Checking "currentValue != null" has a good advantage:
* Assume that you we already using a named extra property,
* then decided to create a field (entity extension) for it.
* In this way, it prevents to delete old value in the JSON and
* updates the field on the next save!
*/
var currentValue = e.Entry.CurrentValues[propertyName];
if (currentValue != null)
{
entity.SetProperty(propertyName, currentValue);
}
}
} }
protected virtual EntityChangeReport ApplyAbpConcepts() protected virtual EntityChangeReport ApplyAbpConcepts()
@ -184,9 +229,37 @@ namespace Volo.Abp.EntityFrameworkCore
break; break;
} }
HandleExtraPropertiesOnSave(entry);
AddDomainEvents(changeReport, entry.Entity); AddDomainEvents(changeReport, entry.Entity);
} }
protected virtual void HandleExtraPropertiesOnSave(EntityEntry entry)
{
if (entry.State.IsIn(EntityState.Deleted, EntityState.Unchanged))
{
return;
}
var entityType = entry.Metadata.ClrType;
if (entityType == null)
{
return;
}
if (!(entry.Entity is IHasExtraProperties entity))
{
return;
}
var propertyNames = EntityExtensionManager.GetPropertyNames(entityType);
foreach (var propertyName in propertyNames)
{
entry.Property(propertyName).CurrentValue = entity.GetProperty(propertyName);
}
}
protected virtual void ApplyAbpConceptsForAddedEntity(EntityEntry entry, EntityChangeReport changeReport) protected virtual void ApplyAbpConceptsForAddedEntity(EntityEntry entry, EntityChangeReport changeReport)
{ {
CheckAndSetId(entry); CheckAndSetId(entry);

14
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/EntityExtensionInfo.cs

@ -0,0 +1,14 @@
using System.Collections.Generic;
namespace Volo.Abp.EntityFrameworkCore.Extensions
{
public class EntityExtensionInfo
{
public Dictionary<string, PropertyExtensionInfo> Properties { get; set; }
public EntityExtensionInfo()
{
Properties = new Dictionary<string, PropertyExtensionInfo>();
}
}
}

133
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/EntityExtensionManager.cs

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Volo.Abp.Data;
namespace Volo.Abp.EntityFrameworkCore.Extensions
{
public static class EntityExtensionManager
{
private static readonly Dictionary<Type, EntityExtensionInfo> ExtensionInfos;
static EntityExtensionManager()
{
ExtensionInfos = new Dictionary<Type, EntityExtensionInfo>();
}
/// <summary>
/// Adds an extension property for an entity.
/// If it is already added, replaces the <paramref name="propertyBuildAction"/>
/// by the given one!
/// </summary>
/// <typeparam name="TEntity">Type of the entity</typeparam>
/// <typeparam name="TProperty">Type of the new property</typeparam>
/// <param name="propertyName">Name of the property</param>
/// <param name="propertyBuildAction">An action to configure the database mapping for the new property</param>
public static void AddProperty<TEntity, TProperty>(
[NotNull]string propertyName,
[NotNull]Action<PropertyBuilder> propertyBuildAction)
{
AddProperty(
typeof(TEntity),
typeof(TProperty),
propertyName,
propertyBuildAction
);
}
/// <summary>
/// Adds an extension property for an entity.
/// If it is already added, replaces the <paramref name="propertyBuildAction"/>
/// by the given one!
/// </summary>
/// <param name="entityType">Type of the entity</param>
/// <param name="propertyType">Type of the new property</param>
/// <param name="propertyName">Name of the property</param>
/// <param name="propertyBuildAction">An action to configure the database mapping for the new property</param>
public static void AddProperty(
Type entityType,
Type propertyType,
[NotNull]string propertyName,
[NotNull]Action<PropertyBuilder> propertyBuildAction)
{
Check.NotNull(entityType, nameof(entityType));
Check.NotNull(propertyType, nameof(propertyType));
Check.NotNullOrWhiteSpace(propertyName, nameof(propertyName));
Check.NotNull(propertyBuildAction, nameof(propertyBuildAction));
var extensionInfo = ExtensionInfos
.GetOrAdd(entityType, () => new EntityExtensionInfo());
var propertyExtensionInfo = extensionInfo.Properties
.GetOrAdd(propertyName, () => new PropertyExtensionInfo(propertyType));
propertyExtensionInfo.Action = propertyBuildAction;
}
/// <summary>
/// Configures the entity mapping for the defined extensions.
/// </summary>
/// <typeparam name="TEntity">The entity tye</typeparam>
/// <param name="entityTypeBuilder">Entity type builder</param>
public static void ConfigureExtensions<TEntity>(
[NotNull] this EntityTypeBuilder<TEntity> entityTypeBuilder)
where TEntity : class, IHasExtraProperties
{
ConfigureExtensions(typeof(TEntity), entityTypeBuilder);
}
/// <summary>
/// Configures the entity mapping for the defined extensions.
/// </summary>
/// <param name="entityType">Type of the entity</param>
/// <param name="entityTypeBuilder">Entity type builder</param>
public static void ConfigureExtensions(
[NotNull] Type entityType,
[NotNull] EntityTypeBuilder entityTypeBuilder)
{
Check.NotNull(entityType, nameof(entityType));
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
var entityExtensionInfo = ExtensionInfos.GetOrDefault(entityType);
if (entityExtensionInfo == null)
{
return;
}
foreach (var propertyExtensionInfo in entityExtensionInfo.Properties)
{
var propertyName = propertyExtensionInfo.Key;
var propertyType = propertyExtensionInfo.Value.PropertyType;
/* Prevent multiple calls to the entityTypeBuilder.Property(...) method */
if (entityTypeBuilder.Metadata.FindProperty(propertyName) != null)
{
continue;
}
var property = entityTypeBuilder.Property(
propertyType,
propertyName
);
propertyExtensionInfo.Value.Action(property);
}
}
public static string[] GetPropertyNames(Type entityType)
{
var entityExtensionInfo = ExtensionInfos.GetOrDefault(entityType);
if (entityExtensionInfo == null)
{
return Array.Empty<string>();
}
return entityExtensionInfo
.Properties
.Select(p => p.Key)
.ToArray();
}
}
}

17
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/PropertyExtensionInfo.cs

@ -0,0 +1,17 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Volo.Abp.EntityFrameworkCore.Extensions
{
public class PropertyExtensionInfo
{
public Action<PropertyBuilder> Action { get; set; }
public Type PropertyType { get; }
public PropertyExtensionInfo(Type propertyType)
{
PropertyType = propertyType;
}
}
}

9
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Modeling/AbpEntityTypeBuilderExtensions.cs

@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Volo.Abp.Auditing; using Volo.Abp.Auditing;
using Volo.Abp.Data; using Volo.Abp.Data;
using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Entities;
using Volo.Abp.EntityFrameworkCore.Extensions;
using Volo.Abp.EntityFrameworkCore.ValueComparers; using Volo.Abp.EntityFrameworkCore.ValueComparers;
using Volo.Abp.EntityFrameworkCore.ValueConverters; using Volo.Abp.EntityFrameworkCore.ValueConverters;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
@ -25,7 +26,7 @@ namespace Volo.Abp.EntityFrameworkCore.Modeling
b.TryConfigureCreationTime(); b.TryConfigureCreationTime();
b.TryConfigureLastModificationTime(); b.TryConfigureLastModificationTime();
b.TryConfigureModificationAudited(); b.TryConfigureModificationAudited();
b.TryConfigureMultiTenant(); b.TryConfigureMultiTenant();
} }
public static void ConfigureConcurrencyStamp<T>(this EntityTypeBuilder<T> b) public static void ConfigureConcurrencyStamp<T>(this EntityTypeBuilder<T> b)
@ -58,8 +59,10 @@ namespace Volo.Abp.EntityFrameworkCore.Modeling
{ {
b.Property<Dictionary<string, object>>(nameof(IHasExtraProperties.ExtraProperties)) b.Property<Dictionary<string, object>>(nameof(IHasExtraProperties.ExtraProperties))
.HasColumnName(nameof(IHasExtraProperties.ExtraProperties)) .HasColumnName(nameof(IHasExtraProperties.ExtraProperties))
.HasConversion(new AbpJsonValueConverter<Dictionary<string, object>>()) .HasConversion(new ExtraPropertiesValueConverter(b.Metadata.ClrType))
.Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, object>()); .Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, object>());
EntityExtensionManager.ConfigureExtensions(b.Metadata.ClrType, b);
} }
} }
@ -276,7 +279,7 @@ namespace Volo.Abp.EntityFrameworkCore.Modeling
} }
public static void ConfigureFullAuditedAggregateRoot<T>(this EntityTypeBuilder<T> b) public static void ConfigureFullAuditedAggregateRoot<T>(this EntityTypeBuilder<T> b)
where T : class where T : class
{ {
b.As<EntityTypeBuilder>().TryConfigureFullAudited(); b.As<EntityTypeBuilder>().TryConfigureFullAudited();
b.As<EntityTypeBuilder>().TryConfigureExtraProperties(); b.As<EntityTypeBuilder>().TryConfigureExtraProperties();

16
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/ValueConverters/AbpJsonValueConverter.cs

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Newtonsoft.Json; using Newtonsoft.Json;
using Volo.Abp.Data;
namespace Volo.Abp.EntityFrameworkCore.ValueConverters namespace Volo.Abp.EntityFrameworkCore.ValueConverters
{ {
@ -7,9 +8,20 @@ namespace Volo.Abp.EntityFrameworkCore.ValueConverters
{ {
public AbpJsonValueConverter() public AbpJsonValueConverter()
: base( : base(
d => JsonConvert.SerializeObject(d, Formatting.None), d => SerializeObject(d),
s => JsonConvert.DeserializeObject<TPropertyType>(s)) s => DeserializeObject(s))
{ {
}
private static string SerializeObject(TPropertyType d)
{
return JsonConvert.SerializeObject(d, Formatting.None);
}
private static TPropertyType DeserializeObject(string s)
{
return JsonConvert.DeserializeObject<TPropertyType>(s);
} }
} }
} }

41
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/ValueConverters/ExtraPropertiesValueConverter.cs

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Newtonsoft.Json;
using Volo.Abp.EntityFrameworkCore.Extensions;
namespace Volo.Abp.EntityFrameworkCore.ValueConverters
{
public class ExtraPropertiesValueConverter : ValueConverter<Dictionary<string, object>, string>
{
public ExtraPropertiesValueConverter(Type entityType)
: base(
d => SerializeObject(d, entityType),
s => DeserializeObject(s))
{
}
private static string SerializeObject(Dictionary<string, object> extraProperties, Type entityType)
{
var copyDictionary = new Dictionary<string, object>(extraProperties);
if (entityType != null)
{
var propertyNames = EntityExtensionManager.GetPropertyNames(entityType);
foreach (var propertyName in propertyNames)
{
copyDictionary.Remove(propertyName);
}
}
return JsonConvert.SerializeObject(copyDictionary, Formatting.None);
}
private static Dictionary<string, object> DeserializeObject(string extraPropertiesAsJson)
{
return JsonConvert.DeserializeObject<Dictionary<string, object>>(extraPropertiesAsJson);
}
}
}

15
framework/src/Volo.Abp.Ldap/Volo/Abp/Ldap/LdapManager.cs

@ -3,7 +3,9 @@ using Microsoft.Extensions.Options;
using Novell.Directory.Ldap; using Novell.Directory.Ldap;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Ldap.Exceptions; using Volo.Abp.Ldap.Exceptions;
using Volo.Abp.Ldap.Modeling; using Volo.Abp.Ldap.Modeling;
@ -13,6 +15,7 @@ namespace Volo.Abp.Ldap
{ {
private readonly string _searchBase; private readonly string _searchBase;
private readonly AbpLdapOptions _ldapOptions; private readonly AbpLdapOptions _ldapOptions;
private readonly IHybridServiceScopeFactory _hybridServiceScopeFactory;
private readonly string[] _attributes = private readonly string[] _attributes =
{ {
@ -21,8 +24,9 @@ namespace Volo.Abp.Ldap
"sAMAccountName", "userPrincipalName", "telephoneNumber", "mail" "sAMAccountName", "userPrincipalName", "telephoneNumber", "mail"
}; };
public LdapManager(IOptions<AbpLdapOptions> ldapSettingsOptions) public LdapManager(IOptions<AbpLdapOptions> ldapSettingsOptions, IHybridServiceScopeFactory hybridServiceScopeFactory)
{ {
_hybridServiceScopeFactory = hybridServiceScopeFactory;
_ldapOptions = ldapSettingsOptions.Value; _ldapOptions = ldapSettingsOptions.Value;
_searchBase = _ldapOptions.SearchBase; _searchBase = _ldapOptions.SearchBase;
} }
@ -231,8 +235,15 @@ namespace Volo.Abp.Ldap
return true; return true;
} }
} }
catch (Exception ) catch (Exception ex)
{ {
using (var scope = _hybridServiceScopeFactory.CreateScope())
{
scope.ServiceProvider
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(ex);
}
return false; return false;
} }
} }

11
framework/src/Volo.Abp.RabbitMQ/Volo/Abp/RabbitMQ/RabbitMqMessageConsumer.cs

@ -7,6 +7,7 @@ using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Threading; using Volo.Abp.Threading;
namespace Volo.Abp.RabbitMQ namespace Volo.Abp.RabbitMQ
@ -17,6 +18,8 @@ namespace Volo.Abp.RabbitMQ
protected IConnectionPool ConnectionPool { get; } protected IConnectionPool ConnectionPool { get; }
protected IExceptionNotifier ExceptionNotifier { get; }
protected AbpTimer Timer { get; } protected AbpTimer Timer { get; }
protected ExchangeDeclareConfiguration Exchange { get; private set; } protected ExchangeDeclareConfiguration Exchange { get; private set; }
@ -35,10 +38,12 @@ namespace Volo.Abp.RabbitMQ
public RabbitMqMessageConsumer( public RabbitMqMessageConsumer(
IConnectionPool connectionPool, IConnectionPool connectionPool,
AbpTimer timer) AbpTimer timer,
IExceptionNotifier exceptionNotifier)
{ {
ConnectionPool = connectionPool; ConnectionPool = connectionPool;
Timer = timer; Timer = timer;
ExceptionNotifier = exceptionNotifier;
Logger = NullLogger<RabbitMqMessageConsumer>.Instance; Logger = NullLogger<RabbitMqMessageConsumer>.Instance;
QueueBindCommands = new ConcurrentQueue<QueueBindCommand>(); QueueBindCommands = new ConcurrentQueue<QueueBindCommand>();
@ -114,6 +119,7 @@ namespace Volo.Abp.RabbitMQ
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogException(ex, LogLevel.Warning); Logger.LogException(ex, LogLevel.Warning);
AsyncHelper.RunSync(() => ExceptionNotifier.NotifyAsync(ex, logLevel: LogLevel.Warning));
} }
} }
@ -180,6 +186,7 @@ namespace Volo.Abp.RabbitMQ
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogException(ex, LogLevel.Warning); Logger.LogException(ex, LogLevel.Warning);
AsyncHelper.RunSync(() => ExceptionNotifier.NotifyAsync(ex, logLevel: LogLevel.Warning));
} }
} }
@ -197,6 +204,7 @@ namespace Volo.Abp.RabbitMQ
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogException(ex); Logger.LogException(ex);
await ExceptionNotifier.NotifyAsync(ex);
} }
} }
@ -214,6 +222,7 @@ namespace Volo.Abp.RabbitMQ
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogException(ex, LogLevel.Warning); Logger.LogException(ex, LogLevel.Warning);
AsyncHelper.RunSync(() => ExceptionNotifier.NotifyAsync(ex, logLevel: LogLevel.Warning));
} }
} }

20
framework/src/Volo.Abp.Threading/Volo/Abp/Threading/AbpTimer.cs

@ -3,11 +3,12 @@ using System.Threading;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.ExceptionHandling;
namespace Volo.Abp.Threading namespace Volo.Abp.Threading
{ {
/// <summary> /// <summary>
/// A roboust timer implementation that ensures no overlapping occurs. It waits exactly specified <see cref="Period"/> between ticks. /// A robust timer implementation that ensures no overlapping occurs. It waits exactly specified <see cref="Period"/> between ticks.
/// </summary> /// </summary>
public class AbpTimer : ITransientDependency public class AbpTimer : ITransientDependency
{ {
@ -29,15 +30,23 @@ namespace Volo.Abp.Threading
public ILogger<AbpTimer> Logger { get; set; } public ILogger<AbpTimer> Logger { get; set; }
protected IExceptionNotifier ExceptionNotifier { get; }
private readonly Timer _taskTimer; private readonly Timer _taskTimer;
private volatile bool _performingTasks; private volatile bool _performingTasks;
private volatile bool _isRunning; private volatile bool _isRunning;
public AbpTimer() public AbpTimer(IExceptionNotifier exceptionNotifier)
{ {
ExceptionNotifier = exceptionNotifier;
Logger = NullLogger<AbpTimer>.Instance; Logger = NullLogger<AbpTimer>.Instance;
_taskTimer = new Timer(TimerCallBack, null, Timeout.Infinite, Timeout.Infinite); _taskTimer = new Timer(
TimerCallBack,
null,
Timeout.Infinite,
Timeout.Infinite
);
} }
public void Start(CancellationToken cancellationToken = default) public void Start(CancellationToken cancellationToken = default)
@ -89,9 +98,10 @@ namespace Volo.Abp.Threading
{ {
Elapsed.InvokeSafely(this, new EventArgs()); Elapsed.InvokeSafely(this, new EventArgs());
} }
catch catch(Exception ex)
{ {
Logger.LogException(ex);
AsyncHelper.RunSync(() => ExceptionNotifier.NotifyAsync(ex));
} }
finally finally
{ {

23
framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/ExceptionHandling/ExceptionTestController_Tests.cs

@ -1,6 +1,10 @@
using System.Net; using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NSubstitute;
using Shouldly; using Shouldly;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Http; using Volo.Abp.Http;
using Xunit; using Xunit;
@ -8,12 +12,27 @@ namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling
{ {
public class ExceptionTestController_Tests : AspNetCoreMvcTestBase public class ExceptionTestController_Tests : AspNetCoreMvcTestBase
{ {
private IExceptionSubscriber _fakeExceptionSubscriber;
protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
base.ConfigureServices(context, services);
_fakeExceptionSubscriber = Substitute.For<IExceptionSubscriber>();
services.AddSingleton(_fakeExceptionSubscriber);
}
[Fact] [Fact]
public async Task Should_Return_RemoteServiceErrorResponse_For_UserFriendlyException_For_Void_Return_Value() public async Task Should_Return_RemoteServiceErrorResponse_For_UserFriendlyException_For_Void_Return_Value()
{ {
var result = await GetResponseAsObjectAsync<RemoteServiceErrorResponse>("/api/exception-test/UserFriendlyException1", HttpStatusCode.Forbidden); var result = await GetResponseAsObjectAsync<RemoteServiceErrorResponse>("/api/exception-test/UserFriendlyException1", HttpStatusCode.Forbidden);
result.Error.ShouldNotBeNull(); result.Error.ShouldNotBeNull();
result.Error.Message.ShouldBe("This is a sample exception!"); result.Error.Message.ShouldBe("This is a sample exception!");
_fakeExceptionSubscriber
.Received()
.HandleAsync(Arg.Any<ExceptionNotificationContext>());
} }
[Fact] [Fact]
@ -24,6 +43,10 @@ namespace Volo.Abp.AspNetCore.Mvc.ExceptionHandling
"/api/exception-test/UserFriendlyException2" "/api/exception-test/UserFriendlyException2"
) )
); );
_fakeExceptionSubscriber
.DidNotReceive()
.HandleAsync(Arg.Any<ExceptionNotificationContext>());
} }
} }
} }

6
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AbpEntityFrameworkCoreTestModule.cs

@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Autofac; using Volo.Abp.Autofac;
using Volo.Abp.EntityFrameworkCore.Domain;
using Volo.Abp.EntityFrameworkCore.TestApp.SecondContext; using Volo.Abp.EntityFrameworkCore.TestApp.SecondContext;
using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext; using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext;
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
@ -21,6 +22,11 @@ namespace Volo.Abp.EntityFrameworkCore
[DependsOn(typeof(AbpEfCoreTestSecondContextModule))] [DependsOn(typeof(AbpEfCoreTestSecondContextModule))]
public class AbpEntityFrameworkCoreTestModule : AbpModule public class AbpEntityFrameworkCoreTestModule : AbpModule
{ {
public override void PreConfigureServices(ServiceConfigurationContext context)
{
TestEntityExtensionConfigurator.Configure();
}
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
context.Services.AddAbpDbContext<TestAppDbContext>(options => context.Services.AddAbpDbContext<TestAppDbContext>(options =>

25
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Domain/ExtraProperties_Tests.cs

@ -1,9 +1,32 @@
using Volo.Abp.TestApp.Testing; using System.Threading.Tasks;
using Shouldly;
using Volo.Abp.Data;
using Volo.Abp.TestApp.Testing;
using Xunit;
namespace Volo.Abp.EntityFrameworkCore.Domain namespace Volo.Abp.EntityFrameworkCore.Domain
{ {
public class ExtraProperties_Tests : ExtraProperties_Tests<AbpEntityFrameworkCoreTestModule> public class ExtraProperties_Tests : ExtraProperties_Tests<AbpEntityFrameworkCoreTestModule>
{ {
[Fact]
public async Task Should_Get_An_Extra_Property_Configured_As_Extension()
{
var london = await CityRepository.FindByNameAsync("London");
london.HasProperty("PhoneCode").ShouldBeTrue();
london.GetProperty<string>("PhoneCode").ShouldBe("42");
}
[Fact]
public async Task Should_Update_An_Existing_Extra_Property_Configured_As_Extension()
{
var london = await CityRepository.FindByNameAsync("London");
london.GetProperty<string>("PhoneCode").ShouldBe("42");
london.ExtraProperties["PhoneCode"] = "53";
await CityRepository.UpdateAsync(london);
var london2 = await CityRepository.FindByNameAsync("London");
london2.GetProperty<string>("PhoneCode").ShouldBe("53");
}
} }
} }

22
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Domain/TestEntityExtensionConfigurator.cs

@ -0,0 +1,22 @@
using Volo.Abp.EntityFrameworkCore.Extensions;
using Volo.Abp.TestApp.Domain;
using Volo.Abp.Threading;
namespace Volo.Abp.EntityFrameworkCore.Domain
{
public static class TestEntityExtensionConfigurator
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
OneTimeRunner.Run(() =>
{
EntityExtensionManager.AddProperty<City, string>(
"PhoneCode",
p => p.HasMaxLength(8)
);
});
}
}
}

3
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/TestMigrationsDbContext.cs

@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Extensions;
using Volo.Abp.EntityFrameworkCore.TestApp.SecondContext; using Volo.Abp.EntityFrameworkCore.TestApp.SecondContext;
using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext; using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext;
using Volo.Abp.TestApp.Domain; using Volo.Abp.TestApp.Domain;
@ -36,6 +37,8 @@ namespace Volo.Abp.EntityFrameworkCore
modelBuilder.Entity<City>(b => modelBuilder.Entity<City>(b =>
{ {
//b.ConfigureExtensions();
b.OwnsMany(c => c.Districts, d => b.OwnsMany(c => c.Districts, d =>
{ {
d.WithOwner().HasForeignKey(x => x.CityId); d.WithOwner().HasForeignKey(x => x.CityId);

3
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Extensions;
using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext; using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext;
using Volo.Abp.TestApp.Domain; using Volo.Abp.TestApp.Domain;
@ -43,6 +44,8 @@ namespace Volo.Abp.TestApp.EntityFrameworkCore
modelBuilder.Entity<City>(b => modelBuilder.Entity<City>(b =>
{ {
//b.ConfigureExtensions();
b.OwnsMany(c => c.Districts, d => b.OwnsMany(c => c.Districts, d =>
{ {
d.WithOwner().HasForeignKey(x => x.CityId); d.WithOwner().HasForeignKey(x => x.CityId);

4
framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/TestDataBuilder.cs

@ -21,7 +21,7 @@ namespace Volo.Abp.TestApp
private readonly IRepository<EntityWithIntPk, int> _entityWithIntPksRepository; private readonly IRepository<EntityWithIntPk, int> _entityWithIntPksRepository;
public TestDataBuilder( public TestDataBuilder(
IBasicRepository<Person, Guid> personRepository, IBasicRepository<Person, Guid> personRepository,
ICityRepository cityRepository, ICityRepository cityRepository,
IRepository<EntityWithIntPk, int> entityWithIntPksRepository) IRepository<EntityWithIntPk, int> entityWithIntPksRepository)
{ {
@ -46,7 +46,7 @@ namespace Volo.Abp.TestApp
await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Tokyo")); await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Tokyo"));
await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Madrid")); await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Madrid"));
await _cityRepository.InsertAsync(new City(LondonCityId, "London") { ExtraProperties = { { "Population", 10_470_000 } } }); await _cityRepository.InsertAsync(new City(LondonCityId, "London") { ExtraProperties = { { "Population", 10_470_000 }, { "PhoneCode", "42" } } });
await _cityRepository.InsertAsync(istanbul); await _cityRepository.InsertAsync(istanbul);
await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Paris")); await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Paris"));
await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Washington")); await _cityRepository.InsertAsync(new City(Guid.NewGuid(), "Washington"));

1
framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Testing/ExtraProperties_Tests.cs

@ -41,6 +41,7 @@ namespace Volo.Abp.TestApp.Testing
public async Task Should_Update_An_Existing_Extra_Property() public async Task Should_Update_An_Existing_Extra_Property()
{ {
var london = await CityRepository.FindByNameAsync("London"); var london = await CityRepository.FindByNameAsync("London");
london.GetProperty<int>("Population").ShouldBe(10_470_000);
london.ExtraProperties["Population"] = 11_000_042; london.ExtraProperties["Population"] = 11_000_042;
await CityRepository.UpdateAsync(london); await CityRepository.UpdateAsync(london);

8
modules/audit-logging/src/Volo.Abp.AuditLogging.EntityFrameworkCore/Volo/Abp/AuditLogging/EntityFrameworkCore/AbpAuditLoggingDbContextModelBuilderExtensions.cs

@ -25,7 +25,7 @@ namespace Volo.Abp.AuditLogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "AuditLogs", options.Schema); b.ToTable(options.TablePrefix + "AuditLogs", options.Schema);
b.ConfigureExtraProperties(); b.ConfigureByConvention();
b.Property(x => x.ApplicationName).HasMaxLength(AuditLogConsts.MaxApplicationNameLength).HasColumnName(nameof(AuditLog.ApplicationName)); b.Property(x => x.ApplicationName).HasMaxLength(AuditLogConsts.MaxApplicationNameLength).HasColumnName(nameof(AuditLog.ApplicationName));
b.Property(x => x.ClientIpAddress).HasMaxLength(AuditLogConsts.MaxClientIpAddressLength).HasColumnName(nameof(AuditLog.ClientIpAddress)); b.Property(x => x.ClientIpAddress).HasMaxLength(AuditLogConsts.MaxClientIpAddressLength).HasColumnName(nameof(AuditLog.ClientIpAddress));
@ -56,7 +56,7 @@ namespace Volo.Abp.AuditLogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "AuditLogActions", options.Schema); b.ToTable(options.TablePrefix + "AuditLogActions", options.Schema);
b.ConfigureExtraProperties(); b.ConfigureByConvention();
b.Property(x => x.AuditLogId).HasColumnName(nameof(AuditLogAction.AuditLogId)); b.Property(x => x.AuditLogId).HasColumnName(nameof(AuditLogAction.AuditLogId));
b.Property(x => x.ServiceName).HasMaxLength(AuditLogActionConsts.MaxServiceNameLength).HasColumnName(nameof(AuditLogAction.ServiceName)); b.Property(x => x.ServiceName).HasMaxLength(AuditLogActionConsts.MaxServiceNameLength).HasColumnName(nameof(AuditLogAction.ServiceName));
@ -73,7 +73,7 @@ namespace Volo.Abp.AuditLogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "EntityChanges", options.Schema); b.ToTable(options.TablePrefix + "EntityChanges", options.Schema);
b.ConfigureExtraProperties(); b.ConfigureByConvention();
b.Property(x => x.EntityTypeFullName).HasMaxLength(EntityChangeConsts.MaxEntityTypeFullNameLength).IsRequired().HasColumnName(nameof(EntityChange.EntityTypeFullName)); b.Property(x => x.EntityTypeFullName).HasMaxLength(EntityChangeConsts.MaxEntityTypeFullNameLength).IsRequired().HasColumnName(nameof(EntityChange.EntityTypeFullName));
b.Property(x => x.EntityId).HasMaxLength(EntityChangeConsts.MaxEntityIdLength).IsRequired().HasColumnName(nameof(EntityChange.EntityId)); b.Property(x => x.EntityId).HasMaxLength(EntityChangeConsts.MaxEntityIdLength).IsRequired().HasColumnName(nameof(EntityChange.EntityId));
@ -92,6 +92,8 @@ namespace Volo.Abp.AuditLogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "EntityPropertyChanges", options.Schema); b.ToTable(options.TablePrefix + "EntityPropertyChanges", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.NewValue).HasMaxLength(EntityPropertyChangeConsts.MaxNewValueLength).HasColumnName(nameof(EntityPropertyChange.NewValue)); b.Property(x => x.NewValue).HasMaxLength(EntityPropertyChangeConsts.MaxNewValueLength).HasColumnName(nameof(EntityPropertyChange.NewValue));
b.Property(x => x.PropertyName).HasMaxLength(EntityPropertyChangeConsts.MaxPropertyNameLength).IsRequired().HasColumnName(nameof(EntityPropertyChange.PropertyName)); b.Property(x => x.PropertyName).HasMaxLength(EntityPropertyChangeConsts.MaxPropertyNameLength).IsRequired().HasColumnName(nameof(EntityPropertyChange.PropertyName));
b.Property(x => x.PropertyTypeFullName).HasMaxLength(EntityPropertyChangeConsts.MaxPropertyTypeFullNameLength).IsRequired().HasColumnName(nameof(EntityPropertyChange.PropertyTypeFullName)); b.Property(x => x.PropertyTypeFullName).HasMaxLength(EntityPropertyChangeConsts.MaxPropertyTypeFullNameLength).IsRequired().HasColumnName(nameof(EntityPropertyChange.PropertyTypeFullName));

3
modules/background-jobs/src/Volo.Abp.BackgroundJobs.EntityFrameworkCore/Volo/Abp/BackgroundJobs/EntityFrameworkCore/BackgroundJobsDbContextModelCreatingExtensions.cs

@ -23,8 +23,7 @@ namespace Volo.Abp.BackgroundJobs.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "BackgroundJobs", options.Schema); b.ToTable(options.TablePrefix + "BackgroundJobs", options.Schema);
b.ConfigureCreationTime(); b.ConfigureByConvention();
b.ConfigureExtraProperties();
b.Property(x => x.JobName).IsRequired().HasMaxLength(BackgroundJobRecordConsts.MaxJobNameLength); b.Property(x => x.JobName).IsRequired().HasMaxLength(BackgroundJobRecordConsts.MaxJobNameLength);
b.Property(x => x.JobArgs).IsRequired().HasMaxLength(BackgroundJobRecordConsts.MaxJobArgsLength); b.Property(x => x.JobArgs).IsRequired().HasMaxLength(BackgroundJobRecordConsts.MaxJobArgsLength);

12
modules/blogging/src/Volo.Blogging.EntityFrameworkCore/Volo/Blogging/EntityFrameworkCore/BloggingDbContextModelBuilderExtensions.cs

@ -31,15 +31,15 @@ namespace Volo.Blogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Users", options.Schema); b.ToTable(options.TablePrefix + "Users", options.Schema);
b.ConfigureByConvention();
b.ConfigureAbpUser(); b.ConfigureAbpUser();
b.ConfigureExtraProperties();
}); });
builder.Entity<Blog>(b => builder.Entity<Blog>(b =>
{ {
b.ToTable(options.TablePrefix + "Blogs", options.Schema); b.ToTable(options.TablePrefix + "Blogs", options.Schema);
b.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
b.Property(x => x.Name).IsRequired().HasMaxLength(BlogConsts.MaxNameLength).HasColumnName(nameof(Blog.Name)); b.Property(x => x.Name).IsRequired().HasMaxLength(BlogConsts.MaxNameLength).HasColumnName(nameof(Blog.Name));
b.Property(x => x.ShortName).IsRequired().HasMaxLength(BlogConsts.MaxShortNameLength).HasColumnName(nameof(Blog.ShortName)); b.Property(x => x.ShortName).IsRequired().HasMaxLength(BlogConsts.MaxShortNameLength).HasColumnName(nameof(Blog.ShortName));
@ -50,7 +50,7 @@ namespace Volo.Blogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Posts", options.Schema); b.ToTable(options.TablePrefix + "Posts", options.Schema);
b.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
b.Property(x => x.BlogId).HasColumnName(nameof(Post.BlogId)); b.Property(x => x.BlogId).HasColumnName(nameof(Post.BlogId));
b.Property(x => x.Title).IsRequired().HasMaxLength(PostConsts.MaxTitleLength).HasColumnName(nameof(Post.Title)); b.Property(x => x.Title).IsRequired().HasMaxLength(PostConsts.MaxTitleLength).HasColumnName(nameof(Post.Title));
@ -67,7 +67,7 @@ namespace Volo.Blogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Comments", options.Schema); b.ToTable(options.TablePrefix + "Comments", options.Schema);
b.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
b.Property(x => x.Text).IsRequired().HasMaxLength(CommentConsts.MaxTextLength).HasColumnName(nameof(Comment.Text)); b.Property(x => x.Text).IsRequired().HasMaxLength(CommentConsts.MaxTextLength).HasColumnName(nameof(Comment.Text));
b.Property(x => x.RepliedCommentId).HasColumnName(nameof(Comment.RepliedCommentId)); b.Property(x => x.RepliedCommentId).HasColumnName(nameof(Comment.RepliedCommentId));
@ -81,7 +81,7 @@ namespace Volo.Blogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Tags", options.Schema); b.ToTable(options.TablePrefix + "Tags", options.Schema);
b.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
b.Property(x => x.Name).IsRequired().HasMaxLength(TagConsts.MaxNameLength).HasColumnName(nameof(Tag.Name)); b.Property(x => x.Name).IsRequired().HasMaxLength(TagConsts.MaxNameLength).HasColumnName(nameof(Tag.Name));
b.Property(x => x.Description).HasMaxLength(TagConsts.MaxDescriptionLength).HasColumnName(nameof(Tag.Description)); b.Property(x => x.Description).HasMaxLength(TagConsts.MaxDescriptionLength).HasColumnName(nameof(Tag.Description));
@ -94,6 +94,8 @@ namespace Volo.Blogging.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "PostTags", options.Schema); b.ToTable(options.TablePrefix + "PostTags", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.PostId).HasColumnName(nameof(PostTag.PostId)); b.Property(x => x.PostId).HasColumnName(nameof(PostTag.PostId));
b.Property(x => x.TagId).HasColumnName(nameof(PostTag.TagId)); b.Property(x => x.TagId).HasColumnName(nameof(PostTag.TagId));

2
modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContextModelBuilderExtensions.cs

@ -63,6 +63,8 @@ namespace Volo.Docs.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "DocumentContributors", options.Schema); b.ToTable(options.TablePrefix + "DocumentContributors", options.Schema);
b.ConfigureByConvention();
b.HasKey(x => new { x.DocumentId, x.Username }); b.HasKey(x => new { x.DocumentId, x.Username });
}); });
} }

47
modules/docs/src/Volo.Docs.Web/Markdown/MarkdownDocumentToHtmlConverter.cs

@ -1,4 +1,5 @@
using System; using System;
using System.Diagnostics;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
@ -24,9 +25,9 @@ namespace Volo.Docs.Markdown
} }
private const string MdLinkFormat = "[{0}]({1}{2}/{3}/{4}{5}/{6})"; private const string MdLinkFormat = "[{0}]({1}{2}/{3}/{4}{5}/{6})";
private const string MarkdownLinkRegExp = @"\[(.*?)\]\((.*?)\)"; private const string MarkdownLinkRegExp = @"\[(.*?)\]\(((.*?)(\?(.*?))*?)\)";
private const string AnchorLinkRegExp = @"<a[^>]+href=\""(.*?)\""[^>]*>(.*)?</a>"; private const string AnchorLinkRegExp = @"<a[^>]+href=\""(.*?)\""[^>]*>(.*)?</a>";
public virtual string Convert(ProjectDto project, DocumentWithDetailsDto document, string version, public virtual string Convert(ProjectDto project, DocumentWithDetailsDto document, string version,
string languageCode) string languageCode)
{ {
@ -45,7 +46,7 @@ namespace Volo.Docs.Markdown
return _markdownConverter.ConvertToHtml(content); return _markdownConverter.ConvertToHtml(content);
} }
protected virtual string NormalizeLinks( protected virtual string NormalizeLinks(
string content, string content,
string projectShortName, string projectShortName,
@ -53,10 +54,29 @@ namespace Volo.Docs.Markdown
string documentLocalDirectory, string documentLocalDirectory,
string languageCode) string languageCode)
{ {
var normalized = Regex.Replace(content, MarkdownLinkRegExp, delegate (Match match)
var normalized = NormalizeMdLinks(content, projectShortName, version, documentLocalDirectory, languageCode);
normalized = NormalizeAnchorLinks(projectShortName, version, documentLocalDirectory, languageCode, normalized);
return normalized;
}
private string NormalizeMdLinks(string content,
string projectShortName,
string version,
string documentLocalDirectory,
string languageCode)
{
return Regex.Replace(content, MarkdownLinkRegExp, delegate (Match match)
{ {
var link = match.Groups[2].Value; var link = match.Groups[3].Value;
if (UrlHelper.IsExternalLink(link) || !link.EndsWith(".md")) if (UrlHelper.IsExternalLink(link))
{
return match.Value;
}
if (!link.EndsWith(".md"))
{ {
return match.Value; return match.Value;
} }
@ -64,6 +84,13 @@ namespace Volo.Docs.Markdown
var displayText = match.Groups[1].Value; var displayText = match.Groups[1].Value;
var documentName = RemoveFileExtension(link); var documentName = RemoveFileExtension(link);
var hasUrlParameter = match.Groups.Count > 3 && !match.Groups[4].Value.IsNullOrEmpty();
if (hasUrlParameter)
{
documentName += match.Groups[4].Value;
}
var documentLocalDirectoryNormalized = documentLocalDirectory.TrimStart('/').TrimEnd('/'); var documentLocalDirectoryNormalized = documentLocalDirectory.TrimStart('/').TrimEnd('/');
if (!string.IsNullOrWhiteSpace(documentLocalDirectoryNormalized)) if (!string.IsNullOrWhiteSpace(documentLocalDirectoryNormalized))
{ {
@ -81,8 +108,12 @@ namespace Volo.Docs.Markdown
documentName documentName
); );
}); });
}
normalized = Regex.Replace(normalized, AnchorLinkRegExp, delegate (Match match) private string NormalizeAnchorLinks(string projectShortName, string version, string documentLocalDirectory,
string languageCode, string normalized)
{
return Regex.Replace(normalized, AnchorLinkRegExp, delegate (Match match)
{ {
var link = match.Groups[1].Value; var link = match.Groups[1].Value;
if (UrlHelper.IsExternalLink(link)) if (UrlHelper.IsExternalLink(link))
@ -109,8 +140,6 @@ namespace Volo.Docs.Markdown
documentName documentName
); );
}); });
return normalized;
} }
private static string RemoveFileExtension(string documentName) private static string RemoveFileExtension(string documentName)

3
modules/feature-management/src/Volo.Abp.FeatureManagement.EntityFrameworkCore/Volo/Abp/FeatureManagement/EntityFrameworkCore/FeatureManagementDbContextModelCreatingExtensions.cs

@ -1,5 +1,6 @@
using System; using System;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
namespace Volo.Abp.FeatureManagement.EntityFrameworkCore namespace Volo.Abp.FeatureManagement.EntityFrameworkCore
{ {
@ -22,6 +23,8 @@ namespace Volo.Abp.FeatureManagement.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "FeatureValues", options.Schema); b.ToTable(options.TablePrefix + "FeatureValues", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.Name).HasMaxLength(FeatureValueConsts.MaxNameLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(FeatureValueConsts.MaxNameLength).IsRequired();
b.Property(x => x.Value).HasMaxLength(FeatureValueConsts.MaxValueLength).IsRequired(); b.Property(x => x.Value).HasMaxLength(FeatureValueConsts.MaxValueLength).IsRequired();
b.Property(x => x.ProviderName).HasMaxLength(FeatureValueConsts.MaxProviderNameLength); b.Property(x => x.ProviderName).HasMaxLength(FeatureValueConsts.MaxProviderNameLength);

22
modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContextModelBuilderExtensions.cs

@ -1,6 +1,7 @@
using System; using System;
using JetBrains.Annotations; using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Extensions;
using Volo.Abp.EntityFrameworkCore.Modeling; using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.Users.EntityFrameworkCore; using Volo.Abp.Users.EntityFrameworkCore;
@ -25,7 +26,7 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Users", options.Schema); b.ToTable(options.TablePrefix + "Users", options.Schema);
b.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
b.ConfigureAbpUser(); b.ConfigureAbpUser();
b.Property(u => u.NormalizedUserName).IsRequired().HasMaxLength(IdentityUserConsts.MaxNormalizedUserNameLength).HasColumnName(nameof(IdentityUser.NormalizedUserName)); b.Property(u => u.NormalizedUserName).IsRequired().HasMaxLength(IdentityUserConsts.MaxNormalizedUserNameLength).HasColumnName(nameof(IdentityUser.NormalizedUserName));
@ -35,12 +36,12 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
b.Property(u => u.TwoFactorEnabled).HasDefaultValue(false).HasColumnName(nameof(IdentityUser.TwoFactorEnabled)); b.Property(u => u.TwoFactorEnabled).HasDefaultValue(false).HasColumnName(nameof(IdentityUser.TwoFactorEnabled));
b.Property(u => u.LockoutEnabled).HasDefaultValue(false).HasColumnName(nameof(IdentityUser.LockoutEnabled)); b.Property(u => u.LockoutEnabled).HasDefaultValue(false).HasColumnName(nameof(IdentityUser.LockoutEnabled));
b.Property(u => u.AccessFailedCount).HasDefaultValue(0).HasColumnName(nameof(IdentityUser.AccessFailedCount)); b.Property(u => u.AccessFailedCount).HasDefaultValue(0).HasColumnName(nameof(IdentityUser.AccessFailedCount));
b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired(); b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired(); b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
b.HasMany(u => u.Tokens).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); b.HasMany(u => u.Tokens).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
b.HasIndex(u => u.NormalizedUserName); b.HasIndex(u => u.NormalizedUserName);
b.HasIndex(u => u.NormalizedEmail); b.HasIndex(u => u.NormalizedEmail);
b.HasIndex(u => u.UserName); b.HasIndex(u => u.UserName);
@ -51,6 +52,8 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "UserClaims", options.Schema); b.ToTable(options.TablePrefix + "UserClaims", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.Id).ValueGeneratedNever(); b.Property(x => x.Id).ValueGeneratedNever();
b.Property(uc => uc.ClaimType).HasMaxLength(IdentityUserClaimConsts.MaxClaimTypeLength).IsRequired(); b.Property(uc => uc.ClaimType).HasMaxLength(IdentityUserClaimConsts.MaxClaimTypeLength).IsRequired();
@ -63,6 +66,8 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "UserRoles", options.Schema); b.ToTable(options.TablePrefix + "UserRoles", options.Schema);
b.ConfigureByConvention();
b.HasKey(ur => new { ur.UserId, ur.RoleId }); b.HasKey(ur => new { ur.UserId, ur.RoleId });
b.HasOne<IdentityRole>().WithMany().HasForeignKey(ur => ur.RoleId).IsRequired(); b.HasOne<IdentityRole>().WithMany().HasForeignKey(ur => ur.RoleId).IsRequired();
@ -75,6 +80,8 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "UserLogins", options.Schema); b.ToTable(options.TablePrefix + "UserLogins", options.Schema);
b.ConfigureByConvention();
b.HasKey(x => new { x.UserId, x.LoginProvider }); b.HasKey(x => new { x.UserId, x.LoginProvider });
b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserLoginConsts.MaxLoginProviderLength).IsRequired(); b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserLoginConsts.MaxLoginProviderLength).IsRequired();
@ -88,6 +95,8 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "UserTokens", options.Schema); b.ToTable(options.TablePrefix + "UserTokens", options.Schema);
b.ConfigureByConvention();
b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name }); b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserTokenConsts.MaxLoginProviderLength).IsRequired(); b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserTokenConsts.MaxLoginProviderLength).IsRequired();
@ -98,8 +107,7 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Roles", options.Schema); b.ToTable(options.TablePrefix + "Roles", options.Schema);
b.ConfigureConcurrencyStamp(); b.ConfigureByConvention();
b.ConfigureExtraProperties();
b.Property(r => r.Name).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNameLength); b.Property(r => r.Name).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNameLength);
b.Property(r => r.NormalizedName).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNormalizedNameLength); b.Property(r => r.NormalizedName).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNormalizedNameLength);
@ -117,6 +125,8 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "RoleClaims", options.Schema); b.ToTable(options.TablePrefix + "RoleClaims", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.Id).ValueGeneratedNever(); b.Property(x => x.Id).ValueGeneratedNever();
b.Property(uc => uc.ClaimType).HasMaxLength(IdentityRoleClaimConsts.MaxClaimTypeLength).IsRequired(); b.Property(uc => uc.ClaimType).HasMaxLength(IdentityRoleClaimConsts.MaxClaimTypeLength).IsRequired();
@ -129,7 +139,7 @@ namespace Volo.Abp.Identity.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "ClaimTypes", options.Schema); b.ToTable(options.TablePrefix + "ClaimTypes", options.Schema);
b.ConfigureExtraProperties(); b.ConfigureByConvention();
b.Property(uc => uc.Name).HasMaxLength(IdentityClaimTypeConsts.MaxNameLength).IsRequired(); // make unique b.Property(uc => uc.Name).HasMaxLength(IdentityClaimTypeConsts.MaxNameLength).IsRequired(); // make unique
b.Property(uc => uc.Regex).HasMaxLength(IdentityClaimTypeConsts.MaxRegexLength); b.Property(uc => uc.Regex).HasMaxLength(IdentityClaimTypeConsts.MaxRegexLength);

286
modules/identityserver/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/IdentityServerDbContextModelCreatingExtensions.cs

@ -28,264 +28,292 @@ namespace Volo.Abp.IdentityServer.EntityFrameworkCore
optionsAction?.Invoke(options); optionsAction?.Invoke(options);
builder.Entity<Client>(client => builder.Entity<Client>(b =>
{ {
client.ToTable(options.TablePrefix + "Clients", options.Schema); b.ToTable(options.TablePrefix + "Clients", options.Schema);
client.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
client.Property(x => x.ClientId).HasMaxLength(ClientConsts.ClientIdMaxLength).IsRequired(); b.Property(x => x.ClientId).HasMaxLength(ClientConsts.ClientIdMaxLength).IsRequired();
client.Property(x => x.ProtocolType).HasMaxLength(ClientConsts.ProtocolTypeMaxLength).IsRequired(); b.Property(x => x.ProtocolType).HasMaxLength(ClientConsts.ProtocolTypeMaxLength).IsRequired();
client.Property(x => x.ClientName).HasMaxLength(ClientConsts.ClientNameMaxLength); b.Property(x => x.ClientName).HasMaxLength(ClientConsts.ClientNameMaxLength);
client.Property(x => x.ClientUri).HasMaxLength(ClientConsts.ClientUriMaxLength); b.Property(x => x.ClientUri).HasMaxLength(ClientConsts.ClientUriMaxLength);
client.Property(x => x.LogoUri).HasMaxLength(ClientConsts.LogoUriMaxLength); b.Property(x => x.LogoUri).HasMaxLength(ClientConsts.LogoUriMaxLength);
client.Property(x => x.Description).HasMaxLength(ClientConsts.DescriptionMaxLength); b.Property(x => x.Description).HasMaxLength(ClientConsts.DescriptionMaxLength);
client.Property(x => x.FrontChannelLogoutUri).HasMaxLength(ClientConsts.FrontChannelLogoutUriMaxLength); b.Property(x => x.FrontChannelLogoutUri).HasMaxLength(ClientConsts.FrontChannelLogoutUriMaxLength);
client.Property(x => x.BackChannelLogoutUri).HasMaxLength(ClientConsts.BackChannelLogoutUriMaxLength); b.Property(x => x.BackChannelLogoutUri).HasMaxLength(ClientConsts.BackChannelLogoutUriMaxLength);
client.Property(x => x.ClientClaimsPrefix).HasMaxLength(ClientConsts.ClientClaimsPrefixMaxLength); b.Property(x => x.ClientClaimsPrefix).HasMaxLength(ClientConsts.ClientClaimsPrefixMaxLength);
client.Property(x => x.PairWiseSubjectSalt).HasMaxLength(ClientConsts.PairWiseSubjectSaltMaxLength); b.Property(x => x.PairWiseSubjectSalt).HasMaxLength(ClientConsts.PairWiseSubjectSaltMaxLength);
client.Property(x => x.UserCodeType).HasMaxLength(ClientConsts.UserCodeTypeMaxLength); b.Property(x => x.UserCodeType).HasMaxLength(ClientConsts.UserCodeTypeMaxLength);
client.HasMany(x => x.AllowedScopes).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.AllowedScopes).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.ClientSecrets).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.ClientSecrets).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.AllowedGrantTypes).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.AllowedGrantTypes).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.AllowedCorsOrigins).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.AllowedCorsOrigins).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.RedirectUris).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.RedirectUris).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.PostLogoutRedirectUris).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.PostLogoutRedirectUris).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.IdentityProviderRestrictions).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.IdentityProviderRestrictions).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.Claims).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.Claims).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasMany(x => x.Properties).WithOne().HasForeignKey(x => x.ClientId).IsRequired(); b.HasMany(x => x.Properties).WithOne().HasForeignKey(x => x.ClientId).IsRequired();
client.HasIndex(x => x.ClientId); b.HasIndex(x => x.ClientId);
}); });
builder.Entity<ClientGrantType>(grantType => builder.Entity<ClientGrantType>(b =>
{ {
grantType.ToTable(options.TablePrefix + "ClientGrantTypes", options.Schema); b.ToTable(options.TablePrefix + "ClientGrantTypes", options.Schema);
b.ConfigureByConvention();
grantType.HasKey(x => new { x.ClientId, x.GrantType }); b.HasKey(x => new { x.ClientId, x.GrantType });
grantType.Property(x => x.GrantType).HasMaxLength(ClientGrantTypeConsts.GrantTypeMaxLength).IsRequired(); b.Property(x => x.GrantType).HasMaxLength(ClientGrantTypeConsts.GrantTypeMaxLength).IsRequired();
}); });
builder.Entity<ClientRedirectUri>(redirectUri => builder.Entity<ClientRedirectUri>(b =>
{ {
redirectUri.ToTable(options.TablePrefix + "ClientRedirectUris", options.Schema); b.ToTable(options.TablePrefix + "ClientRedirectUris", options.Schema);
redirectUri.HasKey(x => new { x.ClientId, x.RedirectUri }); b.ConfigureByConvention();
b.HasKey(x => new { x.ClientId, x.RedirectUri });
if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql) if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql)
{ {
redirectUri.Property(x => x.RedirectUri).HasMaxLength(300).IsRequired(); b.Property(x => x.RedirectUri).HasMaxLength(300).IsRequired();
} }
else else
{ {
redirectUri.Property(x => x.RedirectUri).HasMaxLength(ClientRedirectUriConsts.RedirectUriMaxLength).IsRequired(); b.Property(x => x.RedirectUri).HasMaxLength(ClientRedirectUriConsts.RedirectUriMaxLength).IsRequired();
} }
}); });
builder.Entity<ClientPostLogoutRedirectUri>(postLogoutRedirectUri => builder.Entity<ClientPostLogoutRedirectUri>(b =>
{ {
postLogoutRedirectUri.ToTable(options.TablePrefix + "ClientPostLogoutRedirectUris", options.Schema); b.ToTable(options.TablePrefix + "ClientPostLogoutRedirectUris", options.Schema);
b.ConfigureByConvention();
postLogoutRedirectUri.HasKey(x => new { x.ClientId, x.PostLogoutRedirectUri }); b.HasKey(x => new { x.ClientId, x.PostLogoutRedirectUri });
if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql) if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql)
{ {
postLogoutRedirectUri.Property(x => x.PostLogoutRedirectUri).HasMaxLength(300).IsRequired(); b.Property(x => x.PostLogoutRedirectUri).HasMaxLength(300).IsRequired();
} }
else else
{ {
postLogoutRedirectUri.Property(x => x.PostLogoutRedirectUri).HasMaxLength(ClientPostLogoutRedirectUriConsts.PostLogoutRedirectUriMaxLength).IsRequired(); b.Property(x => x.PostLogoutRedirectUri).HasMaxLength(ClientPostLogoutRedirectUriConsts.PostLogoutRedirectUriMaxLength).IsRequired();
} }
}); });
builder.Entity<ClientScope>(scope => builder.Entity<ClientScope>(b =>
{ {
scope.ToTable(options.TablePrefix + "ClientScopes", options.Schema); b.ToTable(options.TablePrefix + "ClientScopes", options.Schema);
scope.HasKey(x => new { x.ClientId, x.Scope }); b.ConfigureByConvention();
b.HasKey(x => new { x.ClientId, x.Scope });
scope.Property(x => x.Scope).HasMaxLength(ClientScopeConsts.ScopeMaxLength).IsRequired(); b.Property(x => x.Scope).HasMaxLength(ClientScopeConsts.ScopeMaxLength).IsRequired();
}); });
builder.Entity<ClientSecret>(secret => builder.Entity<ClientSecret>(b =>
{ {
secret.ToTable(options.TablePrefix + "ClientSecrets", options.Schema); b.ToTable(options.TablePrefix + "ClientSecrets", options.Schema);
secret.HasKey(x => new { x.ClientId, x.Type, x.Value }); b.ConfigureByConvention();
secret.Property(x => x.Type).HasMaxLength(SecretConsts.TypeMaxLength).IsRequired(); b.HasKey(x => new { x.ClientId, x.Type, x.Value });
b.Property(x => x.Type).HasMaxLength(SecretConsts.TypeMaxLength).IsRequired();
if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql) if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql)
{ {
secret.Property(x => x.Value).HasMaxLength(300).IsRequired(); b.Property(x => x.Value).HasMaxLength(300).IsRequired();
} }
else else
{ {
secret.Property(x => x.Value).HasMaxLength(SecretConsts.ValueMaxLength).IsRequired(); b.Property(x => x.Value).HasMaxLength(SecretConsts.ValueMaxLength).IsRequired();
} }
secret.Property(x => x.Description).HasMaxLength(SecretConsts.DescriptionMaxLength); b.Property(x => x.Description).HasMaxLength(SecretConsts.DescriptionMaxLength);
}); });
builder.Entity<ClientClaim>(claim => builder.Entity<ClientClaim>(b =>
{ {
claim.ToTable(options.TablePrefix + "ClientClaims", options.Schema); b.ToTable(options.TablePrefix + "ClientClaims", options.Schema);
claim.HasKey(x => new { x.ClientId, x.Type, x.Value }); b.ConfigureByConvention();
claim.Property(x => x.Type).HasMaxLength(ClientClaimConsts.TypeMaxLength).IsRequired(); b.HasKey(x => new { x.ClientId, x.Type, x.Value });
claim.Property(x => x.Value).HasMaxLength(ClientClaimConsts.ValueMaxLength).IsRequired();
b.Property(x => x.Type).HasMaxLength(ClientClaimConsts.TypeMaxLength).IsRequired();
b.Property(x => x.Value).HasMaxLength(ClientClaimConsts.ValueMaxLength).IsRequired();
}); });
builder.Entity<ClientIdPRestriction>(idPRestriction => builder.Entity<ClientIdPRestriction>(b =>
{ {
idPRestriction.ToTable(options.TablePrefix + "ClientIdPRestrictions", options.Schema); b.ToTable(options.TablePrefix + "ClientIdPRestrictions", options.Schema);
b.ConfigureByConvention();
idPRestriction.HasKey(x => new { x.ClientId, x.Provider }); b.HasKey(x => new { x.ClientId, x.Provider });
idPRestriction.Property(x => x.Provider).HasMaxLength(ClientIdPRestrictionConsts.ProviderMaxLength).IsRequired(); b.Property(x => x.Provider).HasMaxLength(ClientIdPRestrictionConsts.ProviderMaxLength).IsRequired();
}); });
builder.Entity<ClientCorsOrigin>(corsOrigin => builder.Entity<ClientCorsOrigin>(b =>
{ {
corsOrigin.ToTable(options.TablePrefix + "ClientCorsOrigins", options.Schema); b.ToTable(options.TablePrefix + "ClientCorsOrigins", options.Schema);
corsOrigin.HasKey(x => new { x.ClientId, x.Origin }); b.ConfigureByConvention();
corsOrigin.Property(x => x.Origin).HasMaxLength(ClientCorsOriginConsts.OriginMaxLength).IsRequired(); b.HasKey(x => new { x.ClientId, x.Origin });
b.Property(x => x.Origin).HasMaxLength(ClientCorsOriginConsts.OriginMaxLength).IsRequired();
}); });
builder.Entity<ClientProperty>(property => builder.Entity<ClientProperty>(b =>
{ {
property.ToTable(options.TablePrefix + "ClientProperties", options.Schema); b.ToTable(options.TablePrefix + "ClientProperties", options.Schema);
b.ConfigureByConvention();
property.HasKey(x => new { x.ClientId, x.Key }); b.HasKey(x => new { x.ClientId, x.Key });
property.Property(x => x.Key).HasMaxLength(ClientPropertyConsts.KeyMaxLength).IsRequired(); b.Property(x => x.Key).HasMaxLength(ClientPropertyConsts.KeyMaxLength).IsRequired();
property.Property(x => x.Value).HasMaxLength(ClientPropertyConsts.ValueMaxLength).IsRequired(); b.Property(x => x.Value).HasMaxLength(ClientPropertyConsts.ValueMaxLength).IsRequired();
}); });
builder.Entity<PersistedGrant>(grant => builder.Entity<PersistedGrant>(b =>
{ {
grant.ToTable(options.TablePrefix + "PersistedGrants", options.Schema); b.ToTable(options.TablePrefix + "PersistedGrants", options.Schema);
grant.ConfigureExtraProperties(); b.ConfigureByConvention();
grant.Property(x => x.Key).HasMaxLength(PersistedGrantConsts.KeyMaxLength).ValueGeneratedNever(); b.Property(x => x.Key).HasMaxLength(PersistedGrantConsts.KeyMaxLength).ValueGeneratedNever();
grant.Property(x => x.Type).HasMaxLength(PersistedGrantConsts.TypeMaxLength).IsRequired(); b.Property(x => x.Type).HasMaxLength(PersistedGrantConsts.TypeMaxLength).IsRequired();
grant.Property(x => x.SubjectId).HasMaxLength(PersistedGrantConsts.SubjectIdMaxLength); b.Property(x => x.SubjectId).HasMaxLength(PersistedGrantConsts.SubjectIdMaxLength);
grant.Property(x => x.ClientId).HasMaxLength(PersistedGrantConsts.ClientIdMaxLength).IsRequired(); b.Property(x => x.ClientId).HasMaxLength(PersistedGrantConsts.ClientIdMaxLength).IsRequired();
grant.Property(x => x.CreationTime).IsRequired(); b.Property(x => x.CreationTime).IsRequired();
if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql) if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql)
{ {
grant.Property(x => x.Data).HasMaxLength(10000).IsRequired(); b.Property(x => x.Data).HasMaxLength(10000).IsRequired();
} }
else else
{ {
grant.Property(x => x.Data).HasMaxLength(PersistedGrantConsts.DataMaxLength).IsRequired(); b.Property(x => x.Data).HasMaxLength(PersistedGrantConsts.DataMaxLength).IsRequired();
} }
grant.HasKey(x => x.Key); //TODO: What about Id!!! b.HasKey(x => x.Key); //TODO: What about Id!!!
grant.HasIndex(x => new { x.SubjectId, x.ClientId, x.Type }); b.HasIndex(x => new { x.SubjectId, x.ClientId, x.Type });
grant.HasIndex(x => x.Expiration); b.HasIndex(x => x.Expiration);
}); });
builder.Entity<IdentityResource>(identityResource => builder.Entity<IdentityResource>(b =>
{ {
identityResource.ToTable(options.TablePrefix + "IdentityResources", options.Schema); b.ToTable(options.TablePrefix + "IdentityResources", options.Schema);
identityResource.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
identityResource.Property(x => x.Name).HasMaxLength(IdentityResourceConsts.NameMaxLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(IdentityResourceConsts.NameMaxLength).IsRequired();
identityResource.Property(x => x.DisplayName).HasMaxLength(IdentityResourceConsts.DisplayNameMaxLength); b.Property(x => x.DisplayName).HasMaxLength(IdentityResourceConsts.DisplayNameMaxLength);
identityResource.Property(x => x.Description).HasMaxLength(IdentityResourceConsts.DescriptionMaxLength); b.Property(x => x.Description).HasMaxLength(IdentityResourceConsts.DescriptionMaxLength);
identityResource.Property(x => x.Properties) b.Property(x => x.Properties)
.HasConversion(new AbpJsonValueConverter<Dictionary<string, string>>()) .HasConversion(new AbpJsonValueConverter<Dictionary<string, string>>())
.Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, string>()); .Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, string>());
identityResource.HasMany(x => x.UserClaims).WithOne().HasForeignKey(x => x.IdentityResourceId).IsRequired(); b.HasMany(x => x.UserClaims).WithOne().HasForeignKey(x => x.IdentityResourceId).IsRequired();
}); });
builder.Entity<IdentityClaim>(claim => builder.Entity<IdentityClaim>(b =>
{ {
claim.ToTable(options.TablePrefix + "IdentityClaims", options.Schema); b.ToTable(options.TablePrefix + "IdentityClaims", options.Schema);
b.ConfigureByConvention();
claim.HasKey(x => new { x.IdentityResourceId, x.Type }); b.HasKey(x => new { x.IdentityResourceId, x.Type });
claim.Property(x => x.Type).HasMaxLength(UserClaimConsts.TypeMaxLength).IsRequired(); b.Property(x => x.Type).HasMaxLength(UserClaimConsts.TypeMaxLength).IsRequired();
}); });
builder.Entity<ApiResource>(apiResource => builder.Entity<ApiResource>(b =>
{ {
apiResource.ToTable(options.TablePrefix + "ApiResources", options.Schema); b.ToTable(options.TablePrefix + "ApiResources", options.Schema);
apiResource.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
apiResource.Property(x => x.Name).HasMaxLength(ApiResourceConsts.NameMaxLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(ApiResourceConsts.NameMaxLength).IsRequired();
apiResource.Property(x => x.DisplayName).HasMaxLength(ApiResourceConsts.DisplayNameMaxLength); b.Property(x => x.DisplayName).HasMaxLength(ApiResourceConsts.DisplayNameMaxLength);
apiResource.Property(x => x.Description).HasMaxLength(ApiResourceConsts.DescriptionMaxLength); b.Property(x => x.Description).HasMaxLength(ApiResourceConsts.DescriptionMaxLength);
apiResource.Property(x => x.Properties) b.Property(x => x.Properties)
.HasConversion(new AbpJsonValueConverter<Dictionary<string, string>>()) .HasConversion(new AbpJsonValueConverter<Dictionary<string, string>>())
.Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, string>()); .Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, string>());
apiResource.HasMany(x => x.Secrets).WithOne().HasForeignKey(x => x.ApiResourceId).IsRequired(); b.HasMany(x => x.Secrets).WithOne().HasForeignKey(x => x.ApiResourceId).IsRequired();
apiResource.HasMany(x => x.Scopes).WithOne().HasForeignKey(x => x.ApiResourceId).IsRequired(); b.HasMany(x => x.Scopes).WithOne().HasForeignKey(x => x.ApiResourceId).IsRequired();
apiResource.HasMany(x => x.UserClaims).WithOne().HasForeignKey(x => x.ApiResourceId).IsRequired(); b.HasMany(x => x.UserClaims).WithOne().HasForeignKey(x => x.ApiResourceId).IsRequired();
}); });
builder.Entity<ApiSecret>(apiSecret => builder.Entity<ApiSecret>(b =>
{ {
apiSecret.ToTable(options.TablePrefix + "ApiSecrets", options.Schema); b.ToTable(options.TablePrefix + "ApiSecrets", options.Schema);
apiSecret.HasKey(x => new { x.ApiResourceId, x.Type, x.Value }); b.ConfigureByConvention();
b.HasKey(x => new { x.ApiResourceId, x.Type, x.Value });
apiSecret.Property(x => x.Type).HasMaxLength(SecretConsts.TypeMaxLength).IsRequired(); b.Property(x => x.Type).HasMaxLength(SecretConsts.TypeMaxLength).IsRequired();
apiSecret.Property(x => x.Description).HasMaxLength(SecretConsts.DescriptionMaxLength); b.Property(x => x.Description).HasMaxLength(SecretConsts.DescriptionMaxLength);
if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql) if (options.DatabaseProvider == EfCoreDatabaseProvider.MySql)
{ {
apiSecret.Property(x => x.Value).HasMaxLength(300).IsRequired(); b.Property(x => x.Value).HasMaxLength(300).IsRequired();
} }
else else
{ {
apiSecret.Property(x => x.Value).HasMaxLength(SecretConsts.ValueMaxLength).IsRequired(); b.Property(x => x.Value).HasMaxLength(SecretConsts.ValueMaxLength).IsRequired();
} }
}); });
builder.Entity<ApiResourceClaim>(apiClaim => builder.Entity<ApiResourceClaim>(b =>
{ {
apiClaim.ToTable(options.TablePrefix + "ApiClaims", options.Schema); b.ToTable(options.TablePrefix + "ApiClaims", options.Schema);
b.ConfigureByConvention();
apiClaim.HasKey(x => new { x.ApiResourceId, x.Type }); b.HasKey(x => new { x.ApiResourceId, x.Type });
apiClaim.Property(x => x.Type).HasMaxLength(UserClaimConsts.TypeMaxLength).IsRequired(); b.Property(x => x.Type).HasMaxLength(UserClaimConsts.TypeMaxLength).IsRequired();
}); });
builder.Entity<ApiScope>(apiScope => builder.Entity<ApiScope>(b =>
{ {
apiScope.ToTable(options.TablePrefix + "ApiScopes", options.Schema); b.ToTable(options.TablePrefix + "ApiScopes", options.Schema);
apiScope.HasKey(x => new { x.ApiResourceId, x.Name }); b.ConfigureByConvention();
b.HasKey(x => new { x.ApiResourceId, x.Name });
apiScope.Property(x => x.Name).HasMaxLength(ApiScopeConsts.NameMaxLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(ApiScopeConsts.NameMaxLength).IsRequired();
apiScope.Property(x => x.DisplayName).HasMaxLength(ApiScopeConsts.DisplayNameMaxLength); b.Property(x => x.DisplayName).HasMaxLength(ApiScopeConsts.DisplayNameMaxLength);
apiScope.Property(x => x.Description).HasMaxLength(ApiScopeConsts.DescriptionMaxLength); b.Property(x => x.Description).HasMaxLength(ApiScopeConsts.DescriptionMaxLength);
apiScope.HasMany(x => x.UserClaims).WithOne().HasForeignKey(x => new { x.ApiResourceId, x.Name }).IsRequired(); b.HasMany(x => x.UserClaims).WithOne().HasForeignKey(x => new { x.ApiResourceId, x.Name }).IsRequired();
}); });
builder.Entity<ApiScopeClaim>(apiScopeClaim => builder.Entity<ApiScopeClaim>(b =>
{ {
apiScopeClaim.ToTable(options.TablePrefix + "ApiScopeClaims", options.Schema); b.ToTable(options.TablePrefix + "ApiScopeClaims", options.Schema);
b.ConfigureByConvention();
apiScopeClaim.HasKey(x => new { x.ApiResourceId, x.Name, x.Type }); b.HasKey(x => new { x.ApiResourceId, x.Name, x.Type });
apiScopeClaim.Property(x => x.Type).HasMaxLength(UserClaimConsts.TypeMaxLength).IsRequired(); b.Property(x => x.Type).HasMaxLength(UserClaimConsts.TypeMaxLength).IsRequired();
apiScopeClaim.Property(x => x.Name).HasMaxLength(ApiScopeConsts.NameMaxLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(ApiScopeConsts.NameMaxLength).IsRequired();
}); });
builder.Entity<DeviceFlowCodes>(b => builder.Entity<DeviceFlowCodes>(b =>

3
modules/permission-management/src/Volo.Abp.PermissionManagement.EntityFrameworkCore/Volo/Abp/PermissionManagement/EntityFrameworkCore/AbpPermissionManagementDbContextModelBuilderExtensions.cs

@ -1,6 +1,7 @@
using System; using System;
using JetBrains.Annotations; using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
namespace Volo.Abp.PermissionManagement.EntityFrameworkCore namespace Volo.Abp.PermissionManagement.EntityFrameworkCore
{ {
@ -23,6 +24,8 @@ namespace Volo.Abp.PermissionManagement.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "PermissionGrants", options.Schema); b.ToTable(options.TablePrefix + "PermissionGrants", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.Name).HasMaxLength(PermissionGrantConsts.MaxNameLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(PermissionGrantConsts.MaxNameLength).IsRequired();
b.Property(x => x.ProviderName).HasMaxLength(PermissionGrantConsts.MaxProviderNameLength).IsRequired(); b.Property(x => x.ProviderName).HasMaxLength(PermissionGrantConsts.MaxProviderNameLength).IsRequired();
b.Property(x => x.ProviderKey).HasMaxLength(PermissionGrantConsts.MaxProviderKeyLength).IsRequired(); b.Property(x => x.ProviderKey).HasMaxLength(PermissionGrantConsts.MaxProviderKeyLength).IsRequired();

2
modules/setting-management/src/Volo.Abp.SettingManagement.EntityFrameworkCore/Volo/Abp/SettingManagement/EntityFrameworkCore/SettingManagementDbContextModelBuilderExtensions.cs

@ -38,6 +38,8 @@ namespace Volo.Abp.SettingManagement.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Settings", options.Schema); b.ToTable(options.TablePrefix + "Settings", options.Schema);
b.ConfigureByConvention();
b.Property(x => x.Name).HasMaxLength(SettingConsts.MaxNameLength).IsRequired(); b.Property(x => x.Name).HasMaxLength(SettingConsts.MaxNameLength).IsRequired();
b.Property(x => x.Value).HasMaxLength(SettingConsts.MaxValueLength).IsRequired(); b.Property(x => x.Value).HasMaxLength(SettingConsts.MaxValueLength).IsRequired();
b.Property(x => x.ProviderName).HasMaxLength(SettingConsts.MaxProviderNameLength); b.Property(x => x.ProviderName).HasMaxLength(SettingConsts.MaxProviderNameLength);

4
modules/tenant-management/src/Volo.Abp.TenantManagement.EntityFrameworkCore/Volo/Abp/TenantManagement/EntityFrameworkCore/AbpTenantManagementDbContextModelCreatingExtensions.cs

@ -24,7 +24,7 @@ namespace Volo.Abp.TenantManagement.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "Tenants", options.Schema); b.ToTable(options.TablePrefix + "Tenants", options.Schema);
b.ConfigureFullAuditedAggregateRoot(); b.ConfigureByConvention();
b.Property(t => t.Name).IsRequired().HasMaxLength(TenantConsts.MaxNameLength); b.Property(t => t.Name).IsRequired().HasMaxLength(TenantConsts.MaxNameLength);
@ -37,6 +37,8 @@ namespace Volo.Abp.TenantManagement.EntityFrameworkCore
{ {
b.ToTable(options.TablePrefix + "TenantConnectionStrings", options.Schema); b.ToTable(options.TablePrefix + "TenantConnectionStrings", options.Schema);
b.ConfigureByConvention();
b.HasKey(x => new { x.TenantId, x.Name }); b.HasKey(x => new { x.TenantId, x.Name });
b.Property(cs => cs.Name).IsRequired().HasMaxLength(TenantConnectionStringConsts.MaxNameLength); b.Property(cs => cs.Name).IsRequired().HasMaxLength(TenantConnectionStringConsts.MaxNameLength);

3
npm/ng-packs/.gitignore

@ -45,4 +45,5 @@ testem.log
.DS_Store .DS_Store
Thumbs.db Thumbs.db
!**/[Pp]ackages/* !**/[Pp]ackages/*
*.internal.*

11
npm/ng-packs/angular.json

@ -485,6 +485,14 @@
"maximumError": "10kb" "maximumError": "10kb"
} }
] ]
},
"internal": {
"fileReplacements": [
{
"replace": "apps/dev-app/src/environments/environment.ts",
"with": "apps/dev-app/src/environments/environment.internal.ts"
}
]
} }
} }
}, },
@ -496,6 +504,9 @@
"configurations": { "configurations": {
"production": { "production": {
"browserTarget": "dev-app:build:production" "browserTarget": "dev-app:build:production"
},
"internal": {
"browserTarget": "dev-app:build:internal"
} }
} }
}, },

4
npm/ng-packs/package.json

@ -6,9 +6,9 @@
}, },
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
"abpng": "abpng",
"symlink": "symlink", "symlink": "symlink",
"start": "ng serve dev-app", "start": "ng serve dev-app",
"start:internal": "ng serve dev-app --configuration=internal",
"test": "ng test --watchAll --runInBand", "test": "ng test --watchAll --runInBand",
"commit": "git-cz", "commit": "git-cz",
"lint": "ng lint", "lint": "ng lint",
@ -81,7 +81,7 @@
"protractor": "~5.4.0", "protractor": "~5.4.0",
"rxjs": "~6.4.0", "rxjs": "~6.4.0",
"snq": "^1.0.3", "snq": "^1.0.3",
"symlink-manager": "^1.4.2", "symlink-manager": "^1.4.3",
"ts-node": "~7.0.0", "ts-node": "~7.0.0",
"ts-toolbelt": "^6.3.6", "ts-toolbelt": "^6.3.6",
"tsickle": "^0.37.0", "tsickle": "^0.37.0",

9
npm/ng-packs/packages/account/src/lib/services/account.service.ts

@ -7,6 +7,8 @@ import { RegisterResponse, RegisterRequest, TenantIdResponse } from '../models';
providedIn: 'root', providedIn: 'root',
}) })
export class AccountService { export class AccountService {
apiName = 'AbpAccount';
constructor(private rest: RestService) {} constructor(private rest: RestService) {}
findTenant(tenantName: string): Observable<TenantIdResponse> { findTenant(tenantName: string): Observable<TenantIdResponse> {
@ -15,7 +17,7 @@ export class AccountService {
url: `/api/abp/multi-tenancy/tenants/by-name/${tenantName}`, url: `/api/abp/multi-tenancy/tenants/by-name/${tenantName}`,
}; };
return this.rest.request<null, TenantIdResponse>(request); return this.rest.request<null, TenantIdResponse>(request, { apiName: this.apiName });
} }
register(body: RegisterRequest): Observable<RegisterResponse> { register(body: RegisterRequest): Observable<RegisterResponse> {
@ -25,6 +27,9 @@ export class AccountService {
body, body,
}; };
return this.rest.request<RegisterRequest, RegisterResponse>(request, { skipHandleError: true }); return this.rest.request<RegisterRequest, RegisterResponse>(request, {
skipHandleError: true,
apiName: this.apiName,
});
} }
} }

12
npm/ng-packs/packages/core/src/lib/services/application-configuration.service.ts

@ -3,12 +3,18 @@ import { Observable } from 'rxjs';
import { Rest } from '../models/rest'; import { Rest } from '../models/rest';
import { ApplicationConfiguration } from '../models/application-configuration'; import { ApplicationConfiguration } from '../models/application-configuration';
import { RestService } from './rest.service'; import { RestService } from './rest.service';
import { Store } from '@ngxs/store';
import { ConfigState } from '../states/config.state';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class ApplicationConfigurationService { export class ApplicationConfigurationService {
constructor(private rest: RestService) {} get apiName(): string {
return this.store.selectSnapshot(ConfigState.getDeep('environment.application.name'));
}
constructor(private rest: RestService, private store: Store) {}
getConfiguration(): Observable<ApplicationConfiguration.Response> { getConfiguration(): Observable<ApplicationConfiguration.Response> {
const request: Rest.Request<null> = { const request: Rest.Request<null> = {
@ -16,6 +22,8 @@ export class ApplicationConfigurationService {
url: '/api/abp/application-configuration', url: '/api/abp/application-configuration',
}; };
return this.rest.request<null, ApplicationConfiguration.Response>(request); return this.rest.request<null, ApplicationConfiguration.Response>(request, {
apiName: this.apiName,
});
} }
} }

3
npm/ng-packs/packages/core/src/lib/services/index.ts

@ -3,7 +3,8 @@ export * from './auth.service';
export * from './config-state.service'; export * from './config-state.service';
export * from './lazy-load.service'; export * from './lazy-load.service';
export * from './localization.service'; export * from './localization.service';
export * from './profile-state.service';
export * from './profile.service'; export * from './profile.service';
export * from './rest.service'; export * from './rest.service';
export * from './profile-state.service';
export * from './session-state.service'; export * from './session-state.service';
export * from './track-by.service';

18
npm/ng-packs/packages/core/src/lib/services/profile.service.ts

@ -7,6 +7,8 @@ import { Profile, Rest } from '../models';
providedIn: 'root', providedIn: 'root',
}) })
export class ProfileService { export class ProfileService {
apiName = 'AbpIdentity';
constructor(private rest: RestService) {} constructor(private rest: RestService) {}
get(): Observable<Profile.Response> { get(): Observable<Profile.Response> {
@ -15,7 +17,7 @@ export class ProfileService {
url: '/api/identity/my-profile', url: '/api/identity/my-profile',
}; };
return this.rest.request<null, Profile.Response>(request); return this.rest.request<null, Profile.Response>(request, { apiName: this.apiName });
} }
update(body: Profile.Response): Observable<Profile.Response> { update(body: Profile.Response): Observable<Profile.Response> {
@ -25,16 +27,24 @@ export class ProfileService {
body, body,
}; };
return this.rest.request<Profile.Response, Profile.Response>(request); return this.rest.request<Profile.Response, Profile.Response>(request, {
apiName: this.apiName,
});
} }
changePassword(body: Profile.ChangePasswordRequest, skipHandleError: boolean = false): Observable<null> { changePassword(
body: Profile.ChangePasswordRequest,
skipHandleError: boolean = false,
): Observable<null> {
const request: Rest.Request<Profile.ChangePasswordRequest> = { const request: Rest.Request<Profile.ChangePasswordRequest> = {
method: 'POST', method: 'POST',
url: '/api/identity/my-profile/change-password', url: '/api/identity/my-profile/change-password',
body, body,
}; };
return this.rest.request<Profile.ChangePasswordRequest, null>(request, { skipHandleError }); return this.rest.request<Profile.ChangePasswordRequest, null>(request, {
skipHandleError,
apiName: this.apiName,
});
} }
} }

4
npm/ng-packs/packages/core/src/lib/states/config.state.ts

@ -81,7 +81,7 @@ export class ConfigState {
static getApiUrl(key?: string) { static getApiUrl(key?: string) {
const selector = createSelector([ConfigState], (state: Config.State): string => { const selector = createSelector([ConfigState], (state: Config.State): string => {
return state.environment.apis[key || 'default'].url; return (state.environment.apis[key || 'default'] || state.environment.apis.default).url;
}); });
return selector; return selector;
@ -301,7 +301,7 @@ export class ConfigState {
} }
@Action(SetEnvironment) @Action(SetEnvironment)
setEnvironment({ patchState }: StateContext<Config.State>, environment: Config.Environment) { setEnvironment({ patchState }: StateContext<Config.State>, { environment }: SetEnvironment) {
return patchState({ return patchState({
environment, environment,
}); });

1532
npm/ng-packs/packages/core/src/lib/tests/linked-list.spec.ts

File diff suppressed because it is too large

1
npm/ng-packs/packages/core/src/lib/utils/index.ts

@ -1,5 +1,6 @@
export * from './common-utils'; export * from './common-utils';
export * from './generator-utils'; export * from './generator-utils';
export * from './initial-utils'; export * from './initial-utils';
export * from './linked-list';
export * from './route-utils'; export * from './route-utils';
export * from './rxjs-utils'; export * from './rxjs-utils';

396
npm/ng-packs/packages/core/src/lib/utils/linked-list.ts

@ -0,0 +1,396 @@
/* tslint:disable:no-non-null-assertion */
import compare from 'just-compare';
export class ListNode<T = any> {
readonly value: T;
next: ListNode | undefined;
previous: ListNode | undefined;
constructor(value: T) {
this.value = value;
}
}
export class LinkedList<T = any> {
private first: ListNode<T> | undefined;
private last: ListNode<T> | undefined;
private size = 0;
get head(): ListNode<T> | undefined {
return this.first;
}
get tail(): ListNode<T> | undefined {
return this.last;
}
get length(): number {
return this.size;
}
private attach(
value: T,
previousNode: ListNode<T> | undefined,
nextNode: ListNode<T> | undefined,
): ListNode<T> {
if (!previousNode) return this.addHead(value);
if (!nextNode) return this.addTail(value);
const node = new ListNode(value);
node.previous = previousNode;
previousNode.next = node;
node.next = nextNode;
nextNode.previous = node;
this.size++;
return node;
}
private attachMany(
values: T[],
previousNode: ListNode<T> | undefined,
nextNode: ListNode<T> | undefined,
): ListNode<T>[] {
if (!values.length) return [];
if (!previousNode) return this.addManyHead(values);
if (!nextNode) return this.addManyTail(values);
const list = new LinkedList<T>();
list.addManyTail(values);
list.first!.previous = previousNode;
previousNode.next = list.first;
list.last!.next = nextNode;
nextNode.previous = list.last;
this.size += values.length;
return list.toNodeArray();
}
private detach(node: ListNode<T>) {
if (!node.previous) return this.dropHead();
if (!node.next) return this.dropTail();
node.previous.next = node.next;
node.next.previous = node.previous;
this.size--;
return node;
}
add(value: T) {
return {
after: (previousValue: T, compareFn: ListComparisonFn<T> = compare) =>
this.addAfter(value, previousValue, compareFn),
before: (nextValue: T, compareFn: ListComparisonFn<T> = compare) =>
this.addBefore(value, nextValue, compareFn),
byIndex: (position: number) => this.addByIndex(value, position),
head: () => this.addHead(value),
tail: () => this.addTail(value),
};
}
addMany(values: T[]) {
return {
after: (previousValue: T, compareFn: ListComparisonFn<T> = compare) =>
this.addManyAfter(values, previousValue, compareFn),
before: (nextValue: T, compareFn: ListComparisonFn<T> = compare) =>
this.addManyBefore(values, nextValue, compareFn),
byIndex: (position: number) => this.addManyByIndex(values, position),
head: () => this.addManyHead(values),
tail: () => this.addManyTail(values),
};
}
addAfter(value: T, previousValue: T, compareFn: ListComparisonFn<T> = compare): ListNode<T> {
const previous = this.find(node => compareFn(node.value, previousValue));
return previous ? this.attach(value, previous, previous.next) : this.addTail(value);
}
addBefore(value: T, nextValue: T, compareFn: ListComparisonFn<T> = compare): ListNode<T> {
const next = this.find(node => compareFn(node.value, nextValue));
return next ? this.attach(value, next.previous, next) : this.addHead(value);
}
addByIndex(value: T, position: number): ListNode<T> {
if (position < 0) position += this.size;
else if (position >= this.size) return this.addTail(value);
if (position <= 0) return this.addHead(value);
const next = this.get(position)!;
return this.attach(value, next.previous, next);
}
addHead(value: T): ListNode<T> {
const node = new ListNode(value);
node.next = this.first;
if (this.first) this.first.previous = node;
else this.last = node;
this.first = node;
this.size++;
return node;
}
addTail(value: T): ListNode<T> {
const node = new ListNode(value);
if (this.first) {
node.previous = this.last;
this.last!.next = node;
this.last = node;
} else {
this.first = node;
this.last = node;
}
this.size++;
return node;
}
addManyAfter(
values: T[],
previousValue: T,
compareFn: ListComparisonFn<T> = compare,
): ListNode<T>[] {
const previous = this.find(node => compareFn(node.value, previousValue));
return previous ? this.attachMany(values, previous, previous.next) : this.addManyTail(values);
}
addManyBefore(
values: T[],
nextValue: T,
compareFn: ListComparisonFn<T> = compare,
): ListNode<T>[] {
const next = this.find(node => compareFn(node.value, nextValue));
return next ? this.attachMany(values, next.previous, next) : this.addManyHead(values);
}
addManyByIndex(values: T[], position: number): ListNode<T>[] {
if (position < 0) position += this.size;
if (position <= 0) return this.addManyHead(values);
if (position >= this.size) return this.addManyTail(values);
const next = this.get(position)!;
return this.attachMany(values, next.previous, next);
}
addManyHead(values: T[]): ListNode<T>[] {
return values.reduceRight<ListNode<T>[]>((nodes, value) => {
nodes.unshift(this.addHead(value));
return nodes;
}, []);
}
addManyTail(values: T[]): ListNode<T>[] {
return values.map(value => this.addTail(value));
}
drop() {
return {
byIndex: (position: number) => this.dropByIndex(position),
byValue: (value: T, compareFn: ListComparisonFn<T> = compare) =>
this.dropByValue(value, compareFn),
byValueAll: (value: T, compareFn: ListComparisonFn<T> = compare) =>
this.dropByValueAll(value, compareFn),
head: () => this.dropHead(),
tail: () => this.dropTail(),
};
}
dropMany(count: number) {
return {
byIndex: (position: number) => this.dropManyByIndex(count, position),
head: () => this.dropManyHead(count),
tail: () => this.dropManyTail(count),
};
}
dropByIndex(position: number): ListNode<T> | undefined {
if (position < 0) position += this.size;
const current = this.get(position);
return current ? this.detach(current) : undefined;
}
dropByValue(value: T, compareFn: ListComparisonFn<T> = compare): ListNode<T> | undefined {
const position = this.findIndex(node => compareFn(node.value, value));
return position < 0 ? undefined : this.dropByIndex(position);
}
dropByValueAll(value: T, compareFn: ListComparisonFn<T> = compare): ListNode<T>[] {
const dropped: ListNode<T>[] = [];
for (let current = this.first, position = 0; current; position++, current = current.next) {
if (compareFn(current.value, value)) {
dropped.push(this.dropByIndex(position - dropped.length)!);
}
}
return dropped;
}
dropHead(): ListNode<T> | undefined {
const head = this.first;
if (head) {
this.first = head.next;
if (this.first) this.first.previous = undefined;
else this.last = undefined;
this.size--;
return head;
}
return undefined;
}
dropTail(): ListNode<T> | undefined {
const tail = this.last;
if (tail) {
this.last = tail.previous;
if (this.last) this.last.next = undefined;
else this.first = undefined;
this.size--;
return tail;
}
return undefined;
}
dropManyByIndex(count: number, position: number): ListNode<T>[] {
if (count <= 0) return [];
if (position < 0) position = Math.max(position + this.size, 0);
else if (position >= this.size) return [];
count = Math.min(count, this.size - position);
const dropped: ListNode<T>[] = [];
while (count--) {
const current = this.get(position);
dropped.push(this.detach(current!)!);
}
return dropped;
}
dropManyHead(count: Exclude<number, 0>): ListNode<T>[] {
if (count <= 0) return [];
count = Math.min(count, this.size);
const dropped: ListNode<T>[] = [];
while (count--) dropped.unshift(this.dropHead()!);
return dropped;
}
dropManyTail(count: Exclude<number, 0>): ListNode<T>[] {
if (count <= 0) return [];
count = Math.min(count, this.size);
const dropped: ListNode<T>[] = [];
while (count--) dropped.push(this.dropTail()!);
return dropped;
}
find(predicate: ListIteratorFn<T>): ListNode<T> | undefined {
for (let current = this.first, position = 0; current; position++, current = current.next) {
if (predicate(current, position, this)) return current;
}
return undefined;
}
findIndex(predicate: ListIteratorFn<T>): number {
for (let current = this.first, position = 0; current; position++, current = current.next) {
if (predicate(current, position, this)) return position;
}
return -1;
}
forEach<R = boolean>(callback: ListIteratorFn<T, R>) {
for (let node = this.first, position = 0; node; position++, node = node.next) {
callback(node, position, this);
}
}
get(position: number): ListNode<T> | undefined {
return this.find((_, index) => position === index);
}
indexOf(value: T, compareFn: ListComparisonFn<T> = compare): number {
return this.findIndex(node => compareFn(node.value, value));
}
toArray(): T[] {
const array = new Array(this.size);
this.forEach((node, index) => (array[index!] = node.value));
return array;
}
toNodeArray(): ListNode<T>[] {
const array = new Array(this.size);
this.forEach((node, index) => (array[index!] = node));
return array;
}
toString(mapperFn: ListMapperFn<T> = JSON.stringify): string {
return this.toArray()
.map(value => mapperFn(value))
.join(' <-> ');
}
*[Symbol.iterator]() {
for (let node = this.first, position = 0; node; position++, node = node.next) {
yield node.value;
}
}
}
export type ListMapperFn<T = any> = (value: T) => any;
export type ListComparisonFn<T = any> = (value1: T, value2: T) => boolean;
export type ListIteratorFn<T = any, R = boolean> = (
node: ListNode<T>,
index?: number,
list?: LinkedList,
) => R;

8
npm/ng-packs/packages/feature-management/src/lib/services/feature-management.service.ts

@ -8,6 +8,8 @@ import { FeatureManagement } from '../models';
providedIn: 'root', providedIn: 'root',
}) })
export class FeatureManagementService { export class FeatureManagementService {
apiName = 'FeatureManagement';
constructor(private rest: RestService, private store: Store) {} constructor(private rest: RestService, private store: Store) {}
getFeatures(params: FeatureManagement.Provider): Observable<FeatureManagement.Features> { getFeatures(params: FeatureManagement.Provider): Observable<FeatureManagement.Features> {
@ -16,7 +18,9 @@ export class FeatureManagementService {
url: '/api/abp/features', url: '/api/abp/features',
params, params,
}; };
return this.rest.request<FeatureManagement.Provider, FeatureManagement.Features>(request); return this.rest.request<FeatureManagement.Provider, FeatureManagement.Features>(request, {
apiName: this.apiName,
});
} }
updateFeatures({ updateFeatures({
@ -30,6 +34,6 @@ export class FeatureManagementService {
body: { features }, body: { features },
params: { providerKey, providerName }, params: { providerKey, providerName },
}; };
return this.rest.request<FeatureManagement.Features, null>(request); return this.rest.request<FeatureManagement.Features, null>(request, { apiName: this.apiName });
} }
} }

34
npm/ng-packs/packages/identity/src/lib/services/identity.service.ts

@ -7,6 +7,8 @@ import { Identity } from '../models/identity';
providedIn: 'root', providedIn: 'root',
}) })
export class IdentityService { export class IdentityService {
apiName = 'AbpIdentity';
constructor(private rest: RestService) {} constructor(private rest: RestService) {}
getRoles(params = {} as ABP.PageQueryParams): Observable<Identity.RoleResponse> { getRoles(params = {} as ABP.PageQueryParams): Observable<Identity.RoleResponse> {
@ -16,7 +18,7 @@ export class IdentityService {
params, params,
}; };
return this.rest.request<null, Identity.RoleResponse>(request); return this.rest.request<null, Identity.RoleResponse>(request, { apiName: this.apiName });
} }
getAllRoles(): Observable<Identity.RoleResponse> { getAllRoles(): Observable<Identity.RoleResponse> {
@ -25,7 +27,7 @@ export class IdentityService {
url: '/api/identity/roles/all', url: '/api/identity/roles/all',
}; };
return this.rest.request<null, Identity.RoleResponse>(request); return this.rest.request<null, Identity.RoleResponse>(request, { apiName: this.apiName });
} }
getRoleById(id: string): Observable<Identity.RoleItem> { getRoleById(id: string): Observable<Identity.RoleItem> {
@ -34,7 +36,7 @@ export class IdentityService {
url: `/api/identity/roles/${id}`, url: `/api/identity/roles/${id}`,
}; };
return this.rest.request<null, Identity.RoleItem>(request); return this.rest.request<null, Identity.RoleItem>(request, { apiName: this.apiName });
} }
deleteRole(id: string): Observable<Identity.RoleItem> { deleteRole(id: string): Observable<Identity.RoleItem> {
@ -43,7 +45,7 @@ export class IdentityService {
url: `/api/identity/roles/${id}`, url: `/api/identity/roles/${id}`,
}; };
return this.rest.request<null, Identity.RoleItem>(request); return this.rest.request<null, Identity.RoleItem>(request, { apiName: this.apiName });
} }
createRole(body: Identity.RoleSaveRequest): Observable<Identity.RoleItem> { createRole(body: Identity.RoleSaveRequest): Observable<Identity.RoleItem> {
@ -53,7 +55,9 @@ export class IdentityService {
body, body,
}; };
return this.rest.request<Identity.RoleSaveRequest, Identity.RoleItem>(request); return this.rest.request<Identity.RoleSaveRequest, Identity.RoleItem>(request, {
apiName: this.apiName,
});
} }
updateRole(body: Identity.RoleItem): Observable<Identity.RoleItem> { updateRole(body: Identity.RoleItem): Observable<Identity.RoleItem> {
@ -66,7 +70,9 @@ export class IdentityService {
body, body,
}; };
return this.rest.request<Identity.RoleItem, Identity.RoleItem>(request); return this.rest.request<Identity.RoleItem, Identity.RoleItem>(request, {
apiName: this.apiName,
});
} }
getUsers(params = {} as ABP.PageQueryParams): Observable<Identity.UserResponse> { getUsers(params = {} as ABP.PageQueryParams): Observable<Identity.UserResponse> {
@ -76,7 +82,7 @@ export class IdentityService {
params, params,
}; };
return this.rest.request<null, Identity.UserResponse>(request); return this.rest.request<null, Identity.UserResponse>(request, { apiName: this.apiName });
} }
getUserById(id: string): Observable<Identity.UserItem> { getUserById(id: string): Observable<Identity.UserItem> {
@ -85,7 +91,7 @@ export class IdentityService {
url: `/api/identity/users/${id}`, url: `/api/identity/users/${id}`,
}; };
return this.rest.request<null, Identity.UserItem>(request); return this.rest.request<null, Identity.UserItem>(request, { apiName: this.apiName });
} }
getUserRoles(id: string): Observable<Identity.RoleResponse> { getUserRoles(id: string): Observable<Identity.RoleResponse> {
@ -94,7 +100,7 @@ export class IdentityService {
url: `/api/identity/users/${id}/roles`, url: `/api/identity/users/${id}/roles`,
}; };
return this.rest.request<null, Identity.RoleResponse>(request); return this.rest.request<null, Identity.RoleResponse>(request, { apiName: this.apiName });
} }
deleteUser(id: string): Observable<null> { deleteUser(id: string): Observable<null> {
@ -103,7 +109,7 @@ export class IdentityService {
url: `/api/identity/users/${id}`, url: `/api/identity/users/${id}`,
}; };
return this.rest.request<null, null>(request); return this.rest.request<null, null>(request, { apiName: this.apiName });
} }
createUser(body: Identity.UserSaveRequest): Observable<Identity.UserItem> { createUser(body: Identity.UserSaveRequest): Observable<Identity.UserItem> {
@ -113,7 +119,9 @@ export class IdentityService {
body, body,
}; };
return this.rest.request<Identity.UserSaveRequest, Identity.UserItem>(request); return this.rest.request<Identity.UserSaveRequest, Identity.UserItem>(request, {
apiName: this.apiName,
});
} }
updateUser(body: Identity.UserItem): Observable<Identity.UserItem> { updateUser(body: Identity.UserItem): Observable<Identity.UserItem> {
@ -126,6 +134,8 @@ export class IdentityService {
body, body,
}; };
return this.rest.request<Identity.UserItem, Identity.UserItem>(request); return this.rest.request<Identity.UserItem, Identity.UserItem>(request, {
apiName: this.apiName,
});
} }
} }

15
npm/ng-packs/packages/permission-management/src/lib/services/permission-management.service.ts

@ -7,16 +7,23 @@ import { PermissionManagement } from '../models/permission-management';
providedIn: 'root', providedIn: 'root',
}) })
export class PermissionManagementService { export class PermissionManagementService {
apiName = 'AbpPermissionManagement';
constructor(private rest: RestService) {} constructor(private rest: RestService) {}
getPermissions(params: PermissionManagement.GrantedProvider): Observable<PermissionManagement.Response> { getPermissions(
params: PermissionManagement.GrantedProvider,
): Observable<PermissionManagement.Response> {
const request: Rest.Request<PermissionManagement.GrantedProvider> = { const request: Rest.Request<PermissionManagement.GrantedProvider> = {
method: 'GET', method: 'GET',
url: '/api/abp/permissions', url: '/api/abp/permissions',
params, params,
}; };
return this.rest.request<PermissionManagement.GrantedProvider, PermissionManagement.Response>(request); return this.rest.request<PermissionManagement.GrantedProvider, PermissionManagement.Response>(
request,
{ apiName: this.apiName },
);
} }
updatePermissions({ updatePermissions({
@ -31,6 +38,8 @@ export class PermissionManagementService {
params: { providerKey, providerName }, params: { providerKey, providerName },
}; };
return this.rest.request<PermissionManagement.UpdateRequest, null>(request); return this.rest.request<PermissionManagement.UpdateRequest, null>(request, {
apiName: this.apiName,
});
} }
} }

28
npm/ng-packs/packages/tenant-management/src/lib/services/tenant-management.service.ts

@ -7,6 +7,8 @@ import { TenantManagement } from '../models/tenant-management';
providedIn: 'root', providedIn: 'root',
}) })
export class TenantManagementService { export class TenantManagementService {
apiName = 'AbpTenantManagement';
constructor(private rest: RestService) {} constructor(private rest: RestService) {}
getTenant(params = {} as ABP.PageQueryParams): Observable<TenantManagement.Response> { getTenant(params = {} as ABP.PageQueryParams): Observable<TenantManagement.Response> {
@ -16,7 +18,7 @@ export class TenantManagementService {
params, params,
}; };
return this.rest.request<null, TenantManagement.Response>(request); return this.rest.request<null, TenantManagement.Response>(request, { apiName: this.apiName });
} }
getTenantById(id: string): Observable<ABP.BasicItem> { getTenantById(id: string): Observable<ABP.BasicItem> {
@ -25,7 +27,7 @@ export class TenantManagementService {
url: `/api/multi-tenancy/tenants/${id}`, url: `/api/multi-tenancy/tenants/${id}`,
}; };
return this.rest.request<null, ABP.BasicItem>(request); return this.rest.request<null, ABP.BasicItem>(request, { apiName: this.apiName });
} }
deleteTenant(id: string): Observable<null> { deleteTenant(id: string): Observable<null> {
@ -34,7 +36,7 @@ export class TenantManagementService {
url: `/api/multi-tenancy/tenants/${id}`, url: `/api/multi-tenancy/tenants/${id}`,
}; };
return this.rest.request<null, null>(request); return this.rest.request<null, null>(request, { apiName: this.apiName });
} }
createTenant(body: TenantManagement.AddRequest): Observable<ABP.BasicItem> { createTenant(body: TenantManagement.AddRequest): Observable<ABP.BasicItem> {
@ -44,7 +46,9 @@ export class TenantManagementService {
body, body,
}; };
return this.rest.request<TenantManagement.AddRequest, ABP.BasicItem>(request); return this.rest.request<TenantManagement.AddRequest, ABP.BasicItem>(request, {
apiName: this.apiName,
});
} }
updateTenant(body: TenantManagement.UpdateRequest): Observable<ABP.BasicItem> { updateTenant(body: TenantManagement.UpdateRequest): Observable<ABP.BasicItem> {
@ -57,7 +61,9 @@ export class TenantManagementService {
body, body,
}; };
return this.rest.request<TenantManagement.UpdateRequest, ABP.BasicItem>(request); return this.rest.request<TenantManagement.UpdateRequest, ABP.BasicItem>(request, {
apiName: this.apiName,
});
} }
getDefaultConnectionString(id: string): Observable<string> { getDefaultConnectionString(id: string): Observable<string> {
@ -68,7 +74,9 @@ export class TenantManagementService {
responseType: Rest.ResponseType.Text, responseType: Rest.ResponseType.Text,
url, url,
}; };
return this.rest.request<TenantManagement.DefaultConnectionStringRequest, string>(request); return this.rest.request<TenantManagement.DefaultConnectionStringRequest, string>(request, {
apiName: this.apiName,
});
} }
updateDefaultConnectionString( updateDefaultConnectionString(
@ -81,7 +89,9 @@ export class TenantManagementService {
url, url,
params: { defaultConnectionString: payload.defaultConnectionString }, params: { defaultConnectionString: payload.defaultConnectionString },
}; };
return this.rest.request<TenantManagement.DefaultConnectionStringRequest, any>(request); return this.rest.request<TenantManagement.DefaultConnectionStringRequest, any>(request, {
apiName: this.apiName,
});
} }
deleteDefaultConnectionString(id: string): Observable<string> { deleteDefaultConnectionString(id: string): Observable<string> {
@ -91,6 +101,8 @@ export class TenantManagementService {
method: 'DELETE', method: 'DELETE',
url, url,
}; };
return this.rest.request<TenantManagement.DefaultConnectionStringRequest, any>(request); return this.rest.request<TenantManagement.DefaultConnectionStringRequest, any>(request, {
apiName: this.apiName,
});
} }
} }

6
npm/ng-packs/scripts/install-new-dependencies.ts

@ -13,11 +13,15 @@ const updateAndInstall = async () => {
`../packages/${project}/package.json`, `../packages/${project}/package.json`,
); );
const isPackageExistOnNPM = !(
execa.sync('npm', ['search', name]).stdout.indexOf('No matches found for') > -1
);
packageJson.devDependencies = { packageJson.devDependencies = {
...packageJson.devDependencies, ...packageJson.devDependencies,
...dependencies, ...dependencies,
...peerDependencies, ...peerDependencies,
...{ [name]: `~${version}` }, ...(isPackageExistOnNPM && { [name]: `~${version}` }),
}; };
packageJson.devDependencies = Object.keys(packageJson.devDependencies) packageJson.devDependencies = Object.keys(packageJson.devDependencies)

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

Loading…
Cancel
Save