Browse Source

Merge branch 'dev' into maliming/Apply-Entity-Extension-System-for-samples

pull/3366/head
maliming 7 years ago
parent
commit
0bb4cdeaf3
  1. 7
      abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json
  2. 11
      docs/en/Customizing-Application-Modules-Extending-Entities.md
  3. 2
      docs/en/Entities.md
  4. 15
      docs/en/Entity-Framework-Core-Migrations.md
  5. 41
      docs/en/Entity-Framework-Core.md
  6. 6
      docs/en/Getting-Started-With-Startup-Templates.md
  7. 3
      docs/en/Object-Extensions.md
  8. 15
      docs/en/Startup-Templates/Application.md
  9. 53
      docs/en/UI/Angular/Component-Replacement.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. 9
      docs/en/docs-nav.json
  17. 7
      docs/zh-Hans/Best-Practices/Entity-Framework-Core-Integration.md
  18. 30
      docs/zh-Hans/Customizing-Application-Modules-Extending-Entities.md
  19. 9
      docs/zh-Hans/Entities.md
  20. 99
      docs/zh-Hans/Entity-Framework-Core-Migrations.md
  21. 107
      docs/zh-Hans/Entity-Framework-Core.md
  22. 468
      docs/zh-Hans/UI/AspNetCore/Customization-User-Interface.md
  23. 4
      docs/zh-Hans/docs-nav.json
  24. 16
      framework/Volo.Abp.sln
  25. 36
      framework/src/Volo.Abp.AutoMapper/AutoMapper/AbpAutoMapperExtensibleDtoExtensions.cs
  26. 1
      framework/src/Volo.Abp.AutoMapper/Volo.Abp.AutoMapper.csproj
  27. 5
      framework/src/Volo.Abp.AutoMapper/Volo/Abp/AutoMapper/AbpAutoMapperModule.cs
  28. 15
      framework/src/Volo.Abp.Core/Volo/Abp/Check.cs
  29. 1
      framework/src/Volo.Abp.Data/Volo.Abp.Data.csproj
  30. 4
      framework/src/Volo.Abp.Data/Volo/Abp/Data/AbpDataModule.cs
  31. 2
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/AuditedEntityWithUserDto.cs
  32. 4
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/CreationAuditedEntityWithUserDto.cs
  33. 35
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleAuditedEntityDto.cs
  34. 40
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleAuditedEntityWithUserDto.cs
  35. 35
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleCreationAuditedEntityDto.cs
  36. 32
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleCreationAuditedEntityWithUserDto.cs
  37. 28
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleEntityDto.cs
  38. 41
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleFullAuditedEntityDto.cs
  39. 46
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleFullAuditedEntityWithUserDto.cs
  40. 6
      framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/FullAuditedEntityWithUserDto.cs
  41. 2
      framework/src/Volo.Abp.EntityFrameworkCore.MySQL/Volo.Abp.EntityFrameworkCore.MySQL.csproj
  42. 35
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs
  43. 14
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/EntityExtensionInfo.cs
  44. 133
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/EntityExtensionManager.cs
  45. 17
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Extensions/PropertyExtensionInfo.cs
  46. 33
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Modeling/AbpEntityTypeBuilderExtensions.cs
  47. 15
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/ValueConverters/ExtraPropertiesValueConverter.cs
  48. 41
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/EfCoreObjectExtensionInfoExtensions.cs
  49. 80
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/EfCoreObjectExtensionManagerExtensions.cs
  50. 50
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/EfCoreObjectExtensionPropertyInfoExtensions.cs
  51. 27
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/ObjectExtensionPropertyInfoEfCoreMappingOptions.cs
  52. 3
      framework/src/Volo.Abp.ObjectExtending/FodyWeavers.xml
  53. 30
      framework/src/Volo.Abp.ObjectExtending/FodyWeavers.xsd
  54. 3
      framework/src/Volo.Abp.ObjectExtending/Properties/AssemblyInfo.cs
  55. 21
      framework/src/Volo.Abp.ObjectExtending/Volo.Abp.ObjectExtending.csproj
  56. 0
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs
  57. 0
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/IHasExtraProperties.cs
  58. 9
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/AbpObjectExtendingModule.cs
  59. 17
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ExtensibleObject.cs
  60. 175
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/HasExtraPropertiesObjectExtendingExtensions.cs
  61. 28
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/MappingPropertyDefinitionChecks.cs
  62. 78
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionInfo.cs
  63. 66
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionManager.cs
  64. 44
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionManagerExtensions.cs
  65. 33
      framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionPropertyInfo.cs
  66. 41
      framework/test/Volo.Abp.AutoMapper.Tests/AutoMapper/AbpAutoMapperExtensibleDtoExtensions_Tests.cs
  67. 2
      framework/test/Volo.Abp.AutoMapper.Tests/Volo.Abp.AutoMapper.Tests.csproj
  68. 9
      framework/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/AutoMapperTestModule.cs
  69. 4
      framework/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyMapProfile.cs
  70. 11
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Domain/TestEntityExtensionConfigurator.cs
  71. 3
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/TestMigrationsDbContext.cs
  72. 3
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs
  73. 16
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo.Abp.ObjectExtending.Tests.csproj
  74. 9
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/AbpObjectExtendingTestBase.cs
  75. 27
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/AbpObjectExtendingTestModule.cs
  76. 73
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/HasExtraPropertiesObjectExtendingExtensions_Tests.cs
  77. 63
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/ObjectExtensionManager_Tests.cs
  78. 7
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/TestObjects/ExtensibleTestPerson.cs
  79. 7
      framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/TestObjects/ExtensibleTestPersonDto.cs
  80. 2
      modules/blogging/src/Volo.Blogging.Application/Volo/Blogging/Posts/PostAppService.cs
  81. 12
      modules/docs/app/VoloDocs.Web/Controllers/HomeController.cs
  82. 18
      modules/docs/app/VoloDocs.Web/Pages/Index.cshtml
  83. 42
      modules/docs/app/VoloDocs.Web/Pages/Index.cshtml.cs
  84. 5
      modules/docs/app/VoloDocs.Web/appsettings.json
  85. 2796
      modules/docs/app/VoloDocs.Web/package-lock.json
  86. 2
      modules/docs/app/VoloDocs.Web/package.json
  87. 12
      modules/docs/src/Volo.Docs.Admin.Application/Volo/Docs/Admin/Documents/DocumentAdminAppService.cs
  88. 128
      modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/DocumentAppService.cs
  89. 7
      modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainConsts.cs
  90. 15
      modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentSource.cs
  91. 29
      modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentSource.cs
  92. 69
      modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubRepositoryManager.cs
  93. 22
      modules/docs/src/Volo.Docs.Domain/Volo/Extensions/NewtonsoftJsonExtensions.cs
  94. 109
      modules/docs/src/Volo.Docs.Web/HtmlConverting/ScribanDocumentSectionRenderer.cs
  95. 31
      modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml
  96. 88
      modules/docs/src/Volo.Docs.Web/Pages/Documents/Search.cshtml
  97. 240
      modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/Styles/vs.css
  98. 2
      modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/Styles/vs.min.css
  99. 349
      modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/Styles/vs.scss
  100. 1
      modules/docs/src/Volo.Docs.Web/Volo.Docs.Web.csproj

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"
} }
} }

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

@ -37,13 +37,14 @@ As mentioned above, all extra properties of an entity are stored as a single JSO
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. 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: Assume that you want to add a `SocialSecurityNumber` to the `IdentityUser` entity of the [Identity Module](Modules/Identity.md). You can use the `ObjectExtensionManager`:
````csharp ````csharp
EntityExtensionManager.AddProperty<IdentityUser, string>( ObjectExtensionManager.Instance
"SocialSecurityNumber", .MapEfCoreProperty<IdentityUser, string>(
b => { b.HasMaxLength(32); } "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 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).

2
docs/en/Entities.md

@ -375,7 +375,7 @@ The way to store this dictionary in the database depends on the database provide
* For [Entity Framework Core](Entity-Framework-Core.md), here are two type of configurations; * 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. * 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`. * If you want, you can use the `ObjectExtensionManager` to define a separate table field for a desired extra property. Properties those are not configured through the `ObjectExtensionManager` 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 `ObjectExtensionManager`.
* 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

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

@ -409,18 +409,19 @@ public static class MyProjectNameEntityExtensions
{ {
OneTimeRunner.Run(() => OneTimeRunner.Run(() =>
{ {
EntityExtensionManager.AddProperty<IdentityRole, string>( ObjectExtensionManager.Instance
"Title", .MapEfCoreProperty<IdentityRole, string>(
b => { b.HasMaxLength(128); } "Title",
); builder => { builder.HasMaxLength(64); }
);
}); });
} }
} }
```` ````
> Instead of hard-coded "Title" string, we suggest to use `nameof(AppRole.Title)`. > Instead of hard-coded "Title" string, we suggest to use `nameof(AppRole.Title)` or use a constant string.
`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. `ObjectExtensionManager` is used to add properties to existing entities. Since `ObjectExtensionManager.Instance` is a static instance (singleton), we should call it once. `OneTimeRunner` is a simple utility class defined by the ABP Framework.
See the [EF Core integration documentation](Entity-Framework-Core.md) for more about the entity extension system. See the [EF Core integration documentation](Entity-Framework-Core.md) for more about the entity extension system.
@ -543,7 +544,7 @@ In this way, you can easily attach any type of value to an entity of a depended
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. 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. All you need to do is to use the `ObjectExtensionManager` 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

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

@ -298,56 +298,57 @@ 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.
## Extra Properties & Entity Extension Manager ## Extra Properties & Object 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. 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. By default, all the extra properties of an entity are stored as a single `JSON` object in the database.
For more information about the extra properties & the entity extension system, see the following documents: Entity extension system allows you to to store desired extra properties in separate fields in the related database table. 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) * [Customizing the Application Modules: Extending Entities](Customizing-Application-Modules-Extending-Entities.md)
* [Entities](Entities.md) * [Entities](Entities.md)
This section only explains the `EntityExtensionManager` and its usage. This section only explains the EF Core related usage of the `ObjectExtensionManager`.
### AddProperty Method ### ObjectExtensionManager.Instance
`AddProperty` method of the `EntityExtensionManager` allows you to define additional properties for an entity type. `ObjectExtensionManager` implements the singleton pattern, so you need to use the static `ObjectExtensionManager.Instance` to perform all the operations.
### MapEfCoreProperty
`MapEfCoreProperty` is a shortcut extension method to define an extension property for an entity and map to the database.
**Example**: Add `Title` property (database field) to the `IdentityRole` entity: **Example**: Add `Title` property (database field) to the `IdentityRole` entity:
````csharp ````csharp
EntityExtensionManager.AddProperty<IdentityRole, string>( ObjectExtensionManager.Instance
"Title", .MapEfCoreProperty<IdentityRole, string>(
b => { b.HasMaxLength(128); } "Title",
); builder => { builder.HasMaxLength(64); }
);
```` ````
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. If the related module has implemented this feature (by using the `ConfigureEfCoreEntity` 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. >`MapEfCoreProperty` 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 ### ConfigureEfCoreEntity
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: If you are building a reusable module and want to allow application developers to add properties to your entities, you can use the `ConfigureEfCoreEntity` extension method in your entity mapping. However, there is a shortcut extension method `ConfigureObjectExtensions` that can be used while configuring the entity mapping:
````csharp ````csharp
builder.Entity<YourEntity>(b => builder.Entity<YourEntity>(b =>
{ {
b.ConfigureExtensions(); b.ConfigureObjectExtensions();
//... //...
}); });
```` ````
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. > If you call `ConfigureByConvention()` extension method (like `b.ConfigureByConvention()` for this example), ABP Framework internally calls the `ConfigureObjectExtensions` 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. 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 ## Advanced Topics
### Set Default Repository Classes ### Set Default Repository Classes

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)

3
docs/en/Object-Extensions.md

@ -0,0 +1,3 @@
# Object Extensions
TODO

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.

53
docs/en/UI/Angular/Component-Replacement.md

@ -1,10 +1,10 @@
# Component Replacement ## Component Replacement
You can replace some ABP components with your custom components. You can replace some ABP components with your custom components.
The reason that you **can replace** but **cannot customize** default ABP components is disabling or changing a part of that component can cause problems. So we named those components as _Replaceable Components_. The reason that you **can replace** but **cannot customize** default ABP components is disabling or changing a part of that component can cause problems. So we named those components as _Replaceable Components_.
## How to Replace a Component ### How to Replace a Component
Create a new component that you want to use instead of an ABP component. Add that component to `declarations` and `entryComponents` in the `AppModule`. Create a new component that you want to use instead of an ABP component. Add that component to `declarations` and `entryComponents` in the `AppModule`.
@ -29,7 +29,54 @@ export class AppComponent {
![Example Usage](./images/component-replacement.gif) ![Example Usage](./images/component-replacement.gif)
## Available Replaceable Components
### How to Replace a Layout
Each ABP theme module has 3 layouts named `ApplicationLayoutComponent`, `AccountLayoutComponent`, `EmptyLayoutComponent`. These layouts can be replaced with the same way.
> A layout component template should contain `<router-outlet></router-outlet>` element.
The below example describes how to replace the `ApplicationLayoutComponent`:
Run the following command to generate a layout in `angular` folder:
```bash
yarn ng generate component shared/my-application-layout --export --entryComponent
# You don't need the --entryComponent option in Angular 9
```
Add the following code in your layout template (`my-layout.component.html`) where you want the page to be loaded.
```html
<router-outlet></router-outlet>
```
Open the `app.component.ts` and add the below content:
```js
import { ..., AddReplaceableComponent } from '@abp/ng.core'; // imported AddReplaceableComponent
import { MyApplicationLayoutComponent } from './shared/my-application-layout/my-application-layout.component'; // imported MyApplicationLayoutComponent
import { Store } from '@ngxs/store'; // imported Store
//...
export class AppComponent {
constructor(..., private store: Store) {} // injected Store
ngOnInit() {
// added below content
this.store.dispatch(
new AddReplaceableComponent({
component: MyApplicationLayoutComponent,
key: 'Theme.ApplicationLayoutComponent',
}),
);
//...
}
}
```
### Available Replaceable Components
| Component key | Description | | Component key | Description |
| -------------------------------------------------- | --------------------------------------------- | | -------------------------------------------------- | --------------------------------------------- |

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#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#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)

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

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)

468
docs/zh-Hans/UI/AspNetCore/Customization-User-Interface.md

@ -1,3 +1,469 @@
# ASP.NET Core (MVC / Razor Pages) 用户界面自定义指南 # ASP.NET Core (MVC / Razor Pages) 用户界面自定义指南
TODO... 本文档解释了如何重写ASP.NET Core MVC / Razor Page 应用程序依赖[应用模块](../../Modules/Index.md)的用户界面.
## 重写页面
本节介绍了[Razor 页面](https://docs.microsoft.com/zh-cn/aspnet/core/razor-pages/)开发,它是ASP.NET Core推荐的服务端渲染用户页面的方法. 预构建的模块通常使用Razor页面替代经典的MVC方式(下一节也介绍MVC模式).
你通过有三种重写页面的需求:
* 仅**重写页面模型**(C#)端执行其他逻辑,不更改UI.
* 仅**重写Razor页面**(.cshtml文件),不更改逻辑.
* **完全重写** 页面.
### 重写页面模型 (C#)
````csharp
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Identity.Web.Pages.Identity.Users;
namespace Acme.BookStore.Web.Pages.Identity.Users
{
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(EditModalModel))]
public class MyEditModalModel : EditModalModel
{
public MyEditModalModel(
IIdentityUserAppService identityUserAppService,
IIdentityRoleAppService identityRoleAppService
) : base(
identityUserAppService,
identityRoleAppService)
{
}
public override async Task<IActionResult> OnPostAsync()
{
//TODO: Additional logic
await base.OnPostAsync();
//TODO: Additional logic
}
}
}
````
* 这个类继承并替换 `EditModalModel` ,重写了 `OnPostAsync` 方法在基类代码的前后执行附加逻辑
* 它使用 `ExposeServices` 和 `Dependency` attributes去替换这个类.
### 重写Razor页面 (.CSHTML)
使用[虚拟文件系统](../../Virtual-File-System.md)可以重写 `.cshtml` 文件(razor page, razor view, view component... 等.)
虚拟文件系统允许我们将**资源嵌入到程序集中**. 通过这个方式,预构建的模块在Nuget包中定义了Razor页面. 当你依赖模块时,可以覆盖这个模块向虚拟文件系统添加的任何文件,包括页面/视图.
#### 示例
这个示例重写了[账户模块](../../Modules/Account.md)定义的**登录页面**UI
物理文件可以覆盖相同位置的嵌入文件. 账户模块在 `Pages/Account` 文件夹下定义了 `Login.cshtml` 文件. 所以你可以在同一路径下创建文件覆盖它:
![overriding-login-cshtml](../../images/overriding-login-cshtml.png)
通常你想要拷贝模块的 `.cshtml` 原文件,然后进行需要的更改. 你可以在[这里](https://github.com/abpframework/abp/blob/dev/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml)找到源文件. 不要拷贝 `Login.cshtml.cs` 文件,它是隐藏razor页面的代码,我们不希望覆盖它(见下节).
这就够了,接下来你可以对文件内容做你想要的更改.
### 完全重写Razo页面
也许你想要完全重写页面,Razor和页面相关的C#文件.
在这种情况下;
1. 像上面描述过的那术重写C#页面模型类,但不需要替换已存在的页面模型类.
2. 像上面描述过的那样重写Razor页面,并且更改@model指向新的页面模型
#### 示例
这个示例重写了[账户模块](../../Modules/Account.md)定义的**登录页面**
创建一个继承自 `LoginModel`(定义在`Volo.Abp.Account.Web.Pages.Account`命名空间下)的页面模型类:
````csharp
public class MyLoginModel : LoginModel
{
public MyLoginModel(
IAuthenticationSchemeProvider schemeProvider,
IOptions<AbpAccountOptions> accountOptions
) : base(
schemeProvider,
accountOptions)
{
}
public override Task<IActionResult> OnPostAsync(string action)
{
//TODO: Add logic
return base.OnPostAsync(action);
}
//TODO: Add new methods and properties...
}
````
如果需要,你可以重写任何方法或添加新的属性/方法
> 注意我们没有使用 `[Dependency(ReplaceServices = true)]` 或 `[ExposeServices(typeof(LoginModel))]`,因为我们不想替换依赖注入中已存在的类,我们定义了一个新的.
拷贝 `Login.cshtml` 到你们解决方案,更改 **@model** 指定到 `MyLoginModel`:
````xml
@page
...
@model Acme.BookStore.Web.Pages.Account.MyLoginModel
...
````
这就够了,接下来你可以做任何想要更改.
#### 不使用继承替换页面模型
你不需要继承源页面模型类(像之前的示例). 你可以完全**重写实现**你自己的页面. 在这种事情下你可以从 `PageModel`,`AbpPageModel` 或任何你需要的合适的基类派生.
## 重写视图组件
在ABP框架,预构建的模块和主题定义了一些**可重用的视图组件**. 这些视图组件可以像页面一样被替换.
### 示例
下面是应用程序启动模板自带的 **基本主题** 的截图.
![bookstore-brand-area-highlighted](../../images/bookstore-brand-area-highlighted.png)
[基本主题](../../Themes/Basic.md) 为layout定义了一些视图组件. 例如上面带有红色矩形的突出显示区域称为 **Brand组件**, 你可能想添加自己的**自己的应用程序logo**来自定义此组件. 让我们来看看如何去做.
首先创建你的logo并且放到你的web应用程序文件夹中,我们使用 `wwwroot/logos/bookstore-logo.png` 路径. 然后在 `Themes/Basic/Components/Brand` 文件夹下复制[Brand组件视图](https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Components/Brand/Default.cshtml). 结果应该是类似下面的图片:
![bookstore-added-brand-files](../../images/bookstore-added-brand-files.png)
然后对 `Default.cshtml` 文件做你想要的更改. 例如内容可以是这样的:
````xml
<a href="/">
<img src="~/logos/bookstore-logo.png" width="250" height="60"/>
</a>
````
现在你可以运行应用程序看到结果:
![bookstore-added-logo](../../images/bookstore-added-logo.png)
如果你需要,你也可以仅使用依赖注入系统替换组件[背后的C#类代码](https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Components/Brand/MainNavbarBrandViewComponent.cs)
### 重写主题
正如上所解释的,你可以更改任何组件,layout或c#类. 参阅[主题文档]了解更多关于主题系统的信息.
## 重写静态资源
重写模块的静态资源(像JavaScript,Css或图片文件)是很简单的. 只需要在解决方案的相同路径创建文件,虚拟文件系统会自动处理它.
## 操作捆绑
[捆绑 & 压缩](Bundling-Minification.md) 系统提供了**动态可扩展的** 系统去创建**script**和**style**捆绑. 它允许你扩展和操作现有的包.
### 示例: 添加全局CSS文件
例如APP框架定义了一个**全局样式捆绑**添加到所有的页面(事实上由主题添加layout). 让我们添加一个**自定义样式文件**到这个捆绑文件的最后,我们可以覆盖任何全局样式.
创建在 `wwwroot` 文件夹下创建一个CSS文件
![bookstore-global-css-file](../../images/bookstore-global-css-file.png)
在CSS文件中定义一些规则. 例如:
````css
.card-title {
color: orange;
font-size: 2em;
text-decoration: underline;
}
.btn-primary {
background-color: red;
}
````
然后在你的[模块](../../Module-Development-Basics.md) `ConfigureServices` 方法添加这个文件到标准的全局样式捆绑包:
````csharp
Configure<AbpBundlingOptions>(options =>
{
options.StyleBundles.Configure(
StandardBundles.Styles.Global, //The bundle name!
bundleConfiguration =>
{
bundleConfiguration.AddFiles("/styles/my-global-styles.css");
}
);
});
````
#### 全局脚本捆绑包
就像 `StandardBundles.Styles.Global` 一样,还有一个 `StandardBundles.Scripts.Global`,你可以添加文件或操作现有文件.
### 示例: 操作捆绑包文件
上面的示例中添加了新文件到捆绑包. 如果你创建 **bundle contributor** 类则可以做到更多. 示例:
````csharp
public class MyGlobalStyleBundleContributor : BundleContributor
{
public override void ConfigureBundle(BundleConfigurationContext context)
{
context.Files.Clear();
context.Files.Add("/styles/my-global-styles.css");
}
}
````
然后你可以添加这个contributor到已存在的捆绑中:
````csharp
Configure<AbpBundlingOptions>(options =>
{
options.StyleBundles.Configure(
StandardBundles.Styles.Global,
bundleConfiguration =>
{
bundleConfiguration.AddContributors(typeof(MyGlobalStyleBundleContributor));
}
);
});
````
示例中清除了所有的CSS文件,在现实中这并不是一个好主意,你可以找到某个特定的文件替换成你自己的文件.
### 示例: 为特定页面添加JavaScript文件
上面的示例将全局包添加到布局中. 如果要在依赖模块中为特定页面定义添加CSS/JavaScript文件(或替换文件)怎么做?
假设你想要用户进入身份模块的**角色管理**页面时运行**JavaScript代码**.
首先在 `wwwroot`, `Pages` 或 `Views` 文件夹下创建一个标准的JavaScript文件(默认ABP支持这些文件夹下的静态文件). 根据约定我们推荐 `Pages/Identity/Roles` 文件夹:
![bookstore-added-role-js-file](../../images/bookstore-added-role-js-file.png)
该文件的内容很简单:
````js
$(function() {
abp.log.info('My custom role script file has been loaded!');
});
````
然后将这个文件添加到角色管页面理捆绑包中:
````csharp
Configure<AbpBundlingOptions>(options =>
{
options.ScriptBundles
.Configure(
typeof(Volo.Abp.Identity.Web.Pages.Identity.Roles.IndexModel).FullName,
bundleConfig =>
{
bundleConfig.AddFiles("/Pages/Identity/Roles/my-role-script.js");
});
});
````
`typeof(Volo.Abp.Identity.Web.Pages.Identity.Roles.IndexModel).FullName` 是获取角色管理页面捆绑包名称的安全方式:
> 请注意并非每个页面都定义了这个页面的捆绑包. 它们仅在需要时定义.
除了添加新的CSS/JavaScript文件到页面,你也可以以替换(通过捆绑包contributor)已存在.
## 布局定制
布局由主题([参阅主题](Theming.md))定义设计. 它们不包含在下载的应用程序解决方案中. 通过这种方式你可以轻松的**更改**主题并获取新的功能. 你不能**直接更改**应用程序中的布局代码,除非你用自己的布局替换它(在下一部分中说明).
有一些通用的方法可以**自定义布局**,将在下一节中介绍.
### 菜单贡献者
ABP框架定义了两个**标准菜单**:
![bookstore-menus-highlighted](../../images/bookstore-menus-highlighted.png)
* `StandardMenus.Main`: 应用程序的主菜单.
* `StandardMenus.User`: 用户菜单 (通常在屏幕的右上方).
显示菜单是主题的责任,但**菜单项**由模板和你的应用程序代码决定. 只需要实现 `IMenuContributor` 接口并在 `ConfigureMenuAsync` 方法操作菜单项.
渲染菜单时需要执行菜单贡献者. **应用程序启动模板** 已经定义了菜单贡献者,所以你可以使用它. 参阅[导航菜单](Navigation-Menu.md)文档了解更多.
### 工具栏贡献者
[工具栏系统](Toolbars.md)用于在用户界面定义 **工具栏** . 模块 (或你的应用程序)可以将 **项** 添加到工具栏, 随后主题将在**布局**上呈现工具栏.
只有一个 **标准工具栏** (名称为 "Main" - 定义为常量: `StandardToolbars.Main`). 对于基本主题,按如下呈现:![bookstore-toolbar-highlighted](../../images/bookstore-toolbar-highlighted.png)
在上面的屏幕快照中,主工具栏添加了两个项目:语言开关组件和用户菜单. 你可以在此处添加自己的项.
#### 示例: 添加通知图标
在这个示例中,我们会添加一个**通知(响铃)图标**到语言切换项的左侧. 工具栏的项项目是一个**视图组件**. 所以,在你的项目中创建一个新的视图组件:
![bookstore-notification-view-component](../../images/bookstore-notification-view-component.png)
**NotificationViewComponent.cs**
````csharp
public class NotificationViewComponent : AbpViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View("/Pages/Shared/Components/Notification/Default.cshtml");
}
}
````
**Default.cshtml**
````xml
<div id="MainNotificationIcon" style="color: white; margin: 8px;">
<i class="far fa-bell"></i>
</div>
````
现在,我们创建一个类实现 `IToolbarContributor` 接口:
````csharp
public class MyToolbarContributor : IToolbarContributor
{
public Task ConfigureToolbarAsync(IToolbarConfigurationContext context)
{
if (context.Toolbar.Name == StandardToolbars.Main)
{
context.Toolbar.Items
.Insert(0, new ToolbarItem(typeof(NotificationViewComponent)));
}
return Task.CompletedTask;
}
}
````
这个类向 `Main` 工具栏的第一项添加了 `NotificationViewComponent`.
最后你需要将这个贡献者添加到 `AbpToolbarOptions`,在你模块类的 `ConfigureServices` 方法:
````csharp
Configure<AbpToolbarOptions>(options =>
{
options.Contributors.Add(new MyToolbarContributor());
});
````
这就够了,当你运行应用程序后会看到工具栏上的通知图标:
![bookstore-notification-icon-on-toolbar](../../images/bookstore-notification-icon-on-toolbar.png)
示例中的 `NotificationViewComponent` 返回没有任何数据的视图. 在实际场景中,你可能想**查询数据库**(或调用HTTP API)获取通知并传递给视图. 如果需要可以将 `JavaScript` 或 `CSS` 文件添加到工具栏的全局捆绑包中(如前所述).
参阅[工具栏文档](Toolbars.md)了解更多关于工具栏系统.
### 布局钩子
[布局钩子](Layout-Hooks.md) 系统允许你在布局页面的某些特定部分 **添加代码** . 所有主题的所有布局都应该实现这些钩子. 然后你可以将**视图组件**添加到钩子.
#### 示例: 添加谷歌统计
假设你想要添加谷歌统计脚本到布局(将适用所有的页面). 首先在你的项目中**创建一个视图组件**:
![bookstore-google-analytics-view-component](../../images/bookstore-google-analytics-view-component.png)
**NotificationViewComponent.cs**
````csharp
public class GoogleAnalyticsViewComponent : AbpViewComponent
{
public IViewComponentResult Invoke()
{
return View("/Pages/Shared/Components/GoogleAnalytics/Default.cshtml");
}
}
````
**Default.cshtml**
````html
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxx-1', 'auto');
ga('send', 'pageview');
</script>
````
在你自己的代码中更改 `UA-xxxxxx-1` .
然后你可以在你模块的 `ConfigureServices` 方法将这个组件添加到任何的钩子点:
````csharp
Configure<AbpLayoutHookOptions>(options =>
{
options.Add(
LayoutHooks.Head.Last, //The hook name
typeof(GoogleAnalyticsViewComponent) //The component to add
);
});
````
现在谷歌统计代码将在页面的 `head` 所为最后一项插入. 你(或你在使用的模块)可以将多个项添加到相同的钩子,它们都会添加到布局.
在上面我们添加 `GoogleAnalyticsViewComponent` 到所有的布局,你可能只想添加到指定的布局:
````csharp
Configure<AbpLayoutHookOptions>(options =>
{
options.Add(
LayoutHooks.Head.Last,
typeof(GoogleAnalyticsViewComponent),
layout: StandardLayouts.Application //Set the layout to add
);
});
````
参阅下面的布局部分,以了解有关布局系统的更多信息.
### 布局
布局系统允许主题定义标准,命名布局并且允许任何页面选择使用合适的布局. 有三种预定义的布局:
* "**Application**": 应用程序的主要(和默认)布局. 它通常包含页眉,菜单(侧栏),页脚,工具栏等.
* "**Account**": 登录,注册和其他类似页面使用此布局. 默认它用于 `/Pages/Account` 文件夹下的页面.
* "**Empty**": 空的最小的布局.
这些名称在 `StandardLayouts` 类定义为常量. 这是标准的布局名称,所有的主题开箱即用的实现. 你也可以创建自己的布局.
#### 布局位置
你可以在[这里](https://github.com/abpframework/abp/tree/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Layouts)找到基本主题的布局文件. 你可以将它们作用构建自己的布局的参考,也可以在必要时覆盖它们.
#### ITheme
ABP框架使用 `ITheme` 服务通过局部名称获取布局位置. 你可以替换此服务动态的选择布局位置.
#### IThemeManager
`IThemeManager` 用于获取当前主题,并得到了布局路径. 任何页面可以都决定自己的布局. 例:
````html
@using Volo.Abp.AspNetCore.Mvc.UI.Theming
@inject IThemeManager ThemeManager
@{
Layout = ThemeManager.CurrentTheme.GetLayout(StandardLayouts.Empty);
}
````
此页面将使用空白布局. 它使用 `ThemeManager.CurrentTheme.GetEmptyLayout()` 扩展方法.
如果你设置特定目录下所有页面的布局,可以在该文件夹下的 `_ViewStart.cshtml` 文件编写以上代码.

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

@ -282,6 +282,10 @@
"text": "仪表板和小部件(Widget)系统", "text": "仪表板和小部件(Widget)系统",
"path": "UI/AspNetCore/Widgets.md" "path": "UI/AspNetCore/Widgets.md"
}, },
{
"text": "自定义/扩展UI",
"path": "UI/AspNetCore/Customization-User-Interface.md"
},
{ {
"text": "主题化", "text": "主题化",
"path": "UI/AspNetCore/Theming.md" "path": "UI/AspNetCore/Theming.md"

16
framework/Volo.Abp.sln

@ -273,7 +273,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Mvc.UI.
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo", "test\Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo\Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo.csproj", "{0C498CF2-D052-4BF7-AD35-509A90F69707}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo", "test\Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo\Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Demo.csproj", "{0C498CF2-D052-4BF7-AD35-509A90F69707}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Http.Client.IdentityModel.Web.Tests", "test\Volo.Abp.Http.Client.IdentityModel.Web.Tests\Volo.Abp.Http.Client.IdentityModel.Web.Tests.csproj", "{E1963439-2BE5-4DB5-8438-2A9A792A1ADA}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.Http.Client.IdentityModel.Web.Tests", "test\Volo.Abp.Http.Client.IdentityModel.Web.Tests\Volo.Abp.Http.Client.IdentityModel.Web.Tests.csproj", "{E1963439-2BE5-4DB5-8438-2A9A792A1ADA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Abp.ObjectExtending", "src\Volo.Abp.ObjectExtending\Volo.Abp.ObjectExtending.csproj", "{D1815C77-16D6-4F99-8814-69065CD89FB3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.ObjectExtending.Tests", "test\Volo.Abp.ObjectExtending.Tests\Volo.Abp.ObjectExtending.Tests.csproj", "{17F8CA89-D9A2-4863-A5BD-B8E4D2901FD5}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -817,6 +821,14 @@ Global
{E1963439-2BE5-4DB5-8438-2A9A792A1ADA}.Debug|Any CPU.Build.0 = Debug|Any CPU {E1963439-2BE5-4DB5-8438-2A9A792A1ADA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E1963439-2BE5-4DB5-8438-2A9A792A1ADA}.Release|Any CPU.ActiveCfg = Release|Any CPU {E1963439-2BE5-4DB5-8438-2A9A792A1ADA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E1963439-2BE5-4DB5-8438-2A9A792A1ADA}.Release|Any CPU.Build.0 = Release|Any CPU {E1963439-2BE5-4DB5-8438-2A9A792A1ADA}.Release|Any CPU.Build.0 = Release|Any CPU
{D1815C77-16D6-4F99-8814-69065CD89FB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1815C77-16D6-4F99-8814-69065CD89FB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1815C77-16D6-4F99-8814-69065CD89FB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1815C77-16D6-4F99-8814-69065CD89FB3}.Release|Any CPU.Build.0 = Release|Any CPU
{17F8CA89-D9A2-4863-A5BD-B8E4D2901FD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17F8CA89-D9A2-4863-A5BD-B8E4D2901FD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17F8CA89-D9A2-4863-A5BD-B8E4D2901FD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17F8CA89-D9A2-4863-A5BD-B8E4D2901FD5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -956,6 +968,8 @@ Global
{29E42ADB-85F8-44AE-A9B0-078F84C1B866} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} {29E42ADB-85F8-44AE-A9B0-078F84C1B866} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6}
{0C498CF2-D052-4BF7-AD35-509A90F69707} = {447C8A77-E5F0-4538-8687-7383196D04EA} {0C498CF2-D052-4BF7-AD35-509A90F69707} = {447C8A77-E5F0-4538-8687-7383196D04EA}
{E1963439-2BE5-4DB5-8438-2A9A792A1ADA} = {447C8A77-E5F0-4538-8687-7383196D04EA} {E1963439-2BE5-4DB5-8438-2A9A792A1ADA} = {447C8A77-E5F0-4538-8687-7383196D04EA}
{D1815C77-16D6-4F99-8814-69065CD89FB3} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6}
{17F8CA89-D9A2-4863-A5BD-B8E4D2901FD5} = {447C8A77-E5F0-4538-8687-7383196D04EA}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BB97ECF4-9A84-433F-A80B-2A3285BDD1D5} SolutionGuid = {BB97ECF4-9A84-433F-A80B-2A3285BDD1D5}

36
framework/src/Volo.Abp.AutoMapper/AutoMapper/AbpAutoMapperExtensibleDtoExtensions.cs

@ -0,0 +1,36 @@
using System.Collections.Generic;
using Volo.Abp.Data;
using Volo.Abp.ObjectExtending;
namespace AutoMapper
{
public static class AbpAutoMapperExtensibleDtoExtensions
{
public static IMappingExpression<TSource, TDestination> MapExtraProperties<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> mappingExpression,
MappingPropertyDefinitionChecks definitionChecks = MappingPropertyDefinitionChecks.Both)
where TDestination : IHasExtraProperties
where TSource : IHasExtraProperties
{
return mappingExpression
.ForMember(
x => x.ExtraProperties,
y => y.MapFrom(
(source, destination, extraProps) =>
{
var result = extraProps.IsNullOrEmpty()
? new Dictionary<string, object>()
: new Dictionary<string, object>(extraProps);
HasExtraPropertiesObjectExtendingExtensions
.MapExtraPropertiesTo<TSource, TDestination>(
source.ExtraProperties,
result
);
return result;
})
);
}
}
}

1
framework/src/Volo.Abp.AutoMapper/Volo.Abp.AutoMapper.csproj

@ -15,6 +15,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Volo.Abp.ObjectExtending\Volo.Abp.ObjectExtending.csproj" />
<ProjectReference Include="..\Volo.Abp.ObjectMapping\Volo.Abp.ObjectMapping.csproj" /> <ProjectReference Include="..\Volo.Abp.ObjectMapping\Volo.Abp.ObjectMapping.csproj" />
</ItemGroup> </ItemGroup>

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

@ -3,11 +3,14 @@ using AutoMapper;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
using Volo.Abp.ObjectExtending;
using Volo.Abp.ObjectMapping; using Volo.Abp.ObjectMapping;
namespace Volo.Abp.AutoMapper namespace Volo.Abp.AutoMapper
{ {
[DependsOn(typeof(AbpObjectMappingModule))] [DependsOn(
typeof(AbpObjectMappingModule),
typeof(AbpObjectExtendingModule))]
public class AbpAutoMapperModule : AbpModule public class AbpAutoMapperModule : AbpModule
{ {
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)

15
framework/src/Volo.Abp.Core/Volo/Abp/Check.cs

@ -121,6 +121,21 @@ namespace Volo.Abp
return value; return value;
} }
[ContractAnnotation("type:null => halt")]
public static Type AssignableTo<TBaseType>(
Type type,
[InvokerParameterName] [NotNull] string parameterName)
{
NotNull(type, parameterName);
if (!type.IsAssignableTo<TBaseType>())
{
throw new ArgumentException($"{parameterName} (type of {type.AssemblyQualifiedName}) should be assignable to the {typeof(TBaseType).GetFullNameWithAssemblyName()}!");
}
return type;
}
public static string Length( public static string Length(
[CanBeNull] string value, [CanBeNull] string value,
[InvokerParameterName] [NotNull] string parameterName, [InvokerParameterName] [NotNull] string parameterName,

1
framework/src/Volo.Abp.Data/Volo.Abp.Data.csproj

@ -16,6 +16,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Volo.Abp.Core\Volo.Abp.Core.csproj" /> <ProjectReference Include="..\Volo.Abp.Core\Volo.Abp.Core.csproj" />
<ProjectReference Include="..\Volo.Abp.ObjectExtending\Volo.Abp.ObjectExtending.csproj" />
<ProjectReference Include="..\Volo.Abp.Uow\Volo.Abp.Uow.csproj" /> <ProjectReference Include="..\Volo.Abp.Uow\Volo.Abp.Uow.csproj" />
</ItemGroup> </ItemGroup>

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

@ -2,13 +2,15 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
using Volo.Abp.ObjectExtending;
using Volo.Abp.Uow; using Volo.Abp.Uow;
namespace Volo.Abp.Data namespace Volo.Abp.Data
{ {
[DependsOn( [DependsOn(
typeof(AbpObjectExtendingModule),
typeof(AbpUnitOfWorkModule) typeof(AbpUnitOfWorkModule)
)] )]
public class AbpDataModule : AbpModule public class AbpDataModule : AbpModule
{ {
public override void PreConfigureServices(ServiceConfigurationContext context) public override void PreConfigureServices(ServiceConfigurationContext context)

2
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/AuditedEntityWithUserDto.cs

@ -5,6 +5,7 @@ namespace Volo.Abp.Application.Dtos
{ {
/// <summary> /// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface. /// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface.
/// It has the <see cref="Creator"/> and <see cref="LastModifier"/> objects as a DTOs represent the related user.
/// </summary> /// </summary>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam> /// <typeparam name="TUserDto">Type of the User DTO</typeparam>
[Serializable] [Serializable]
@ -19,6 +20,7 @@ namespace Volo.Abp.Application.Dtos
/// <summary> /// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface. /// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface.
/// It has the <see cref="Creator"/> and <see cref="LastModifier"/> objects as a DTOs represent the related user.
/// </summary> /// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam> /// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam> /// <typeparam name="TUserDto">Type of the User DTO</typeparam>

4
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/CreationAuditedEntityWithUserDto.cs

@ -5,6 +5,7 @@ namespace Volo.Abp.Application.Dtos
{ {
/// <summary> /// <summary>
/// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject{TCreator}"/> interface. /// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject{TCreator}"/> interface.
/// It also has the <see cref="Creator"/> object as a DTO represents the user.
/// </summary> /// </summary>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam> /// <typeparam name="TUserDto">Type of the User DTO</typeparam>
[Serializable] [Serializable]
@ -14,7 +15,8 @@ namespace Volo.Abp.Application.Dtos
} }
/// <summary> /// <summary>
/// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObjectObject{TCreator}"/> interface. /// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject{TCreator}"/> interface.
/// It also has the <see cref="Creator"/> object as a DTO represents the user.
/// </summary> /// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam> /// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam> /// <typeparam name="TUserDto">Type of the User DTO</typeparam>

35
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleAuditedEntityDto.cs

@ -0,0 +1,35 @@
using System;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
[Serializable]
public abstract class ExtensibleAuditedEntityDto<TPrimaryKey> : ExtensibleCreationAuditedEntityDto<TPrimaryKey>, IAuditedObject
{
/// <inheritdoc />
public DateTime? LastModificationTime { get; set; }
/// <inheritdoc />
public Guid? LastModifierId { get; set; }
}
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
[Serializable]
public abstract class ExtensibleAuditedEntityDto : ExtensibleCreationAuditedEntityDto, IAuditedObject
{
/// <inheritdoc />
public DateTime? LastModificationTime { get; set; }
/// <inheritdoc />
public Guid? LastModifierId { get; set; }
}
}

40
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleAuditedEntityWithUserDto.cs

@ -0,0 +1,40 @@
using System;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface.
/// It has the <see cref="Creator"/> and <see cref="LastModifier"/> objects as a DTOs represent the related user.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam>
[Serializable]
public abstract class ExtensibleAuditedEntityWithUserDto<TPrimaryKey, TUserDto> : ExtensibleAuditedEntityDto<TPrimaryKey>, IAuditedObject<TUserDto>
{
/// <inheritdoc />
public TUserDto Creator { get; set; }
/// <inheritdoc />
public TUserDto LastModifier { get; set; }
}
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IAuditedObject"/> interface.
/// It has the <see cref="Creator"/> and <see cref="LastModifier"/> objects as a DTOs represent the related user.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam>
[Serializable]
public abstract class ExtensibleAuditedEntityWithUserDto<TUserDto> : ExtensibleAuditedEntityDto,
IAuditedObject<TUserDto>
{
/// <inheritdoc />
public TUserDto Creator { get; set; }
/// <inheritdoc />
public TUserDto LastModifier { get; set; }
}
}

35
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleCreationAuditedEntityDto.cs

@ -0,0 +1,35 @@
using System;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject"/> interface.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
[Serializable]
public abstract class ExtensibleCreationAuditedEntityDto<TPrimaryKey> : ExtensibleEntityDto<TPrimaryKey>, ICreationAuditedObject
{
/// <inheritdoc />
public DateTime CreationTime { get; set; }
/// <inheritdoc />
public Guid? CreatorId { get; set; }
}
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject"/> interface.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
[Serializable]
public abstract class ExtensibleCreationAuditedEntityDto : ExtensibleEntityDto, ICreationAuditedObject
{
/// <inheritdoc />
public DateTime CreationTime { get; set; }
/// <inheritdoc />
public Guid? CreatorId { get; set; }
}
}

32
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleCreationAuditedEntityWithUserDto.cs

@ -0,0 +1,32 @@
using System;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject{TCreator}"/> interface.
/// It has the <see cref="Creator"/> object as a DTO represents the user.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam>
[Serializable]
public abstract class ExtensibleCreationAuditedEntityWithUserDto<TPrimaryKey, TUserDto> : ExtensibleCreationAuditedEntityDto<TPrimaryKey>, ICreationAuditedObject<TUserDto>
{
public TUserDto Creator { get; set; }
}
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="ICreationAuditedObject{TCreator}"/> interface.
/// It has the <see cref="Creator"/> object as a DTO represents the user.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TUserDto">Type of the User DTO</typeparam>
[Serializable]
public abstract class ExtensibleCreationAuditedEntityWithUserDto<TUserDto> : ExtensibleCreationAuditedEntityDto,
ICreationAuditedObject<TUserDto>
{
public TUserDto Creator { get; set; }
}
}

28
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleEntityDto.cs

@ -0,0 +1,28 @@
using System;
using Volo.Abp.ObjectExtending;
namespace Volo.Abp.Application.Dtos
{
[Serializable]
public abstract class ExtensibleEntityDto<TKey> : ExtensibleObject, IEntityDto<TKey>
{
/// <summary>
/// Id of the entity.
/// </summary>
public TKey Id { get; set; }
public override string ToString()
{
return $"[DTO: {GetType().Name}] Id = {Id}";
}
}
[Serializable]
public abstract class ExtensibleEntityDto : ExtensibleObject, IEntityDto
{
public override string ToString()
{
return $"[DTO: {GetType().Name}]";
}
}
}

41
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleFullAuditedEntityDto.cs

@ -0,0 +1,41 @@
using System;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObject"/> interface.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
[Serializable]
public abstract class ExtensibleFullAuditedEntityDto<TPrimaryKey> : ExtensibleAuditedEntityDto<TPrimaryKey>, IFullAuditedObject
{
/// <inheritdoc />
public bool IsDeleted { get; set; }
/// <inheritdoc />
public Guid? DeleterId { get; set; }
/// <inheritdoc />
public DateTime? DeletionTime { get; set; }
}
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObject"/> interface.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
[Serializable]
public abstract class ExtensibleFullAuditedEntityDto : ExtensibleAuditedEntityDto, IFullAuditedObject
{
/// <inheritdoc />
public bool IsDeleted { get; set; }
/// <inheritdoc />
public Guid? DeleterId { get; set; }
/// <inheritdoc />
public DateTime? DeletionTime { get; set; }
}
}

46
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/ExtensibleFullAuditedEntityWithUserDto.cs

@ -0,0 +1,46 @@
using System;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObject{TUser}"/> interface.
/// It has the <see cref="Creator"/>, <see cref="LastModifier"/> and <see cref="Deleter"/> objects as a DTOs represent the related user.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
/// <typeparam name="TUserDto">Type of the User</typeparam>
[Serializable]
public abstract class ExtensibleFullAuditedEntityWithUserDto<TPrimaryKey, TUserDto> : ExtensibleFullAuditedEntityDto<TPrimaryKey>, IFullAuditedObject<TUserDto>
{
/// <inheritdoc />
public TUserDto Creator { get; set; }
/// <inheritdoc />
public TUserDto LastModifier { get; set; }
/// <inheritdoc />
public TUserDto Deleter { get; set; }
}
/// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObject{TUser}"/> interface.
/// It has the <see cref="Creator"/>, <see cref="LastModifier"/> and <see cref="Deleter"/> objects as a DTOs represent the related user.
/// It also implements the <see cref="IHasExtraProperties"/> interface.
/// </summary>
/// <typeparam name="TUserDto">Type of the User</typeparam>
[Serializable]
public abstract class ExtensibleFullAuditedEntityWithUserDto<TUserDto> : ExtensibleFullAuditedEntityDto,
IFullAuditedObject<TUserDto>
{
/// <inheritdoc />
public TUserDto Creator { get; set; }
/// <inheritdoc />
public TUserDto LastModifier { get; set; }
/// <inheritdoc />
public TUserDto Deleter { get; set; }
}
}

6
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/FullAuditedEntityWithUserDto.cs

@ -4,7 +4,8 @@ using Volo.Abp.Auditing;
namespace Volo.Abp.Application.Dtos namespace Volo.Abp.Application.Dtos
{ {
/// <summary> /// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObjectObject{TUser}"/> interface. /// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObject{TUser}"/> interface.
/// It has the <see cref="Creator"/>, <see cref="LastModifier"/> and <see cref="Deleter"/> objects as a DTOs represent the related user.
/// </summary> /// </summary>
/// <typeparam name="TUserDto">Type of the User</typeparam> /// <typeparam name="TUserDto">Type of the User</typeparam>
[Serializable] [Serializable]
@ -21,7 +22,8 @@ namespace Volo.Abp.Application.Dtos
} }
/// <summary> /// <summary>
/// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObjectObject{TUser}"/> interface. /// This class can be inherited by DTO classes to implement <see cref="IFullAuditedObject{TUser}"/> interface.
/// It has the <see cref="Creator"/>, <see cref="LastModifier"/> and <see cref="Deleter"/> objects as a DTOs represent the related user.
/// </summary> /// </summary>
/// <typeparam name="TPrimaryKey">Type of primary key</typeparam> /// <typeparam name="TPrimaryKey">Type of primary key</typeparam>
/// <typeparam name="TUserDto">Type of the User</typeparam> /// <typeparam name="TUserDto">Type of the User</typeparam>

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

@ -19,7 +19,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.0" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>

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

@ -18,11 +18,11 @@ 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;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
using Volo.Abp.ObjectExtending;
using Volo.Abp.Reflection; using Volo.Abp.Reflection;
using Volo.Abp.Timing; using Volo.Abp.Timing;
using Volo.Abp.Uow; using Volo.Abp.Uow;
@ -183,10 +183,18 @@ namespace Volo.Abp.EntityFrameworkCore
return; return;
} }
var propertyNames = EntityExtensionManager.GetPropertyNames(entityType); var objectExtension = ObjectExtensionManager.Instance.GetOrNull(entityType);
if (objectExtension == null)
{
return;
}
foreach (var propertyName in propertyNames) foreach (var property in objectExtension.GetProperties())
{ {
if (!property.IsMappedToFieldForEfCore())
{
continue;
}
/* Checking "currentValue != null" has a good advantage: /* Checking "currentValue != null" has a good advantage:
* Assume that you we already using a named extra property, * Assume that you we already using a named extra property,
* then decided to create a field (entity extension) for it. * then decided to create a field (entity extension) for it.
@ -194,10 +202,10 @@ namespace Volo.Abp.EntityFrameworkCore
* updates the field on the next save! * updates the field on the next save!
*/ */
var currentValue = e.Entry.CurrentValues[propertyName]; var currentValue = e.Entry.CurrentValues[property.Name];
if (currentValue != null) if (currentValue != null)
{ {
entity.SetProperty(propertyName, currentValue); entity.SetProperty(property.Name, currentValue);
} }
} }
} }
@ -251,12 +259,21 @@ namespace Volo.Abp.EntityFrameworkCore
{ {
return; return;
} }
var propertyNames = EntityExtensionManager.GetPropertyNames(entityType);
foreach (var propertyName in propertyNames) var objectExtension = ObjectExtensionManager.Instance.GetOrNull(entityType);
if (objectExtension == null)
{
return;
}
foreach (var property in objectExtension.GetProperties())
{ {
entry.Property(propertyName).CurrentValue = entity.GetProperty(propertyName); if (!entity.HasProperty(property.Name))
{
continue;
}
entry.Property(property.Name).CurrentValue = entity.GetProperty(property.Name);
} }
} }

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

@ -1,14 +0,0 @@
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

@ -1,133 +0,0 @@
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

@ -1,17 +0,0 @@
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;
}
}
}

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

@ -5,10 +5,10 @@ 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;
using Volo.Abp.ObjectExtending;
namespace Volo.Abp.EntityFrameworkCore.Modeling namespace Volo.Abp.EntityFrameworkCore.Modeling
{ {
@ -18,6 +18,7 @@ namespace Volo.Abp.EntityFrameworkCore.Modeling
{ {
b.TryConfigureConcurrencyStamp(); b.TryConfigureConcurrencyStamp();
b.TryConfigureExtraProperties(); b.TryConfigureExtraProperties();
b.TryConfigureObjectExtensions();
b.TryConfigureMayHaveCreator(); b.TryConfigureMayHaveCreator();
b.TryConfigureMustHaveCreator(); b.TryConfigureMustHaveCreator();
b.TryConfigureSoftDelete(); b.TryConfigureSoftDelete();
@ -54,15 +55,30 @@ namespace Volo.Abp.EntityFrameworkCore.Modeling
public static void TryConfigureExtraProperties(this EntityTypeBuilder b) public static void TryConfigureExtraProperties(this EntityTypeBuilder b)
{ {
//TODO: Max length? if (!b.Metadata.ClrType.IsAssignableTo<IHasExtraProperties>())
if (b.Metadata.ClrType.IsAssignableTo<IHasExtraProperties>())
{ {
b.Property<Dictionary<string, object>>(nameof(IHasExtraProperties.ExtraProperties)) return;
.HasColumnName(nameof(IHasExtraProperties.ExtraProperties)) }
.HasConversion(new ExtraPropertiesValueConverter(b.Metadata.ClrType))
.Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, object>());
EntityExtensionManager.ConfigureExtensions(b.Metadata.ClrType, b); b.Property<Dictionary<string, object>>(nameof(IHasExtraProperties.ExtraProperties))
.HasColumnName(nameof(IHasExtraProperties.ExtraProperties))
.HasConversion(new ExtraPropertiesValueConverter(b.Metadata.ClrType))
.Metadata.SetValueComparer(new AbpDictionaryValueComparer<string, object>());
b.TryConfigureObjectExtensions();
}
public static void ConfigureObjectExtensions<T>(this EntityTypeBuilder<T> b)
where T : class, IHasExtraProperties
{
b.As<EntityTypeBuilder>().TryConfigureObjectExtensions();
}
public static void TryConfigureObjectExtensions(this EntityTypeBuilder b)
{
if (b.Metadata.ClrType.IsAssignableTo<IHasExtraProperties>())
{
ObjectExtensionManager.Instance.ConfigureEfCoreEntity(b);
} }
} }
@ -286,7 +302,6 @@ namespace Volo.Abp.EntityFrameworkCore.Modeling
b.As<EntityTypeBuilder>().TryConfigureConcurrencyStamp(); b.As<EntityTypeBuilder>().TryConfigureConcurrencyStamp();
} }
//TODO: Add other interfaces (IAuditedObject<TUser>...) //TODO: Add other interfaces (IAuditedObject<TUser>...)
} }
} }

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

@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Newtonsoft.Json; using Newtonsoft.Json;
using Volo.Abp.EntityFrameworkCore.Extensions; using Volo.Abp.ObjectExtending;
namespace Volo.Abp.EntityFrameworkCore.ValueConverters namespace Volo.Abp.EntityFrameworkCore.ValueConverters
{ {
@ -22,11 +22,16 @@ namespace Volo.Abp.EntityFrameworkCore.ValueConverters
if (entityType != null) if (entityType != null)
{ {
var propertyNames = EntityExtensionManager.GetPropertyNames(entityType); var objectExtension = ObjectExtensionManager.Instance.GetOrNull(entityType);
if (objectExtension != null)
foreach (var propertyName in propertyNames)
{ {
copyDictionary.Remove(propertyName); foreach (var property in objectExtension.GetProperties())
{
if (property.IsMappedToFieldForEfCore())
{
copyDictionary.Remove(property.Name);
}
}
} }
} }

41
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/EfCoreObjectExtensionInfoExtensions.cs

@ -0,0 +1,41 @@
using System;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Volo.Abp.ObjectExtending
{
public static class EfCoreObjectExtensionInfoExtensions
{
public static ObjectExtensionInfo MapEfCoreProperty<TProperty>(
[NotNull] this ObjectExtensionInfo objectExtensionInfo,
[NotNull] string propertyName,
[CanBeNull] Action<PropertyBuilder> propertyBuildAction)
{
return objectExtensionInfo.MapEfCoreProperty(
typeof(TProperty),
propertyName,
propertyBuildAction
);
}
public static ObjectExtensionInfo MapEfCoreProperty(
[NotNull] this ObjectExtensionInfo objectExtensionInfo,
[NotNull] Type propertyType,
[NotNull] string propertyName,
[CanBeNull] Action<PropertyBuilder> propertyBuildAction)
{
Check.NotNull(objectExtensionInfo, nameof(objectExtensionInfo));
return objectExtensionInfo.AddOrUpdateProperty(
propertyType,
propertyName,
options =>
{
options.MapEfCore(
propertyBuildAction
);
}
);
}
}
}

80
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/EfCoreObjectExtensionManagerExtensions.cs

@ -0,0 +1,80 @@
using System;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Volo.Abp.Data;
using Volo.Abp.Domain.Entities;
namespace Volo.Abp.ObjectExtending
{
public static class EfCoreObjectExtensionManagerExtensions
{
public static ObjectExtensionManager MapEfCoreProperty<TEntity, TProperty>(
[NotNull] this ObjectExtensionManager objectExtensionManager,
[NotNull] string propertyName,
[CanBeNull] Action<PropertyBuilder> propertyBuildAction = null)
where TEntity : IHasExtraProperties, IEntity
{
return objectExtensionManager.MapEfCoreProperty(
typeof(TEntity),
typeof(TProperty),
propertyName,
propertyBuildAction
);
}
public static ObjectExtensionManager MapEfCoreProperty(
[NotNull] this ObjectExtensionManager objectExtensionManager,
[NotNull] Type entityType,
[NotNull] Type propertyType,
[NotNull] string propertyName,
[CanBeNull] Action<PropertyBuilder> propertyBuildAction = null)
{
Check.NotNull(objectExtensionManager, nameof(objectExtensionManager));
return objectExtensionManager.AddOrUpdateProperty(
entityType,
propertyType,
propertyName,
options =>
{
options.MapEfCore(
propertyBuildAction
);
}
);
}
public static void ConfigureEfCoreEntity(
[NotNull] this ObjectExtensionManager objectExtensionManager,
[NotNull] EntityTypeBuilder typeBuilder)
{
Check.NotNull(objectExtensionManager, nameof(objectExtensionManager));
Check.NotNull(typeBuilder, nameof(typeBuilder));
var objectExtension = objectExtensionManager.GetOrNull(typeBuilder.Metadata.ClrType);
if (objectExtension == null)
{
return;
}
foreach (var property in objectExtension.GetProperties())
{
var efCoreMapping = property.GetEfCoreMappingOrNull();
if (efCoreMapping == null)
{
continue;
}
/* Prevent multiple calls to the entityTypeBuilder.Property(...) method */
if (typeBuilder.Metadata.FindProperty(property.Name) != null)
{
continue;
}
var propertyBuilder = typeBuilder.Property(property.Type, property.Name);
efCoreMapping.PropertyBuildAction?.Invoke(propertyBuilder);
}
}
}
}

50
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/EfCoreObjectExtensionPropertyInfoExtensions.cs

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Volo.Abp.ObjectExtending
{
public static class EfCoreObjectExtensionPropertyInfoExtensions
{
public const string EfCorePropertyConfigurationName = "EfCoreMapping";
[NotNull]
public static ObjectExtensionPropertyInfo MapEfCore(
[NotNull] this ObjectExtensionPropertyInfo propertyExtension,
[CanBeNull] Action<PropertyBuilder> propertyBuildAction = null)
{
Check.NotNull(propertyExtension, nameof(propertyExtension));
propertyExtension.Configuration[EfCorePropertyConfigurationName] =
new ObjectExtensionPropertyInfoEfCoreMappingOptions(
propertyExtension,
propertyBuildAction
);
return propertyExtension;
}
[CanBeNull]
public static ObjectExtensionPropertyInfoEfCoreMappingOptions GetEfCoreMappingOrNull(
[NotNull] this ObjectExtensionPropertyInfo propertyExtension)
{
Check.NotNull(propertyExtension, nameof(propertyExtension));
return propertyExtension
.Configuration
.GetOrDefault(EfCorePropertyConfigurationName)
as ObjectExtensionPropertyInfoEfCoreMappingOptions;
}
public static bool IsMappedToFieldForEfCore(
[NotNull] this ObjectExtensionPropertyInfo propertyExtension)
{
Check.NotNull(propertyExtension, nameof(propertyExtension));
return propertyExtension
.Configuration
.ContainsKey(EfCorePropertyConfigurationName);
}
}
}

27
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/ObjectExtending/ObjectExtensionPropertyInfoEfCoreMappingOptions.cs

@ -0,0 +1,27 @@
using System;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Volo.Abp.ObjectExtending
{
public class ObjectExtensionPropertyInfoEfCoreMappingOptions
{
[NotNull]
public ObjectExtensionPropertyInfo ExtensionProperty { get; }
[NotNull]
public ObjectExtensionInfo ObjectExtension => ExtensionProperty.ObjectExtension;
[CanBeNull]
public Action<PropertyBuilder> PropertyBuildAction { get; set; }
public ObjectExtensionPropertyInfoEfCoreMappingOptions(
[NotNull] ObjectExtensionPropertyInfo extensionProperty,
[CanBeNull] Action<PropertyBuilder> propertyBuildAction = null)
{
ExtensionProperty = Check.NotNull(extensionProperty, nameof(extensionProperty));
PropertyBuildAction = propertyBuildAction;
}
}
}

3
framework/src/Volo.Abp.ObjectExtending/FodyWeavers.xml

@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<ConfigureAwait ContinueOnCapturedContext="false" />
</Weavers>

30
framework/src/Volo.Abp.ObjectExtending/FodyWeavers.xsd

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
<xs:element name="Weavers">
<xs:complexType>
<xs:all>
<xs:element name="ConfigureAwait" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:attribute name="ContinueOnCapturedContext" type="xs:boolean" />
</xs:complexType>
</xs:element>
</xs:all>
<xs:attribute name="VerifyAssembly" type="xs:boolean">
<xs:annotation>
<xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="VerifyIgnoreCodes" type="xs:string">
<xs:annotation>
<xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="GenerateXsd" type="xs:boolean">
<xs:annotation>
<xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>

3
framework/src/Volo.Abp.ObjectExtending/Properties/AssemblyInfo.cs

@ -0,0 +1,3 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Volo.Abp.ObjectExtending.Tests")]

21
framework/src/Volo.Abp.ObjectExtending/Volo.Abp.ObjectExtending.csproj

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\configureawait.props" />
<Import Project="..\..\..\common.props" />
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>Volo.Abp.ObjectExtending</AssemblyName>
<PackageId>Volo.Abp.ObjectExtending</PackageId>
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<RootNamespace />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Volo.Abp.Core\Volo.Abp.Core.csproj" />
</ItemGroup>
</Project>

0
framework/src/Volo.Abp.Data/Volo/Abp/Data/HasExtraPropertiesExtensions.cs → framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/HasExtraPropertiesExtensions.cs

0
framework/src/Volo.Abp.Data/Volo/Abp/Data/IHasExtraProperties.cs → framework/src/Volo.Abp.ObjectExtending/Volo/Abp/Data/IHasExtraProperties.cs

9
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/AbpObjectExtendingModule.cs

@ -0,0 +1,9 @@
using Volo.Abp.Modularity;
namespace Volo.Abp.ObjectExtending
{
public class AbpObjectExtendingModule : AbpModule
{
}
}

17
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ExtensibleObject.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using Volo.Abp.Data;
namespace Volo.Abp.ObjectExtending
{
[Serializable]
public class ExtensibleObject : IHasExtraProperties
{
public Dictionary<string, object> ExtraProperties { get; protected set; }
public ExtensibleObject()
{
ExtraProperties = new Dictionary<string, object>();
}
}
}

175
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/HasExtraPropertiesObjectExtendingExtensions.cs

@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
using Volo.Abp.Data;
namespace Volo.Abp.ObjectExtending
{
public static class HasExtraPropertiesObjectExtendingExtensions
{
/// <summary>
/// Copies extra properties from the <paramref name="source"/> object
/// to the <paramref name="destination"/> object.
///
/// Checks property definitions (over the <see cref="ObjectExtensionManager"/>)
/// based on the <paramref name="definitionChecks"/> preference.
/// </summary>
/// <typeparam name="TSource">Source class type</typeparam>
/// <typeparam name="TDestination">Destination class type</typeparam>
/// <param name="source">The source object</param>
/// <param name="destination">The destination object</param>
/// <param name="definitionChecks">
/// Controls which properties to map.
/// </param>
public static void MapExtraPropertiesTo<TSource, TDestination>(
[NotNull] this TSource source,
[NotNull] TDestination destination,
MappingPropertyDefinitionChecks definitionChecks = MappingPropertyDefinitionChecks.Both)
where TSource : IHasExtraProperties
where TDestination : IHasExtraProperties
{
Check.NotNull(source, nameof(source));
Check.NotNull(destination, nameof(destination));
MapExtraPropertiesTo(
typeof(TSource),
typeof(TDestination),
source.ExtraProperties,
destination.ExtraProperties,
definitionChecks
);
}
/// <summary>
/// Copies extra properties from the <paramref name="sourceDictionary"/> object
/// to the <paramref name="destinationDictionary"/> object.
///
/// Checks property definitions (over the <see cref="ObjectExtensionManager"/>)
/// based on the <paramref name="definitionChecks"/> preference.
/// </summary>
/// <typeparam name="TSource">Source class type (for definition check)</typeparam>
/// <typeparam name="TDestination">Destination class type (for definition check)</typeparam>
/// <param name="sourceDictionary">The source dictionary object</param>
/// <param name="destinationDictionary">The destination dictionary object</param>
/// <param name="definitionChecks">
/// Controls which properties to map.
/// </param>
public static void MapExtraPropertiesTo<TSource, TDestination>(
[NotNull] Dictionary<string, object> sourceDictionary,
[NotNull] Dictionary<string, object> destinationDictionary,
MappingPropertyDefinitionChecks definitionChecks = MappingPropertyDefinitionChecks.Both)
where TSource : IHasExtraProperties
where TDestination : IHasExtraProperties
{
MapExtraPropertiesTo(
typeof(TSource),
typeof(TDestination),
sourceDictionary,
destinationDictionary,
definitionChecks
);
}
/// <summary>
/// Copies extra properties from the <paramref name="sourceDictionary"/> object
/// to the <paramref name="destinationDictionary"/> object.
///
/// Checks property definitions (over the <see cref="ObjectExtensionManager"/>)
/// based on the <paramref name="definitionChecks"/> preference.
/// </summary>
/// <param name="sourceType">Source type (for definition check)</param>
/// <param name="destinationType">Destination class type (for definition check)</param>
/// <param name="sourceDictionary">The source dictionary object</param>
/// <param name="destinationDictionary">The destination dictionary object</param>
/// <param name="definitionChecks">
/// Controls which properties to map.
/// </param>
public static void MapExtraPropertiesTo(
[NotNull] Type sourceType,
[NotNull] Type destinationType,
[NotNull] Dictionary<string, object> sourceDictionary,
[NotNull] Dictionary<string, object> destinationDictionary,
MappingPropertyDefinitionChecks definitionChecks = MappingPropertyDefinitionChecks.Both)
{
Check.AssignableTo<IHasExtraProperties>(sourceType, nameof(sourceType));
Check.AssignableTo<IHasExtraProperties>(destinationType, nameof(destinationType));
Check.NotNull(sourceDictionary, nameof(sourceDictionary));
Check.NotNull(destinationDictionary, nameof(destinationDictionary));
var sourceObjectExtension = ObjectExtensionManager.Instance.GetOrNull(sourceType);
if (definitionChecks.HasFlag(MappingPropertyDefinitionChecks.Source) &&
sourceObjectExtension == null)
{
return;
}
var destinationObjectExtension = ObjectExtensionManager.Instance.GetOrNull(destinationType);
if (definitionChecks.HasFlag(MappingPropertyDefinitionChecks.Destination) &&
destinationObjectExtension == null)
{
return;
}
if (definitionChecks == MappingPropertyDefinitionChecks.None)
{
foreach (var keyValue in sourceDictionary)
{
destinationDictionary[keyValue.Key] = keyValue.Value;
}
}
else if (definitionChecks == MappingPropertyDefinitionChecks.Source)
{
Debug.Assert(sourceObjectExtension != null, nameof(sourceObjectExtension) + " != null");
foreach (var property in sourceObjectExtension.GetProperties())
{
if (!sourceDictionary.ContainsKey(property.Name))
{
continue;
}
destinationDictionary[property.Name] = sourceDictionary[property.Name];
}
}
else if (definitionChecks == MappingPropertyDefinitionChecks.Destination)
{
Debug.Assert(destinationObjectExtension != null, nameof(destinationObjectExtension) + " != null");
foreach (var keyValue in sourceDictionary)
{
if (!destinationObjectExtension.HasProperty(keyValue.Key))
{
continue;
}
destinationDictionary[keyValue.Key] = keyValue.Value;
}
}
else if (definitionChecks == MappingPropertyDefinitionChecks.Both)
{
Debug.Assert(sourceObjectExtension != null, nameof(sourceObjectExtension) + " != null");
Debug.Assert(destinationObjectExtension != null, nameof(destinationObjectExtension) + " != null");
foreach (var property in sourceObjectExtension.GetProperties())
{
if (!sourceDictionary.ContainsKey(property.Name))
{
continue;
}
if (!destinationObjectExtension.HasProperty(property.Name))
{
continue;
}
destinationDictionary[property.Name] = sourceDictionary[property.Name];
}
}
else
{
throw new NotImplementedException(definitionChecks + " was not implemented!");
}
}
}
}

28
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/MappingPropertyDefinitionChecks.cs

@ -0,0 +1,28 @@
using System;
namespace Volo.Abp.ObjectExtending
{
[Flags]
public enum MappingPropertyDefinitionChecks : byte
{
/// <summary>
/// No check. Copy all extra properties from the source to the destination.
/// </summary>
None = 0,
/// <summary>
/// Copy the extra properties defined for the source class.
/// </summary>
Source = 1,
/// <summary>
/// Copy the extra properties defined for the destination class.
/// </summary>
Destination = 2,
/// <summary>
/// Copy extra properties defined for both of the source and destination classes.
/// </summary>
Both = Source | Destination
}
}

78
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionInfo.cs

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using JetBrains.Annotations;
using Volo.Abp.Data;
namespace Volo.Abp.ObjectExtending
{
public class ObjectExtensionInfo
{
[NotNull]
public Type Type { get; }
[NotNull]
protected Dictionary<string, ObjectExtensionPropertyInfo> Properties { get; }
[NotNull]
public Dictionary<object, object> Configuration { get; }
public ObjectExtensionInfo([NotNull] Type type)
{
Type = Check.AssignableTo<IHasExtraProperties>(type, nameof(type));
Properties = new Dictionary<string, ObjectExtensionPropertyInfo>();
Configuration = new Dictionary<object, object>();
}
public virtual bool HasProperty(string propertyName)
{
return Properties.ContainsKey(propertyName);
}
[NotNull]
public virtual ObjectExtensionInfo AddOrUpdateProperty<TProperty>(
[NotNull] string propertyName,
[CanBeNull] Action<ObjectExtensionPropertyInfo> configureAction = null)
{
return AddOrUpdateProperty(
typeof(TProperty),
propertyName,
configureAction
);
}
[NotNull]
public virtual ObjectExtensionInfo AddOrUpdateProperty(
[NotNull] Type propertyType,
[NotNull] string propertyName,
[CanBeNull] Action<ObjectExtensionPropertyInfo> configureAction = null)
{
Check.NotNull(propertyType, nameof(propertyType));
Check.NotNull(propertyName, nameof(propertyName));
var propertyInfo = Properties.GetOrAdd(
propertyName,
() => new ObjectExtensionPropertyInfo(this, propertyType, propertyName)
);
configureAction?.Invoke(propertyInfo);
return this;
}
[NotNull]
public virtual ImmutableList<ObjectExtensionPropertyInfo> GetProperties()
{
return Properties.Values.ToImmutableList();
}
[CanBeNull]
public virtual ObjectExtensionPropertyInfo GetPropertyOrNull(
[NotNull] string propertyName)
{
Check.NotNullOrEmpty(propertyName, nameof(propertyName));
return Properties.GetOrDefault(propertyName);
}
}
}

66
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionManager.cs

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using JetBrains.Annotations;
using Volo.Abp.Data;
namespace Volo.Abp.ObjectExtending
{
public class ObjectExtensionManager
{
public static ObjectExtensionManager Instance { get; set; } = new ObjectExtensionManager();
protected Dictionary<Type, ObjectExtensionInfo> ObjectsExtensions { get; }
protected internal ObjectExtensionManager()
{
ObjectsExtensions = new Dictionary<Type, ObjectExtensionInfo>();
}
[NotNull]
public virtual ObjectExtensionManager AddOrUpdate<TObject>(
[CanBeNull] Action<ObjectExtensionInfo> configureAction = null)
where TObject : IHasExtraProperties
{
return AddOrUpdate(typeof(TObject), configureAction);
}
[NotNull]
public virtual ObjectExtensionManager AddOrUpdate(
[NotNull] Type type,
[CanBeNull] Action<ObjectExtensionInfo> configureAction = null)
{
Check.AssignableTo<IHasExtraProperties>(type, nameof(type));
var extensionInfo = ObjectsExtensions.GetOrAdd(
type,
() => new ObjectExtensionInfo(type)
);
configureAction?.Invoke(extensionInfo);
return this;
}
[CanBeNull]
public virtual ObjectExtensionInfo GetOrNull<TObject>()
where TObject : IHasExtraProperties
{
return GetOrNull(typeof(TObject));
}
[CanBeNull]
public virtual ObjectExtensionInfo GetOrNull([NotNull] Type type)
{
Check.AssignableTo<IHasExtraProperties>(type, nameof(type));
return ObjectsExtensions.GetOrDefault(type);
}
[NotNull]
public virtual ImmutableList<ObjectExtensionInfo> GetExtendedObjects()
{
return ObjectsExtensions.Values.ToImmutableList();
}
}
}

44
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionManagerExtensions.cs

@ -0,0 +1,44 @@
using System;
using JetBrains.Annotations;
using Volo.Abp.Data;
namespace Volo.Abp.ObjectExtending
{
public static class ObjectExtensionManagerExtensions
{
public static ObjectExtensionManager AddOrUpdateProperty<TObject, TProperty>(
[NotNull] this ObjectExtensionManager objectExtensionManager,
[NotNull] string propertyName,
[CanBeNull] Action<ObjectExtensionPropertyInfo> configureAction = null)
where TObject : IHasExtraProperties
{
return objectExtensionManager.AddOrUpdateProperty(
typeof(TObject),
typeof(TProperty),
propertyName,
configureAction
);
}
public static ObjectExtensionManager AddOrUpdateProperty(
[NotNull] this ObjectExtensionManager objectExtensionManager,
[NotNull] Type objectType,
[NotNull] Type propertyType,
[NotNull] string propertyName,
[CanBeNull] Action<ObjectExtensionPropertyInfo> configureAction = null)
{
Check.NotNull(objectExtensionManager, nameof(objectExtensionManager));
return objectExtensionManager.AddOrUpdate(
objectType,
options =>
{
options.AddOrUpdateProperty(
propertyType,
propertyName,
configureAction
);
});
}
}
}

33
framework/src/Volo.Abp.ObjectExtending/Volo/Abp/ObjectExtending/ObjectExtensionPropertyInfo.cs

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Volo.Abp.ObjectExtending
{
public class ObjectExtensionPropertyInfo
{
[NotNull]
public ObjectExtensionInfo ObjectExtension { get; }
[NotNull]
public string Name { get; }
[NotNull]
public Type Type { get; }
[NotNull]
public Dictionary<object, object> Configuration { get; }
public ObjectExtensionPropertyInfo(
[NotNull] ObjectExtensionInfo objectExtension,
[NotNull] Type type,
[NotNull] string name)
{
ObjectExtension = Check.NotNull(objectExtension, nameof(objectExtension));
Type = Check.NotNull(type, nameof(type));
Name = Check.NotNull(name, nameof(name));
Configuration = new Dictionary<object, object>();
}
}
}

41
framework/test/Volo.Abp.AutoMapper.Tests/AutoMapper/AbpAutoMapperExtensibleDtoExtensions_Tests.cs

@ -0,0 +1,41 @@
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.AutoMapper;
using Volo.Abp.Data;
using Volo.Abp.ObjectExtending.TestObjects;
using Volo.Abp.Testing;
using Xunit;
namespace AutoMapper
{
public class AbpAutoMapperExtensibleDtoExtensions_Tests : AbpIntegratedTest<AutoMapperTestModule>
{
private readonly Volo.Abp.ObjectMapping.IObjectMapper _objectMapper;
public AbpAutoMapperExtensibleDtoExtensions_Tests()
{
_objectMapper = ServiceProvider.GetRequiredService<Volo.Abp.ObjectMapping.IObjectMapper>();
}
[Fact]
public void MapExtraPropertiesTo_Should_Only_Map_Defined_Properties_By_Default()
{
var person = new ExtensibleTestPerson()
.SetProperty("Name", "John")
.SetProperty("Age", 42)
.SetProperty("ChildCount", 2)
.SetProperty("Sex", "male");
var personDto = new ExtensibleTestPersonDto()
.SetProperty("ExistingDtoProperty", "existing-value");
_objectMapper.Map(person, personDto);
personDto.GetProperty<string>("Name").ShouldBe("John"); //Defined in both classes
personDto.HasProperty("Age").ShouldBeFalse(); //Not defined on the destination
personDto.HasProperty("ChildCount").ShouldBeFalse(); //Not defined in the source
personDto.HasProperty("Sex").ShouldBeFalse(); //Not defined in both classes
personDto.GetProperty<string>("ExistingDtoProperty").ShouldBe("existing-value"); //Should not clear existing values
}
}
}

2
framework/test/Volo.Abp.AutoMapper.Tests/Volo.Abp.AutoMapper.Tests.csproj

@ -11,7 +11,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\Volo.Abp.AutoMapper\Volo.Abp.AutoMapper.csproj" /> <ProjectReference Include="..\..\src\Volo.Abp.AutoMapper\Volo.Abp.AutoMapper.csproj" />
<ProjectReference Include="..\AbpTestBase\AbpTestBase.csproj" /> <ProjectReference Include="..\Volo.Abp.ObjectExtending.Tests\Volo.Abp.ObjectExtending.Tests.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
</ItemGroup> </ItemGroup>

9
framework/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/AutoMapperTestModule.cs

@ -1,9 +1,12 @@
using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity;
using Volo.Abp.Modularity; using Volo.Abp.ObjectExtending;
namespace Volo.Abp.AutoMapper namespace Volo.Abp.AutoMapper
{ {
[DependsOn(typeof(AbpAutoMapperModule))] [DependsOn(
typeof(AbpAutoMapperModule),
typeof(AbpObjectExtendingTestModule)
)]
public class AutoMapperTestModule : AbpModule public class AutoMapperTestModule : AbpModule
{ {
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)

4
framework/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyMapProfile.cs

@ -1,4 +1,5 @@
using AutoMapper; using AutoMapper;
using Volo.Abp.ObjectExtending.TestObjects;
namespace Volo.Abp.AutoMapper.SampleClasses namespace Volo.Abp.AutoMapper.SampleClasses
{ {
@ -7,6 +8,9 @@ namespace Volo.Abp.AutoMapper.SampleClasses
public MyMapProfile() public MyMapProfile()
{ {
CreateMap<MyEntity, MyEntityDto>().ReverseMap(); CreateMap<MyEntity, MyEntityDto>().ReverseMap();
CreateMap<ExtensibleTestPerson, ExtensibleTestPersonDto>()
.MapExtraProperties();
} }
} }
} }

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

@ -1,4 +1,4 @@
using Volo.Abp.EntityFrameworkCore.Extensions; using Volo.Abp.ObjectExtending;
using Volo.Abp.TestApp.Domain; using Volo.Abp.TestApp.Domain;
using Volo.Abp.Threading; using Volo.Abp.Threading;
@ -12,10 +12,11 @@ namespace Volo.Abp.EntityFrameworkCore.Domain
{ {
OneTimeRunner.Run(() => OneTimeRunner.Run(() =>
{ {
EntityExtensionManager.AddProperty<City, string>( ObjectExtensionManager.Instance
"PhoneCode", .MapEfCoreProperty<City, string>(
p => p.HasMaxLength(8) "PhoneCode",
); p => p.HasMaxLength(8)
);
}); });
} }
} }

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

@ -1,5 +1,4 @@
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;
@ -37,8 +36,6 @@ 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,6 +1,5 @@
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;
@ -44,8 +43,6 @@ 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);

16
framework/test/Volo.Abp.ObjectExtending.Tests/Volo.Abp.ObjectExtending.Tests.csproj

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\common.test.props" />
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AbpTestBase\AbpTestBase.csproj" />
<ProjectReference Include="..\..\src\Volo.Abp.ObjectExtending\Volo.Abp.ObjectExtending.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
</ItemGroup>
</Project>

9
framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/AbpObjectExtendingTestBase.cs

@ -0,0 +1,9 @@
using Volo.Abp.Testing;
namespace Volo.Abp.ObjectExtending
{
public abstract class AbpObjectExtendingTestBase : AbpIntegratedTest<AbpObjectExtendingTestModule>
{
}
}

27
framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/AbpObjectExtendingTestModule.cs

@ -0,0 +1,27 @@
using Volo.Abp.Modularity;
using Volo.Abp.ObjectExtending.TestObjects;
using Volo.Abp.Threading;
namespace Volo.Abp.ObjectExtending
{
[DependsOn(
typeof(AbpObjectExtendingModule),
typeof(AbpTestBaseModule)
)]
public class AbpObjectExtendingTestModule : AbpModule
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public override void PreConfigureServices(ServiceConfigurationContext context)
{
OneTimeRunner.Run(() =>
{
ObjectExtensionManager.Instance
.AddOrUpdateProperty<ExtensibleTestPerson, string>("Name")
.AddOrUpdateProperty<ExtensibleTestPerson, int>("Age")
.AddOrUpdateProperty<ExtensibleTestPersonDto, string>("Name")
.AddOrUpdateProperty<ExtensibleTestPersonDto, int>("ChildCount");
});
}
}
}

73
framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/HasExtraPropertiesObjectExtendingExtensions_Tests.cs

@ -0,0 +1,73 @@
using Shouldly;
using Volo.Abp.Data;
using Volo.Abp.ObjectExtending.TestObjects;
using Xunit;
namespace Volo.Abp.ObjectExtending
{
public class HasExtraPropertiesObjectExtendingExtensions_Tests : AbpObjectExtendingTestBase
{
private readonly ExtensibleTestPerson _person;
private readonly ExtensibleTestPersonDto _personDto;
public HasExtraPropertiesObjectExtendingExtensions_Tests()
{
_person = new ExtensibleTestPerson()
.SetProperty("Name", "John")
.SetProperty("Age", 42)
.SetProperty("ChildCount", 2)
.SetProperty("Sex", "male");
_personDto = new ExtensibleTestPersonDto()
.SetProperty("ExistingDtoProperty", "existing-value");
}
[Fact]
public void MapExtraPropertiesTo_Should_Only_Map_Defined_Properties_By_Default()
{
_person.MapExtraPropertiesTo(_personDto);
_personDto.GetProperty<string>("Name").ShouldBe("John"); //Defined in both classes
_personDto.HasProperty("Age").ShouldBeFalse(); //Not defined on the destination
_personDto.HasProperty("ChildCount").ShouldBeFalse(); //Not defined in the source
_personDto.HasProperty("Sex").ShouldBeFalse(); //Not defined in both classes
_personDto.GetProperty<string>("ExistingDtoProperty").ShouldBe("existing-value"); //Should not clear existing values
}
[Fact]
public void MapExtraPropertiesTo_Should_Only_Map_Source_Defined_Properties_If_Requested()
{
_person.MapExtraPropertiesTo(_personDto, MappingPropertyDefinitionChecks.Source);
_personDto.GetProperty<string>("Name").ShouldBe("John"); //Defined in both classes
_personDto.GetProperty<int>("Age").ShouldBe(42); //Defined in source
_personDto.HasProperty("ChildCount").ShouldBeFalse(); //Not defined in the source
_personDto.HasProperty("Sex").ShouldBeFalse(); //Not defined in both classes
_personDto.GetProperty<string>("ExistingDtoProperty").ShouldBe("existing-value"); //Should not clear existing values
}
[Fact]
public void MapExtraPropertiesTo_Should_Only_Map_Destination_Defined_Properties_If_Requested()
{
_person.MapExtraPropertiesTo(_personDto, MappingPropertyDefinitionChecks.Destination);
_personDto.GetProperty<string>("Name").ShouldBe("John"); //Defined in both classes
_personDto.GetProperty<int>("ChildCount").ShouldBe(2); //Defined in destination
_personDto.HasProperty("Age").ShouldBeFalse(); //Not defined in destination
_personDto.HasProperty("Sex").ShouldBeFalse(); //Not defined in both classes
_personDto.GetProperty<string>("ExistingDtoProperty").ShouldBe("existing-value"); //Should not clear existing values
}
[Fact]
public void MapExtraPropertiesTo_Should_Copy_all_With_No_Property_Definition_Check()
{
_person.MapExtraPropertiesTo(_personDto, MappingPropertyDefinitionChecks.None);
_personDto.GetProperty<string>("Name").ShouldBe("John");
_personDto.GetProperty<int>("Age").ShouldBe(42);
_personDto.GetProperty<int>("ChildCount").ShouldBe(2);
_personDto.GetProperty<string>("Sex").ShouldBe("male");
_personDto.GetProperty<string>("ExistingDtoProperty").ShouldBe("existing-value"); //Should not clear existing values
}
}
}

63
framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/ObjectExtensionManager_Tests.cs

@ -0,0 +1,63 @@
using System.Linq;
using Shouldly;
using Xunit;
namespace Volo.Abp.ObjectExtending
{
public class ObjectExtensionManager_Tests
{
private readonly ObjectExtensionManager _objectExtensionManager;
public ObjectExtensionManager_Tests()
{
_objectExtensionManager = new ObjectExtensionManager();
}
[Fact]
public void Should_Not_Add_Same_Property_Multiple_Times()
{
_objectExtensionManager
.AddOrUpdateProperty<MyExtensibleObject, string>("TestProp")
.AddOrUpdateProperty<MyExtensibleObject, string>("TestProp");
var objectExtension = _objectExtensionManager.GetOrNull<MyExtensibleObject>();
objectExtension.ShouldNotBeNull();
var properties = objectExtension.GetProperties();
properties.Count.ShouldBe(1);
properties.FirstOrDefault(p => p.Name == "TestProp").ShouldNotBeNull();
}
[Fact]
public void Should_Update_Property_Configuration()
{
_objectExtensionManager
.AddOrUpdateProperty<MyExtensibleObject, string>(
"TestProp",
options =>
{
options.Configuration["TestConfig1"] = "TestConfig1-Value";
}
).AddOrUpdateProperty<MyExtensibleObject, string>(
"TestProp",
options =>
{
options.Configuration["TestConfig2"] = "TestConfig2-Value";
}
);
var objectExtension = _objectExtensionManager.GetOrNull<MyExtensibleObject>();
objectExtension.ShouldNotBeNull();
var property = objectExtension.GetPropertyOrNull("TestProp");
property.ShouldNotBeNull();
property.Configuration["TestConfig1"].ShouldBe("TestConfig1-Value");
property.Configuration["TestConfig2"].ShouldBe("TestConfig2-Value");
}
private class MyExtensibleObject : ExtensibleObject
{
}
}
}

7
framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/TestObjects/ExtensibleTestPerson.cs

@ -0,0 +1,7 @@
namespace Volo.Abp.ObjectExtending.TestObjects
{
public class ExtensibleTestPerson : ExtensibleObject
{
}
}

7
framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/TestObjects/ExtensibleTestPersonDto.cs

@ -0,0 +1,7 @@
namespace Volo.Abp.ObjectExtending.TestObjects
{
public class ExtensibleTestPersonDto : ExtensibleObject
{
}
}

2
modules/blogging/src/Volo.Blogging.Application/Volo/Blogging/Posts/PostAppService.cs

@ -202,7 +202,7 @@ namespace Volo.Blogging.Posts
private async Task RemoveOldTags(ICollection<string> newTags, Post post) private async Task RemoveOldTags(ICollection<string> newTags, Post post)
{ {
foreach (var oldTag in post.Tags) foreach (var oldTag in post.Tags.ToList())
{ {
var tag = await _tagRepository.GetAsync(oldTag.TagId); var tag = await _tagRepository.GetAsync(oldTag.TagId);

12
modules/docs/app/VoloDocs.Web/Controllers/HomeController.cs

@ -1,12 +0,0 @@
using Volo.Abp.AspNetCore.Mvc;
namespace VoloDocs.Web.Controllers
{
public class HomeController : AbpController
{
public void Index()
{
}
}
}

18
modules/docs/app/VoloDocs.Web/Pages/Index.cshtml

@ -3,3 +3,21 @@
@{ @{
} }
@if (!Model.Projects.Any())
{
<abp-alert alert-type="Warning">
<strong>No projects found!</strong><br />
See <a href=" https://docs.abp.io/en/abp/latest/Modules/Docs">documentation</a> to see how you can create a new one.
</abp-alert>
}
else
{
<h1>Projects</h1>
<abp-list-group class="mt-5">
@foreach (var project in Model.Projects)
{
<abp-list-group-item href="@Model.GetUrlForProject(project)">@project.Name</abp-list-group-item>
}
</abp-list-group>
}

42
modules/docs/app/VoloDocs.Web/Pages/Index.cshtml.cs

@ -1,29 +1,59 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Volo.Docs; using Volo.Docs;
using Volo.Docs.Projects;
namespace VoloDocs.Web.Pages namespace VoloDocs.Web.Pages
{ {
public class IndexModel : PageModel public class IndexModel : PageModel
{ {
public IReadOnlyList<ProjectDto> Projects { get; set; }
private readonly DocsUiOptions _urlUiOptions; private readonly DocsUiOptions _urlUiOptions;
public IndexModel(IOptions<DocsUiOptions> urlOptions) private readonly IProjectAppService _projectAppService;
public IndexModel(IOptions<DocsUiOptions> urlOptions, IProjectAppService projectAppService)
{ {
_projectAppService = projectAppService;
_urlUiOptions = urlOptions.Value; _urlUiOptions = urlOptions.Value;
} }
public IActionResult OnGet() public async Task<IActionResult> OnGetAsync()
{ {
//TODO: Create HomeController & Index instead of Page. Otherwise, we have an empty Index.cshtml file. var projects = await _projectAppService.GetListAsync();
if (!_urlUiOptions.RoutePrefix.IsNullOrWhiteSpace())
if (projects.Items.Count == 1)
{ {
return Redirect("." + _urlUiOptions.RoutePrefix); return await RedirectToProjectAsync(projects.Items.First());
}
else if (projects.Items.Count > 1)
{
Projects = projects.Items;
} }
return Page(); return Page();
} }
private async Task<IActionResult> RedirectToProjectAsync(ProjectDto project, string language = "en", string version = null)
{
var path = GetUrlForProject(project, language, version);
return await Task.FromResult(Redirect(path));
}
//Eg: "/en/abp/latest"
public string GetUrlForProject(ProjectDto project, string language = "en", string version = null)
{
return "." +
_urlUiOptions.RoutePrefix.EnsureStartsWith('/').EnsureEndsWith('/') +
language.EnsureEndsWith('/') +
project.ShortName.EnsureEndsWith('/') +
(version ?? DocsAppConsts.Latest);
}
} }
} }

5
modules/docs/app/VoloDocs.Web/appsettings.json

@ -3,5 +3,10 @@
"LogoUrl": "/assets/images/Logo.png", "LogoUrl": "/assets/images/Logo.png",
"ElasticSearch": { "ElasticSearch": {
"Url": "http://localhost:9200" "Url": "http://localhost:9200"
},
"Volo.Docs": {
"DocumentCacheTimeoutInterval": "24:00:00",
"DocumentResource.AbsoluteExpirationRelativeToNow": "24:00:00",
"DocumentResource.SlidingExpiration": "02:00:00"
} }
} }

2796
modules/docs/app/VoloDocs.Web/package-lock.json

File diff suppressed because it is too large

2
modules/docs/app/VoloDocs.Web/package.json

@ -6,4 +6,4 @@
"@abp/aspnetcore.mvc.ui.theme.basic": "^1.0.2", "@abp/aspnetcore.mvc.ui.theme.basic": "^1.0.2",
"@abp/docs": "^1.0.2" "@abp/docs": "^1.0.2"
} }
} }

12
modules/docs/src/Volo.Docs.Admin.Application/Volo/Docs/Admin/Documents/DocumentAdminAppService.cs

@ -4,11 +4,13 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json; using Newtonsoft.Json;
using Volo.Abp;
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.Caching; using Volo.Abp.Caching;
using Volo.Docs.Documents; using Volo.Docs.Documents;
using Volo.Docs.Documents.FullSearch.Elastic; using Volo.Docs.Documents.FullSearch.Elastic;
using Volo.Docs.Projects; using Volo.Docs.Projects;
using Volo.Extensions;
namespace Volo.Docs.Admin.Documents namespace Volo.Docs.Admin.Documents
{ {
@ -38,15 +40,19 @@ namespace Volo.Docs.Admin.Documents
{ {
var project = await _projectRepository.GetAsync(input.ProjectId); var project = await _projectRepository.GetAsync(input.ProjectId);
var navigationFile = await GetDocumentAsync( var navigationDocument = await GetDocumentAsync(
project, project,
project.NavigationDocumentName, project.NavigationDocumentName,
input.LanguageCode, input.LanguageCode,
input.Version input.Version
); );
var nav = JsonConvert.DeserializeObject<NavigationNode>(navigationFile.Content); if (!JsonConvertExtensions.TryDeserializeObject<NavigationNode>(navigationDocument.Content, out var navigation))
var leafs = nav.Items.GetAllNodes(x => x.Items) {
throw new UserFriendlyException($"Cannot validate navigation file '{project.NavigationDocumentName}' for the project {project.Name}.");
}
var leafs = navigation.Items.GetAllNodes(x => x.Items)
.Where(x => x.IsLeaf && !x.Path.IsNullOrWhiteSpace()) .Where(x => x.IsLeaf && !x.Path.IsNullOrWhiteSpace())
.ToList(); .ToList();

128
modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/DocumentAppService.cs

@ -3,13 +3,17 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Nest;
using Newtonsoft.Json; using Newtonsoft.Json;
using Volo.Abp;
using Volo.Abp.Caching; using Volo.Abp.Caching;
using Volo.Docs.Documents.FullSearch.Elastic; using Volo.Docs.Documents.FullSearch.Elastic;
using Volo.Docs.Projects; using Volo.Docs.Projects;
using Volo.Extensions;
namespace Volo.Docs.Documents namespace Volo.Docs.Documents
{ {
@ -24,6 +28,10 @@ namespace Volo.Docs.Documents
protected IHostEnvironment HostEnvironment { get; } protected IHostEnvironment HostEnvironment { get; }
private readonly IDocumentFullSearch _documentFullSearch; private readonly IDocumentFullSearch _documentFullSearch;
private readonly DocsElasticSearchOptions _docsElasticSearchOptions; private readonly DocsElasticSearchOptions _docsElasticSearchOptions;
private readonly IConfiguration _configuration;
private readonly TimeSpan _cacheTimeout;
private readonly TimeSpan _documentResourceAbsoluteExpiration;
private readonly TimeSpan _documentResourceSlidingExpiration;
public DocumentAppService( public DocumentAppService(
IProjectRepository projectRepository, IProjectRepository projectRepository,
@ -32,9 +40,10 @@ namespace Volo.Docs.Documents
IDistributedCache<LanguageConfig> languageCache, IDistributedCache<LanguageConfig> languageCache,
IDistributedCache<DocumentResourceDto> resourceCache, IDistributedCache<DocumentResourceDto> resourceCache,
IDistributedCache<DocumentUpdateInfo> documentUpdateCache, IDistributedCache<DocumentUpdateInfo> documentUpdateCache,
IHostEnvironment hostEnvironment, IHostEnvironment hostEnvironment,
IDocumentFullSearch documentFullSearch, IDocumentFullSearch documentFullSearch,
IOptions<DocsElasticSearchOptions> docsElasticSearchOptions) IOptions<DocsElasticSearchOptions> docsElasticSearchOptions,
IConfiguration configuration)
{ {
_projectRepository = projectRepository; _projectRepository = projectRepository;
_documentRepository = documentRepository; _documentRepository = documentRepository;
@ -44,7 +53,11 @@ namespace Volo.Docs.Documents
DocumentUpdateCache = documentUpdateCache; DocumentUpdateCache = documentUpdateCache;
HostEnvironment = hostEnvironment; HostEnvironment = hostEnvironment;
_documentFullSearch = documentFullSearch; _documentFullSearch = documentFullSearch;
_configuration = configuration;
_docsElasticSearchOptions = docsElasticSearchOptions.Value; _docsElasticSearchOptions = docsElasticSearchOptions.Value;
_cacheTimeout = GetCacheTimeout();
_documentResourceAbsoluteExpiration = GetDocumentResourceAbsoluteExpirationTimeout();
_documentResourceSlidingExpiration = GetDocumentResourceSlidingExpirationTimeout();
} }
public virtual async Task<DocumentWithDetailsDto> GetAsync(GetDocumentInput input) public virtual async Task<DocumentWithDetailsDto> GetAsync(GetDocumentInput input)
@ -82,7 +95,10 @@ namespace Volo.Docs.Documents
input.Version input.Version
); );
var navigationNode = JsonConvert.DeserializeObject<NavigationNode>(navigationDocument.Content); if (!JsonConvertExtensions.TryDeserializeObject<NavigationNode>(navigationDocument.Content, out var navigationNode))
{
throw new UserFriendlyException($"Cannot validate navigation file '{project.NavigationDocumentName}' for the project {project.Name}.");
}
var leafs = navigationNode.Items.GetAllNodes(x => x.Items) var leafs = navigationNode.Items.GetAllNodes(x => x.Items)
.Where(x => !x.Path.IsNullOrWhiteSpace()) .Where(x => !x.Path.IsNullOrWhiteSpace())
@ -127,9 +143,8 @@ namespace Volo.Docs.Documents
GetResourceAsync, GetResourceAsync,
() => new DistributedCacheEntryOptions () => new DistributedCacheEntryOptions
{ {
//TODO: Configurable? AbsoluteExpirationRelativeToNow = _documentResourceAbsoluteExpiration,
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6), SlidingExpiration = _documentResourceSlidingExpiration
SlidingExpiration = TimeSpan.FromMinutes(30)
} }
); );
} }
@ -173,11 +188,16 @@ namespace Volo.Docs.Documents
input.Version input.Version
); );
return JsonConvert.DeserializeObject<DocumentParametersDto>(document.Content); if (!JsonConvertExtensions.TryDeserializeObject<DocumentParametersDto>(document.Content, out var documentParameters))
{
throw new UserFriendlyException($"Cannot validate document parameters file '{project.ParametersDocumentName}' for the project {project.Name}.");
}
return documentParameters;
} }
catch (DocumentNotFoundException) catch (DocumentNotFoundException)
{ {
Logger.LogWarning($"Parameter file ({project.ParametersDocumentName}) not found."); Logger.LogWarning($"Parameter file ({project.ParametersDocumentName}) not found!");
return new DocumentParametersDto(); return new DocumentParametersDto();
} }
} }
@ -190,48 +210,23 @@ namespace Volo.Docs.Documents
{ {
version = string.IsNullOrWhiteSpace(version) ? project.LatestVersionBranchName : version; version = string.IsNullOrWhiteSpace(version) ? project.LatestVersionBranchName : version;
async Task<DocumentWithDetailsDto> GetDocumentAsync(Document oldDocument = null)
{
Logger.LogInformation($"Not found in the cache. Requesting {documentName} from the source...");
var source = _documentStoreFactory.Create(project.DocumentStoreType);
var sourceDocument = await source.GetDocumentAsync(project, documentName, languageCode, version, oldDocument?.LastSignificantUpdateTime);
await _documentRepository.DeleteAsync(project.Id, sourceDocument.Name, sourceDocument.LanguageCode, sourceDocument.Version);
await _documentRepository.InsertAsync(sourceDocument, true);
Logger.LogInformation($"Document retrieved: {documentName}");
var cacheKey = $"DocumentUpdateInfo{sourceDocument.ProjectId}#{sourceDocument.Name}#{sourceDocument.LanguageCode}#{sourceDocument.Version}";
await DocumentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo
{
Name = sourceDocument.Name,
CreationTime = sourceDocument.CreationTime,
LastUpdatedTime = sourceDocument.LastUpdatedTime,
LastSignificantUpdateTime = sourceDocument.LastSignificantUpdateTime
});
return CreateDocumentWithDetailsDto(project, sourceDocument);
}
if (HostEnvironment.IsDevelopment()) if (HostEnvironment.IsDevelopment())
{ {
return await GetDocumentAsync(); return await GetDocumentAsync(documentName, project, languageCode, version);
} }
var document = await _documentRepository.FindAsync(project.Id, documentName, languageCode, version); var document = await _documentRepository.FindAsync(project.Id, documentName, languageCode, version);
if (document == null) if (document == null)
{ {
return await GetDocumentAsync(); return await GetDocumentAsync(documentName, project, languageCode, version);
} }
//Only the latest version (dev) of the document needs to update the cache. //Only the latest version (dev) of the document needs to update the cache.
if (!project.LatestVersionBranchName.IsNullOrWhiteSpace() && if (!project.LatestVersionBranchName.IsNullOrWhiteSpace() &&
document.Version == project.LatestVersionBranchName && document.Version == project.LatestVersionBranchName &&
//TODO: Configurable cache time? document.LastCachedTime + _cacheTimeout < DateTime.Now)
document.LastCachedTime + TimeSpan.FromHours(2) < DateTime.Now)
{ {
return await GetDocumentAsync(document); return await GetDocumentAsync(documentName, project, languageCode, version, document);
} }
var cacheKey = $"DocumentUpdateInfo{document.ProjectId}#{document.Name}#{document.LanguageCode}#{document.Version}"; var cacheKey = $"DocumentUpdateInfo{document.ProjectId}#{document.Name}#{document.LanguageCode}#{document.Version}";
@ -253,5 +248,62 @@ namespace Volo.Docs.Documents
documentDto.Contributors = ObjectMapper.Map<List<DocumentContributor>, List<DocumentContributorDto>>(document.Contributors); documentDto.Contributors = ObjectMapper.Map<List<DocumentContributor>, List<DocumentContributorDto>>(document.Contributors);
return documentDto; return documentDto;
} }
private async Task<DocumentWithDetailsDto> GetDocumentAsync(string documentName, Project project, string languageCode, string version, Document oldDocument = null)
{
Logger.LogInformation($"Not found in the cache. Requesting {documentName} from the source...");
var source = _documentStoreFactory.Create(project.DocumentStoreType);
var sourceDocument = await source.GetDocumentAsync(project, documentName, languageCode, version, oldDocument?.LastSignificantUpdateTime);
await _documentRepository.DeleteAsync(project.Id, sourceDocument.Name, sourceDocument.LanguageCode, sourceDocument.Version);
await _documentRepository.InsertAsync(sourceDocument, true);
Logger.LogInformation($"Document retrieved: {documentName}");
var cacheKey = $"DocumentUpdateInfo{sourceDocument.ProjectId}#{sourceDocument.Name}#{sourceDocument.LanguageCode}#{sourceDocument.Version}";
await DocumentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo
{
Name = sourceDocument.Name,
CreationTime = sourceDocument.CreationTime,
LastUpdatedTime = sourceDocument.LastUpdatedTime,
LastSignificantUpdateTime = sourceDocument.LastSignificantUpdateTime
});
return CreateDocumentWithDetailsDto(project, sourceDocument);
}
private TimeSpan GetCacheTimeout()
{
var value = _configuration["Volo.Docs:DocumentCacheTimeoutInterval"];
if (value.IsNullOrEmpty())
{
return TimeSpan.FromHours(6);
}
return TimeSpan.Parse(value);
}
private TimeSpan GetDocumentResourceAbsoluteExpirationTimeout()
{
var value = _configuration["Volo.Docs:DocumentResource.AbsoluteExpirationRelativeToNow"];
if (value.IsNullOrEmpty())
{
return TimeSpan.FromHours(6);
}
return TimeSpan.Parse(value);
}
private TimeSpan GetDocumentResourceSlidingExpirationTimeout()
{
var value = _configuration["Volo.Docs:DocumentResource.SlidingExpiration"];
if (value.IsNullOrEmpty())
{
return TimeSpan.FromMinutes(30);
}
return TimeSpan.Parse(value);
}
} }
} }

7
modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainConsts.cs

@ -0,0 +1,7 @@
namespace Volo.Docs
{
public class DocsDomainConsts
{
public static string LanguageConfigFileName = "docs-langs.json";
}
}

15
modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentSource.cs

@ -4,11 +4,13 @@ using System.IO;
using System.Security; using System.Security;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Volo.Abp;
using Volo.Abp.Domain.Services; using Volo.Abp.Domain.Services;
using Volo.Abp.IO; using Volo.Abp.IO;
using Volo.Docs.Documents; using Volo.Docs.Documents;
using Volo.Docs.FileSystem.Projects; using Volo.Docs.FileSystem.Projects;
using Volo.Docs.Projects; using Volo.Docs.Projects;
using Volo.Extensions;
namespace Volo.Docs.FileSystem.Documents namespace Volo.Docs.FileSystem.Documents
{ {
@ -22,7 +24,7 @@ namespace Volo.Docs.FileSystem.Documents
var path = Path.Combine(projectFolder, languageCode, documentName); var path = Path.Combine(projectFolder, languageCode, documentName);
CheckDirectorySecurity(projectFolder, path); CheckDirectorySecurity(projectFolder, path);
var content = await FileHelper.ReadAllTextAsync(path); var content = await FileHelper.ReadAllTextAsync(path);
var localDirectory = ""; var localDirectory = "";
@ -55,10 +57,15 @@ namespace Volo.Docs.FileSystem.Documents
public async Task<LanguageConfig> GetLanguageListAsync(Project project, string version) public async Task<LanguageConfig> GetLanguageListAsync(Project project, string version)
{ {
var path = Path.Combine(project.GetFileSystemPath(), "docs-langs.json"); var path = Path.Combine(project.GetFileSystemPath(), DocsDomainConsts.LanguageConfigFileName);
var configAsJson = await FileHelper.ReadAllTextAsync(path); var configJsonContent = await FileHelper.ReadAllTextAsync(path);
if (!JsonConvertExtensions.TryDeserializeObject<LanguageConfig>(configJsonContent, out var languageConfig))
{
throw new UserFriendlyException($"Cannot validate language config file '{DocsDomainConsts.LanguageConfigFileName}' for the project {project.Name}.");
}
return JsonConvert.DeserializeObject<LanguageConfig>(configAsJson); return languageConfig;
} }
public async Task<DocumentResource> GetResource(Project project, string resourceName, string languageCode, string version) public async Task<DocumentResource> GetResource(Project project, string resourceName, string languageCode, string version)

29
modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentSource.cs

@ -3,13 +3,13 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Volo.Abp.Domain.Services; using Volo.Abp.Domain.Services;
using Volo.Docs.Documents; using Volo.Docs.Documents;
using Volo.Docs.GitHub.Projects; using Volo.Docs.GitHub.Projects;
using Volo.Docs.Projects; using Volo.Docs.Projects;
using Newtonsoft.Json.Linq;
using Octokit; using Octokit;
using Volo.Abp;
using Volo.Extensions;
using Project = Volo.Docs.Projects.Project; using Project = Volo.Docs.Projects.Project;
namespace Volo.Docs.GitHub.Documents namespace Volo.Docs.GitHub.Documents
@ -55,11 +55,11 @@ namespace Volo.Docs.GitHub.Documents
var lastSignificantUpdateTime = !isNavigationDocument && !isParameterDocument && version == project.LatestVersionBranchName ? var lastSignificantUpdateTime = !isNavigationDocument && !isParameterDocument && version == project.LatestVersionBranchName ?
await GetLastSignificantUpdateTime( await GetLastSignificantUpdateTime(
fileCommits, fileCommits,
project, project,
project.GetGitHubInnerUrl(languageCode, documentName), project.GetGitHubInnerUrl(languageCode, documentName),
lastKnownSignificantUpdateTime, lastKnownSignificantUpdateTime,
documentCreationTime documentCreationTime
) ?? lastKnownSignificantUpdateTime ) ?? lastKnownSignificantUpdateTime
: null; : null;
var document = new Document(GuidGenerator.Create(), var document = new Document(GuidGenerator.Create(),
@ -179,11 +179,16 @@ namespace Volo.Docs.GitHub.Documents
var rootUrl = project.GetGitHubUrl(version); var rootUrl = project.GetGitHubUrl(version);
var userAgent = project.GetGithubUserAgentOrNull(); var userAgent = project.GetGithubUserAgentOrNull();
var url = CalculateRawRootUrl(rootUrl) + "docs-langs.json"; var url = CalculateRawRootUrl(rootUrl) + DocsDomainConsts.LanguageConfigFileName;
var configAsJson = await DownloadWebContentAsStringAsync(url, token, userAgent); var configAsJson = await DownloadWebContentAsStringAsync(url, token, userAgent);
return JsonConvert.DeserializeObject<LanguageConfig>(configAsJson); if (!JsonConvertExtensions.TryDeserializeObject<LanguageConfig>(configAsJson, out var languageConfig))
{
throw new UserFriendlyException($"Cannot validate language config file '{DocsDomainConsts.LanguageConfigFileName}' for the project {project.Name} - v{version}.");
}
return languageConfig;
} }
private async Task<IReadOnlyList<Release>> GetReleasesAsync(Project project) private async Task<IReadOnlyList<Release>> GetReleasesAsync(Project project)
@ -199,8 +204,14 @@ namespace Volo.Docs.GitHub.Documents
var url = project.GetGitHubUrl(); var url = project.GetGitHubUrl();
var ownerName = GetOwnerNameFromUrl(url); var ownerName = GetOwnerNameFromUrl(url);
var repositoryName = GetRepositoryNameFromUrl(url); var repositoryName = GetRepositoryNameFromUrl(url);
return await _githubRepositoryManager.GetFileCommitsAsync(ownerName, repositoryName,
version, filename, project.GetGitHubAccessTokenOrNull()); return await _githubRepositoryManager.GetFileCommitsAsync(
ownerName,
repositoryName,
version,
filename,
project.GetGitHubAccessTokenOrNull()
);
} }
protected virtual string GetOwnerNameFromUrl(string url) protected virtual string GetOwnerNameFromUrl(string url)
@ -212,7 +223,7 @@ namespace Volo.Docs.GitHub.Documents
} }
catch (Exception) catch (Exception)
{ {
throw new Exception($"Github url is not valid: {url}"); throw new Exception($"GitHub url is not valid: {url}");
} }
} }

69
modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubRepositoryManager.cs

@ -23,54 +23,25 @@ namespace Volo.Docs.GitHub.Documents
public async Task<string> GetFileRawStringContentAsync(string rawUrl, string token, string userAgent) public async Task<string> GetFileRawStringContentAsync(string rawUrl, string token, string userAgent)
{ {
var httpClient = _clientFactory.CreateClient(HttpClientName); using var httpClient = CreateHttpClient(token, userAgent);
if (!token.IsNullOrWhiteSpace())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", token);
}
if (!userAgent.IsNullOrWhiteSpace())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
}
return await httpClient.GetStringAsync(new Uri(rawUrl)); return await httpClient.GetStringAsync(new Uri(rawUrl));
} }
public async Task<byte[]> GetFileRawByteArrayContentAsync(string rawUrl, string token, string userAgent) public async Task<byte[]> GetFileRawByteArrayContentAsync(string rawUrl, string token, string userAgent)
{ {
var httpClient = _clientFactory.CreateClient(HttpClientName); using var httpClient = CreateHttpClient(token, userAgent);
if (!token.IsNullOrWhiteSpace())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", token);
}
if (!userAgent.IsNullOrWhiteSpace())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
}
return await httpClient.GetByteArrayAsync(new Uri(rawUrl)); return await httpClient.GetByteArrayAsync(new Uri(rawUrl));
} }
public async Task<IReadOnlyList<Release>> GetReleasesAsync(string name, string repositoryName, string token) public async Task<IReadOnlyList<Release>> GetReleasesAsync(string name, string repositoryName, string token)
{ {
var client = token.IsNullOrWhiteSpace() var client = GetGitHubClient(name, token);
? new GitHubClient(new ProductHeaderValue(name)) return await client.Repository.Release.GetAll(name, repositoryName);
: new GitHubClient(new ProductHeaderValue(name), new InMemoryCredentialStore(new Credentials(token)));
return (await client
.Repository
.Release
.GetAll(name, repositoryName)).ToList();
} }
public async Task<IReadOnlyList<GitHubCommit>> GetFileCommitsAsync(string name, string repositoryName, string version, string filename, string token) public async Task<IReadOnlyList<GitHubCommit>> GetFileCommitsAsync(string name, string repositoryName, string version, string filename, string token)
{ {
var client = token.IsNullOrWhiteSpace() var client = GetGitHubClient(name, token);
? new GitHubClient(new ProductHeaderValue(name))
: new GitHubClient(new ProductHeaderValue(name), new InMemoryCredentialStore(new Credentials(token)));
var repo = await client.Repository.Get(name, repositoryName); var repo = await client.Repository.Get(name, repositoryName);
var request = new CommitRequest { Path = filename, Sha = version }; var request = new CommitRequest { Path = filename, Sha = version };
return await client.Repository.Commit.GetAll(repo.Id, request); return await client.Repository.Commit.GetAll(repo.Id, request);
@ -78,12 +49,32 @@ namespace Volo.Docs.GitHub.Documents
public async Task<GitHubCommit> GetSingleCommitsAsync(string name, string repositoryName, string sha, string token) public async Task<GitHubCommit> GetSingleCommitsAsync(string name, string repositoryName, string sha, string token)
{ {
var client = token.IsNullOrWhiteSpace() var client = GetGitHubClient(name, token);
? new GitHubClient(new ProductHeaderValue(name))
: new GitHubClient(new ProductHeaderValue(name), new InMemoryCredentialStore(new Credentials(token)));
var repo = await client.Repository.Get(name, repositoryName); var repo = await client.Repository.Get(name, repositoryName);
return await client.Repository.Commit.Get(repo.Id, sha); return await client.Repository.Commit.Get(repo.Id, sha);
} }
private HttpClient CreateHttpClient(string token, string userAgent)
{
var httpClient = _clientFactory.CreateClient(HttpClientName);
if (!token.IsNullOrWhiteSpace())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", token);
}
if (!userAgent.IsNullOrWhiteSpace())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
}
return httpClient;
}
private static GitHubClient GetGitHubClient(string name, string token)
{
return token.IsNullOrWhiteSpace()
? new GitHubClient(new ProductHeaderValue(name))
: new GitHubClient(new ProductHeaderValue(name), new InMemoryCredentialStore(new Credentials(token)));
}
} }
} }

22
modules/docs/src/Volo.Docs.Domain/Volo/Extensions/NewtonsoftJsonExtensions.cs

@ -0,0 +1,22 @@
using System;
using Newtonsoft.Json;
namespace Volo.Extensions
{
public static class JsonConvertExtensions
{
public static bool TryDeserializeObject<T>(string jsonContent, out T result)
{
try
{
result = JsonConvert.DeserializeObject<T>(jsonContent);
return true;
}
catch
{
result = default;
return false;
}
}
}
}

109
modules/docs/src/Volo.Docs.Web/HtmlConverting/ScribanDocumentSectionRenderer.cs

@ -7,16 +7,17 @@ using Newtonsoft.Json;
using Scriban; using Scriban;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Volo.Docs.Documents; using Volo.Abp;
using Volo.Extensions;
namespace Volo.Docs.HtmlConverting namespace Volo.Docs.HtmlConverting
{ {
public class ScribanDocumentSectionRenderer : IDocumentSectionRenderer public class ScribanDocumentSectionRenderer : IDocumentSectionRenderer
{ {
private const string jsonOpener = "````json"; private const string JsonOpener = "````json";
private const string jsonCloser = "````"; private const string JsonCloser = "````";
private const string docs_param = "//[doc-params]"; private const string DocsParam = "//[doc-params]";
private const string docs_templates = "//[doc-template]"; private const string DocsTemplates = "//[doc-template]";
public ILogger<ScribanDocumentSectionRenderer> Logger { get; set; } public ILogger<ScribanDocumentSectionRenderer> Logger { get; set; }
@ -40,6 +41,7 @@ namespace Volo.Docs.HtmlConverting
} }
var result = await scribanTemplate.RenderAsync(parameters); var result = await scribanTemplate.RenderAsync(parameters);
return RemoveOptionsJson(result); return RemoveOptionsJson(result);
} }
@ -47,7 +49,7 @@ namespace Volo.Docs.HtmlConverting
{ {
try try
{ {
if (!document.Contains(jsonOpener) || !document.Contains(docs_param)) if (!document.Contains(JsonOpener) || !document.Contains(DocsParam))
{ {
return new Dictionary<string, List<string>>(); return new Dictionary<string, List<string>>();
} }
@ -59,9 +61,14 @@ namespace Volo.Docs.HtmlConverting
return new Dictionary<string, List<string>>(); return new Dictionary<string, List<string>>();
} }
var pureJson = insideJsonSection.Replace(docs_param, "").Trim(); var pureJson = insideJsonSection.Replace(DocsParam, "").Trim();
if (!JsonConvertExtensions.TryDeserializeObject<Dictionary<string, List<string>>>(pureJson, out var availableParameters))
{
throw new UserFriendlyException("ERROR-20200327: Cannot validate JSON content for `AvailableParameters`!");
}
return JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(pureJson); return await Task.FromResult(availableParameters);
} }
catch (Exception) catch (Exception)
{ {
@ -70,12 +77,13 @@ namespace Volo.Docs.HtmlConverting
} }
} }
private string RemoveOptionsJson(string document) private static string RemoveOptionsJson(string document)
{ {
var orgDocument = document; var orgDocument = document;
try try
{ {
if (!document.Contains(jsonOpener) || !document.Contains(docs_param)) if (!document.Contains(JsonOpener) || !document.Contains(DocsParam))
{ {
return orgDocument; return orgDocument;
} }
@ -88,8 +96,9 @@ namespace Volo.Docs.HtmlConverting
} }
return document.Remove( return document.Remove(
jsonBeginningIndex - jsonOpener.Length, (jsonEndingIndex + jsonCloser.Length) - (jsonBeginningIndex - jsonOpener.Length) jsonBeginningIndex - JsonOpener.Length,
); (jsonEndingIndex + JsonCloser.Length) - (jsonBeginningIndex - JsonOpener.Length)
);
} }
catch (Exception) catch (Exception)
{ {
@ -97,25 +106,25 @@ namespace Volo.Docs.HtmlConverting
} }
} }
private (int, int, string) GetJsonBeginEndIndexesAndPureJson(string document) private static (int, int, string) GetJsonBeginEndIndexesAndPureJson(string document)
{ {
var searchedIndex = 0; var searchedIndex = 0;
while (searchedIndex < document.Length) while (searchedIndex < document.Length)
{ {
var jsonBeginningIndex = document.Substring(searchedIndex).IndexOf(jsonOpener, StringComparison.Ordinal) + jsonOpener.Length + searchedIndex; var jsonBeginningIndex = document.Substring(searchedIndex).IndexOf(JsonOpener, StringComparison.Ordinal) + JsonOpener.Length + searchedIndex;
if (jsonBeginningIndex < 0) if (jsonBeginningIndex < 0)
{ {
return (-1, -1, ""); return (-1, -1, "");
} }
var jsonEndingIndex = document.Substring(jsonBeginningIndex).IndexOf(jsonCloser, StringComparison.Ordinal) + jsonBeginningIndex; var jsonEndingIndex = document.Substring(jsonBeginningIndex).IndexOf(JsonCloser, StringComparison.Ordinal) + jsonBeginningIndex;
var insideJsonSection = document[jsonBeginningIndex..jsonEndingIndex]; var insideJsonSection = document[jsonBeginningIndex..jsonEndingIndex];
if (insideJsonSection.IndexOf(docs_param) < 0) if (insideJsonSection.IndexOf(DocsParam, StringComparison.Ordinal) < 0)
{ {
searchedIndex = jsonEndingIndex + jsonCloser.Length; searchedIndex = jsonEndingIndex + JsonCloser.Length;
continue; continue;
} }
@ -129,68 +138,84 @@ namespace Volo.Docs.HtmlConverting
{ {
var templates = new List<DocumentPartialTemplateWithValuesDto>(); var templates = new List<DocumentPartialTemplateWithValuesDto>();
while (documentContent.Contains(jsonOpener)) while (documentContent.Contains(JsonOpener))
{ {
var afterJsonOpener = documentContent.Substring( var afterJsonOpener = documentContent.Substring(
documentContent.IndexOf(jsonOpener, StringComparison.Ordinal) + jsonOpener.Length); documentContent.IndexOf(JsonOpener, StringComparison.Ordinal) + JsonOpener.Length
);
var betweenJsonOpenerAndCloser = afterJsonOpener.Substring(0, var betweenJsonOpenerAndCloser = afterJsonOpener.Substring(0,
afterJsonOpener.IndexOf(jsonCloser, StringComparison.Ordinal)); afterJsonOpener.IndexOf(JsonCloser, StringComparison.Ordinal)
);
documentContent = afterJsonOpener.Substring( documentContent = afterJsonOpener.Substring(
afterJsonOpener.IndexOf(jsonCloser, StringComparison.Ordinal) + jsonCloser.Length); afterJsonOpener.IndexOf(JsonCloser, StringComparison.Ordinal) + JsonCloser.Length
);
if (!betweenJsonOpenerAndCloser.Contains(docs_templates)) if (!betweenJsonOpenerAndCloser.Contains(DocsTemplates))
{ {
continue; continue;
} }
var json = betweenJsonOpenerAndCloser.Substring(betweenJsonOpenerAndCloser.IndexOf(docs_templates, StringComparison.Ordinal) + docs_templates.Length); var json = betweenJsonOpenerAndCloser.Substring(betweenJsonOpenerAndCloser.IndexOf(DocsTemplates, StringComparison.Ordinal) + DocsTemplates.Length);
var template = JsonConvert.DeserializeObject<DocumentPartialTemplateWithValuesDto>(json); if (!JsonConvertExtensions.TryDeserializeObject<DocumentPartialTemplateWithValuesDto>(json, out var template))
{
throw new UserFriendlyException($"ERROR-20200327: Cannot validate JSON content for `AvailableParameters`!");
}
templates.Add(template); templates.Add(template);
} }
return templates; return await Task.FromResult(templates);
} }
private string SetPartialTemplates(string document, List<DocumentPartialTemplateContent> templates) private static string SetPartialTemplates(string document, IReadOnlyCollection<DocumentPartialTemplateContent> templates)
{ {
var newDocument = new StringBuilder(); var newDocument = new StringBuilder();
while (document.Contains(jsonOpener)) while (document.Contains(JsonOpener))
{ {
var beforeJson = document.Substring(0, var beforeJson = document.Substring(0,
document.IndexOf(jsonOpener, StringComparison.Ordinal) + jsonOpener.Length); document.IndexOf(JsonOpener, StringComparison.Ordinal) + JsonOpener.Length
);
var afterJsonOpener = document.Substring( var afterJsonOpener = document.Substring(
document.IndexOf(jsonOpener, StringComparison.Ordinal) + jsonOpener.Length); document.IndexOf(JsonOpener, StringComparison.Ordinal) + JsonOpener.Length
);
var betweenJsonOpenerAndCloser = afterJsonOpener.Substring(0, var betweenJsonOpenerAndCloser = afterJsonOpener.Substring(0,
afterJsonOpener.IndexOf(jsonCloser, StringComparison.Ordinal)); afterJsonOpener.IndexOf(JsonCloser, StringComparison.Ordinal)
);
if (!betweenJsonOpenerAndCloser.Contains(docs_templates)) if (!betweenJsonOpenerAndCloser.Contains(DocsTemplates))
{ {
document = afterJsonOpener.Substring( document = afterJsonOpener.Substring(
afterJsonOpener.IndexOf(jsonCloser, StringComparison.Ordinal) + jsonCloser.Length); afterJsonOpener.IndexOf(JsonCloser, StringComparison.Ordinal) + JsonCloser.Length
newDocument.Append(beforeJson + betweenJsonOpenerAndCloser + jsonCloser); );
newDocument.Append(beforeJson + betweenJsonOpenerAndCloser + JsonCloser);
continue; continue;
} }
var json = betweenJsonOpenerAndCloser.Substring(betweenJsonOpenerAndCloser.IndexOf(docs_templates, StringComparison.Ordinal) + docs_templates.Length); var json = betweenJsonOpenerAndCloser.Substring(
betweenJsonOpenerAndCloser.IndexOf(DocsTemplates, StringComparison.Ordinal) + DocsTemplates.Length
var templatePath = JsonConvert.DeserializeObject<DocumentPartialTemplateWithValuesDto>(json)?.Path; );
var template = templates.FirstOrDefault(t => t.Path == templatePath); if (JsonConvertExtensions.TryDeserializeObject<DocumentPartialTemplateWithValuesDto>(json, out var documentPartialTemplateWithValuesDto))
{
var template = templates.FirstOrDefault(t => t.Path == documentPartialTemplateWithValuesDto.Path);
var beforeTemplate = document.Substring(0, var beforeTemplate = document.Substring(0,
document.IndexOf(jsonOpener, StringComparison.Ordinal)); document.IndexOf(JsonOpener, StringComparison.Ordinal)
);
newDocument.Append(beforeTemplate + template?.Content + jsonCloser); newDocument.Append(beforeTemplate + template?.Content + JsonCloser);
document = afterJsonOpener.Substring( document = afterJsonOpener.Substring(
afterJsonOpener.IndexOf(jsonCloser, StringComparison.Ordinal) + jsonCloser.Length); afterJsonOpener.IndexOf(JsonCloser, StringComparison.Ordinal) + JsonCloser.Length
);
}
} }
newDocument.Append(document); newDocument.Append(document);

31
modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml

@ -68,7 +68,7 @@
} }
<div class="for-mobile"> <div class="for-mobile">
<div class="navbar-light"> <div class="navbar-dark">
<button type="button" class="open-dmenu navbar-toggler" aria-label="Close"> <button type="button" class="open-dmenu navbar-toggler" aria-label="Close">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
@ -108,7 +108,7 @@
<div class="input-group"> <div class="input-group">
<div class="input-group-prepend"> <div class="input-group-prepend">
<label class="input-group-text"> <label class="input-group-text">
<i class="fa fa-check-square-o" aria-hidden="true" data-toggle="tooltip" title="@L["Version"]"></i> <i class="fas fa-code-branch" aria-hidden="true" data-toggle="tooltip" title="@L["Version"]"></i>
</label> </label>
</div> </div>
@ -124,15 +124,15 @@
@if (Model.LanguageSelectListItems.Count > 1) @if (Model.LanguageSelectListItems.Count > 1)
{ {
<div class="col @(Model.VersionSelectItems.Any()?"pl-0":"")"> <div class="col-5 @(Model.VersionSelectItems.Any()?"pl-0":"")">
<div class="docs-version docs-language @(Model.VersionSelectItems.Any()?"pl-1":"")"> <div class="docs-version docs-language @(Model.VersionSelectItems.Any()?"pl-1":"")">
<div class="version-select"> <div class="version-select">
<div class="input-group"> <div class="input-group">
<div class="input-group-prepend"> @*<div class="input-group-prepend">
<label class="input-group-text"> <label class="input-group-text">
<i class="fa fa-globe" aria-hidden="true" data-toggle="tooltip" title="@L["Language"]"></i> <i class="fa fa-globe" aria-hidden="true" data-toggle="tooltip" title="@L["Language"]"></i>
</label> </label>
</div> </div>*@
<select asp-items="Model.LanguageSelectListItems" <select asp-items="Model.LanguageSelectListItems"
class="form-control" class="form-control"
onchange="window.location.replace(this.value)"> onchange="window.location.replace(this.value)">
@ -163,11 +163,11 @@
@if (Model.FullSearchEnabled) @if (Model.FullSearchEnabled)
{ {
<div class="docs-version mb-4"> <div class="docs-version mt-2 mb-4">
<div class="version-select"> <div class="version-select">
<div class="input-group"> <div class="input-group">
<div class="input-group-prepend"> <div class="input-group-prepend">
<label class="input-group-text"><i class="fa fa-filter"></i></label> <label class="input-group-text"><i class="fa fa-search"></i></label>
</div> </div>
<input class="form-control" <input class="form-control"
@ -224,7 +224,9 @@
@if (!string.IsNullOrEmpty(Model.Document.EditLink)) @if (!string.IsNullOrEmpty(Model.Document.EditLink))
{ {
<a href="@Model.Document.EditLink" target="_blank"> <a href="@Model.Document.EditLink" target="_blank">
<i class="fa fa-edit"></i> @(L["Edit"]) (@L["LastEditTime"]: @Model.Document.LastUpdatedTime.ToShortDateString()) <i class="fa fa-edit"></i>
@(L["Edit"])
<span class="for-desktop">(@L["LastEditTime"]: @Model.Document.LastUpdatedTime.ToShortDateString())</span>
</a> </a>
} }
</div> </div>
@ -232,20 +234,21 @@
<div class="float-right mr-3"> <div class="float-right mr-3">
@if (Model.Document.Contributors != null && Model.Document.Contributors.Count > 0) @if (Model.Document.Contributors != null && Model.Document.Contributors.Count > 0)
{ {
@(L["Contributors"].Value + " :") <span class="for-desktop">
@(L["Contributors"].Value + " :") </span>
@foreach (var contributor in Model.Document.Contributors) @foreach (var contributor in Model.Document.Contributors)
{ {
<a href="@contributor.UserProfileUrl" target="_blank"> <a href="@contributor.UserProfileUrl" target="_blank">
<img src="@contributor.AvatarUrl" <img src="@contributor.AvatarUrl"
class="rounded-circle" class="rounded-circle"
alt="Avatar" alt="Avatar"
height="21" height="21"
width="21" width="21"
title="@contributor.Username" /> title="@contributor.Username" />
</a> </a>
} }
} }
</div> </div>
</div> </div>

88
modules/docs/src/Volo.Docs.Web/Pages/Documents/Search.cshtml

@ -15,53 +15,73 @@
<style> <style>
highlight { highlight {
font-weight: bold; font-weight: bold;
color: red; color: #212529;
font-style: italic; background: #f9efa6;
padding: 0 3px;
border-radius: 3px;
}
body {
background-color: rgba(0, 0, 0, 0.03);
} }
</style> </style>
} }
<div class="container"> <div class="container mb-5">
<form method="get" action="/search/@Model.LanguageCode/@Model.ProjectName/@Model.Version/" class="mt-4"> <form method="get" action="/search/@Model.LanguageCode/@Model.ProjectName/@Model.Version/" class="mt-4">
<input type="text" asp-for="@Model.KeyWord" class="form-control" /> <h4 class="text-center my-3">Search in Documents</h4>
<button type="submit" class="btn-block btn-primary btn-lg mt-3">Search</button> <div class="card rounded">
<div class="p-3 bg-white">
<div class="form-row">
<div class="col"><input type="text" asp-for="@Model.KeyWord" class="form-control" /></div>
<div class="col-auto"><button type="submit" class="btn btn-primary px-md-5">Search</button></div>
</div>
</div>
</div>
</form> </form>
<div class="my-3 p-3 bg-white rounded"> <div class="card mt-4 rounded">
<h6 class="border-bottom pb-4 mb-0">Search results</h6> <div class="card-header">
<h5 class="text-center ">Search Results</h5>
@foreach (var docs in Model.SearchOutputs) </div>
{ <div class="p-5 card-body">
<div class="media text-muted pt-3"> @foreach (var docs in Model.SearchOutputs)
<div class="media-body pb-3 mb-0 small border-bottom"> {
<div class="list-group"> <div class="media text-muted">
<div class="media-body pb-3 small">
<div class="list-group">
@functions @functions
{
string RemoveFileExtensionFromPath(string path)
{
if (path == null)
{ {
return null; string RemoveFileExtensionFromPath(string path)
} {
if (path == null)
{
return null;
}
return path.EndsWith("." + @Model.Project.Format) return path.EndsWith("." + @Model.Project.Format)
? path.Left(path.Length - Model.Project.Format.Length - 1) ? path.Left(path.Length - Model.Project.Format.Length - 1)
: path; : path;
}
} }
}
<a href="/@Model.LanguageCode/@Model.ProjectName/@Model.Version/@RemoveFileExtensionFromPath(docs.Name)">
<h3>@RemoveFileExtensionFromPath(docs.Name)</h3></a>
@foreach (var highlight in docs.Highlight)
{
<p class="list-group-item list-group-item-action">@Html.Raw(highlight)</p>
}
<h5 class="mb-3">
<a href="/@Model.LanguageCode/@Model.ProjectName/@Model.Version/@RemoveFileExtensionFromPath(docs.Name)">
@RemoveFileExtensionFromPath(docs.Name)
</a>
</h5>
<div class="mb-4">
@foreach (var highlight in docs.Highlight)
{
<p class=" ">@Html.Raw(highlight)</p>
}
</div>
</div>
</div> </div>
</div> </div>
</div> }
} </div>
</div> </div>
</div> </div>

240
modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/Styles/vs.css

@ -10,21 +10,21 @@
transition: color .25s linear; transition: color .25s linear;
color: gray; } color: gray; }
.docs-page .anchorjs-link:hover { .docs-page .anchorjs-link:hover {
color: #007bff;
text-decoration: none; } text-decoration: none; }
.docs-page .docs-sidebar { .docs-page .docs-sidebar {
background: #f5f7f9;
padding-right: 1rem; padding-right: 1rem;
position: relative; position: relative;
top: 0px; top: 0px;
left: 0; left: 0;
position: fixed; } position: fixed;
background: #1d1d1d; }
.docs-page .docs-sidebar .input-group {
border-radius: 5px;
overflow: hidden; }
.docs-page .docs-sidebar .docs-sidebar-wrapper { .docs-page .docs-sidebar .docs-sidebar-wrapper {
width: 270px; width: 270px;
float: right; } float: right; }
.docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control { .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control {
background: none;
background: #fff;
border: 0; } border: 0; }
.docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:focus, .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:active, .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:hover, .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:visited { .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:focus, .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:active, .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:hover, .docs-page .docs-sidebar .docs-sidebar-wrapper input.form-control:visited {
box-shadow: none; } box-shadow: none; }
@ -33,27 +33,28 @@
padding: 0 1rem; padding: 0 1rem;
margin: .25rem 0; } margin: .25rem 0; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select {
border-radius: 3px; border-radius: 3px; }
border: 1px solid #e9ecef; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select .input-group-text { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select .input-group-text {
padding: 0.375rem 0.6rem; padding: 0 10px;
font-size: .9rem; font-size: .9rem;
width: 32px; width: 26px;
height: 30px; height: 34px;
line-height: 1; line-height: 1;
border-radius: 0px; border-radius: 0px;
border: 1px solid #e9ecef; } border: 0; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select .input-group-text i {
color: #666; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control {
padding: 0 10px; padding: 0 10px 2px 10px;
border: 0; border: 0;
min-height: 30px; min-height: 34px;
height: 30px; height: 34px;
font-size: .85em; font-size: .9em;
border-radius: 1px; } border-radius: 0px; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:focus, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:active, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:hover, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:visited, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:focus, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:active, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:hover, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:visited { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:focus, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:active, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:hover, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control:visited, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:focus, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:active, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:hover, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control:visited {
box-shadow: none; } box-shadow: none; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control {
padding-left: 6px; } padding: 0 10px 2px 6px; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-filter { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-filter {
padding: 0 1rem; padding: 0 1rem;
margin: .5rem 0; margin: .5rem 0;
@ -64,7 +65,7 @@
height: 100vh; } height: 100vh; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list > ul { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list > ul {
display: block; display: block;
height: calc(100vh - 220px); height: calc(100vh - 320px);
overflow-y: auto; } overflow-y: auto; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul {
font-size: .935em; font-size: .935em;
@ -88,6 +89,12 @@
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a.last-link { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a.last-link {
top: 11px; top: 11px;
color: #aaa; } color: #aaa; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li .badge {
text-transform: uppercase;
font-size: 9px;
position: relative;
letter-spacing: .125px;
top: -2px; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li span.tree-toggle { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li span.tree-toggle {
color: #999; color: #999;
padding: 7px 0; padding: 7px 0;
@ -129,10 +136,10 @@
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree.last-link > span .fa { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree.last-link > span .fa {
transform: rotate(0deg); } transform: rotate(0deg); }
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand { .docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand {
font-size: 1.5rem; font-size: 1.35rem;
color: #000; color: #000;
font-weight: 700; font-weight: 700;
padding: 20px 0 10px; padding: 15px 0 15px;
line-height: 1; } line-height: 1; }
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand strong { .docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand strong {
font-weight: 300; font-weight: 300;
@ -153,7 +160,8 @@
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-logo-desc strong { .docs-page .docs-sidebar .docs-top .navbar-logo .navbar-logo-desc strong {
display: block; } display: block; }
.docs-page .docs-content { .docs-page .docs-content {
overflow-x: scroll; } overflow-x: scroll;
min-height: 100vh; }
.docs-page .docs-content .contributors { .docs-page .docs-content .contributors {
position: absolute; position: absolute;
top: 15px; top: 15px;
@ -222,10 +230,11 @@
.docs-page .docs-content article.docs-body .blockquote { .docs-page .docs-content article.docs-body .blockquote {
margin-bottom: 1rem; margin-bottom: 1rem;
margin-left: 0; margin-left: 0;
border-left: 2px solid gray; border-left: 3px solid #d2dbe4;
padding: 1em; padding: 1em 1.5em;
background-color: #eee; background-color: #e9edf1;
padding-bottom: .2em; } padding-bottom: .2em;
font-size: 1em; }
.docs-page .docs-content article.docs-body img { .docs-page .docs-content article.docs-body img {
max-width: 100%; max-width: 100%;
border: 1px solid #f4f5f7; border: 1px solid #f4f5f7;
@ -257,10 +266,8 @@
.docs-page .docs-page-index .docs-inner-anchors { .docs-page .docs-page-index .docs-inner-anchors {
position: fixed; position: fixed;
top: 0px; top: 0px;
/* max-width: 270px; */
padding: 10px; padding: 10px;
font-size: .90em; font-size: .90em; }
/* height: 100vh; */ }
.docs-page .docs-page-index .docs-inner-anchors .navbar .nav-pills { .docs-page .docs-page-index .docs-inner-anchors .navbar .nav-pills {
font-size: .92em; font-size: .92em;
margin-left: 15px; margin-left: 15px;
@ -300,83 +307,95 @@
.docs-page .docs-page-index .scroll-top-btn.showup { .docs-page .docs-page-index .scroll-top-btn.showup {
display: block; } display: block; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control, .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control {
background: #000000;
color: white; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control {
background: #000000;
color: white; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control::placeholder {
color: white;
opacity: .5; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version .version-select label {
background: #000000;
border-color: #000000;
color: #ddd; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-filter .form-control {
background: #333;
color: #999; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-filter select {
border: 0;
border-radius: 6px; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-filter .filter-icon i.fa {
color: #aaa; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a {
color: #aaa;
border-bottom: 0; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a:hover {
color: #fff; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon {
font-size: .85em;
transition: .3s;
width: 18px;
height: 18px;
text-align: center;
padding: 0;
line-height: 1;
border-radius: 50%;
margin-right: 4px;
position: absolute;
left: 2px;
top: 11px;
color: #aaa;
cursor: default; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon .fa-long-arrow-right.no-link {
color: #555; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon .fa-chevron-right {
cursor: pointer; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon.last-link {
top: 11px; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li span.tree-toggle {
color: #555;
padding: 7px 0;
display: block;
border-bottom: 0; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree > a {
color: #fff;
transition: .4s; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree > a span .fa {
color: #fff; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree > a span:not(.last-link) .fa {
transform: rotate(90deg);
color: #fff; }
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand {
color: #fff;
text-transform: uppercase;
white-space: unset; }
.docs-page .docs-sidebar .docs-top .navbar-logo .go-back-site {
color: #fff;
text-align: center;
display: block;
width: 100%;
background: #444;
padding: 6px 0 8px;
border-radius: 5px; }
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-logo-desc {
color: #ddd; }
@media (min-width: 1100px) { @media (min-width: 1100px) {
.container { .container {
max-width: 1080px; } max-width: 1080px; } }
.docs-page .docs-sidebar.dark-sidebar {
background: #191919; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-version .version-select {
border: 1px solid #333; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-version .version-select select.form-control, .docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control {
background: #191919;
border-color: #191919;
color: #999; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control {
background: #191919;
border-color: #191919;
color: #999; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-version .version-select input.form-control::placeholder {
color: #999;
opacity: .5; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-version .version-select label {
background: #333;
border-color: #333;
color: #ddd; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-filter .form-control {
background: #333;
color: #999; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-filter select {
border: 0;
border-radius: 6px; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-filter .filter-icon i.fa {
color: #aaa; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a {
color: #aaa;
border-bottom: 0; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a:hover {
color: #fff; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon {
font-size: .85em;
transition: .3s;
width: 18px;
height: 18px;
text-align: center;
padding: 0;
line-height: 1;
border-radius: 50%;
margin-right: 4px;
position: absolute;
left: 2px;
top: 11px;
color: #aaa;
cursor: default; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon .fa-long-arrow-right.no-link {
color: #555; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon .fa-chevron-right {
cursor: pointer; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li a .plus-icon.last-link {
top: 11px; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li span.tree-toggle {
color: #555;
padding: 7px 0;
display: block;
border-bottom: 0; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree > a {
color: #fff;
transition: .4s; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree > a span .fa {
color: #fff; }
.docs-page .docs-sidebar.dark-sidebar .docs-sidebar-wrapper .docs-tree-list ul li.selected-tree > a span:not(.last-link) .fa {
transform: rotate(90deg);
color: #fff; }
.docs-page .docs-sidebar.dark-sidebar .docs-top .navbar-logo .navbar-brand {
color: #fff;
text-transform: uppercase;
white-space: unset; }
.docs-page .docs-sidebar.dark-sidebar .docs-top .navbar-logo .go-back-site {
color: #fff; }
.docs-page .docs-sidebar.dark-sidebar .docs-top .navbar-logo .navbar-logo-desc {
color: #ddd; } }
@media (min-width: 1366px) { @media (min-width: 1366px) {
.container { .container {
@ -420,30 +439,21 @@
left: 0; left: 0;
width: 100%; width: 100%;
z-index: 100; z-index: 100;
background: #f5f7f9; background: #1d1d1d;
display: none; } display: none; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list .docs-filter { .docs-page .docs-sidebar .docs-sidebar-wrapper .docs-tree-list .docs-filter {
padding: 0 0 1rem !important; } padding: 0 0 1rem !important; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version label {
width: 36px;
text-align: center;
padding-left: 0;
padding-right: 0;
display: inline-block;
line-height: 26px; }
.docs-page .docs-sidebar .docs-sidebar-wrapper .docs-version input.form-control {
padding-left: 12px !important; }
.docs-page .docs-sidebar .docs-top .navbar-logo { .docs-page .docs-sidebar .docs-top .navbar-logo {
padding: 0rem; padding: 0rem;
padding-top: .3rem; padding-top: .3rem;
display: block; display: block;
text-align: center; } text-align: center; }
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand { .docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand {
font-size: 1.5rem; font-size: 1.25rem;
font-weight: 700; font-weight: 700;
display: block; display: block;
margin-right: 0em; margin-right: 0em;
padding: 7px 0 10px; padding: 10px 0 15px;
text-transform: uppercase; } text-transform: uppercase; }
.docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand .docs-logo { .docs-page .docs-sidebar .docs-top .navbar-logo .navbar-brand .docs-logo {
width: 110px; } width: 110px; }

2
modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/Styles/vs.min.css

File diff suppressed because one or more lines are too long

349
modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/Styles/vs.scss

@ -16,19 +16,20 @@ body {
} }
.anchorjs-link:hover { .anchorjs-link:hover {
color: #007bff;
text-decoration: none; text-decoration: none;
} }
.docs-sidebar { .docs-sidebar {
background: #f5f7f9;
padding-right: 1rem; padding-right: 1rem;
position: relative; position: relative;
top: 0px; top: 0px;
left: 0; left: 0;
position: fixed; position: fixed;
background: #1d1d1d;
.docs-language {
.input-group {
border-radius: 5px;
overflow: hidden;
} }
.docs-sidebar-wrapper { .docs-sidebar-wrapper {
@ -36,8 +37,6 @@ body {
float: right; float: right;
input.form-control { input.form-control {
background: none;
background: #fff;
border: 0; border: 0;
&:focus, &:active, &:hover, &:visited { &:focus, &:active, &:hover, &:visited {
@ -52,25 +51,28 @@ body {
.version-select { .version-select {
border-radius: 3px; border-radius: 3px;
border: 1px solid #e9ecef;
.input-group-text { .input-group-text {
padding: 0.375rem 0.6rem; padding: 0 10px;
font-size: .9rem; font-size: .9rem;
width: 32px; width: 26px;
height: 30px; height: 34px;
line-height: 1; line-height: 1;
border-radius: 0px; border-radius: 0px;
border: 1px solid #e9ecef; border: 0;
i {
color: #666;
}
} }
select.form-control, input.form-control { select.form-control, input.form-control {
padding: 0 10px; padding: 0 10px 2px 10px;
border: 0; border: 0;
min-height: 30px; min-height: 34px;
height: 30px; height: 34px;
font-size: .85em; font-size: .9em;
border-radius: 1px; border-radius: 0px;
&:focus, &:active, &:hover, &:visited { &:focus, &:active, &:hover, &:visited {
box-shadow: none; box-shadow: none;
@ -78,10 +80,7 @@ body {
} }
select.form-control { select.form-control {
padding-left: 6px; padding: 0 10px 2px 6px;
}
label {
} }
} }
} }
@ -104,7 +103,7 @@ body {
> ul { > ul {
display: block; display: block;
height: calc(100vh - 220px); height: calc(100vh - 320px);
overflow-y: auto; overflow-y: auto;
} }
@ -139,6 +138,14 @@ body {
} }
} }
.badge {
text-transform: uppercase;
font-size: 9px;
position: relative;
letter-spacing: .125px;
top: -2px;
}
span.tree-toggle { span.tree-toggle {
color: #999; color: #999;
padding: 7px 0; padding: 7px 0;
@ -224,16 +231,16 @@ body {
.docs-top { .docs-top {
.navbar-logo { .navbar-logo {
.navbar-brand { .navbar-brand {
font-size: 1.5rem; font-size: 1.35rem;
color: #000; color: #000;
font-weight: 700; font-weight: 700;
padding: 20px 0 10px; padding: 15px 0 15px;
line-height: 1; line-height: 1;
strong { strong {
font-weight: 300; font-weight: 300;
text-transform: uppercase; text-transform: uppercase;
font-size: .7em; font-size: .7em;
letter-spacing: 1px; letter-spacing: 1px;
} }
} }
@ -264,6 +271,7 @@ body {
.docs-content { .docs-content {
overflow-x: scroll; overflow-x: scroll;
min-height: 100vh;
.contributors { .contributors {
position: absolute; position: absolute;
@ -372,10 +380,11 @@ body {
.blockquote { .blockquote {
margin-bottom: 1rem; margin-bottom: 1rem;
margin-left: 0; margin-left: 0;
border-left: 2px solid gray; border-left: 3px solid #d2dbe4;
padding: 1em; padding: 1em 1.5em;
background-color: #eee; background-color: #e9edf1;
padding-bottom: .2em padding-bottom: .2em;
font-size: 1em;
} }
img { img {
@ -433,10 +442,9 @@ body {
.docs-inner-anchors { .docs-inner-anchors {
position: fixed; position: fixed;
top: 0px; top: 0px;
/* max-width: 270px; */
padding: 10px; padding: 10px;
font-size: .90em; font-size: .90em;
/* height: 100vh; */
.navbar { .navbar {
.nav-pills { .nav-pills {
font-size: .92em; font-size: .92em;
@ -508,163 +516,189 @@ body {
} }
@media (min-width: 1100px) { .docs-page {
.container { .docs-sidebar {
max-width: 1080px; .docs-sidebar-wrapper {
}
.docs-page {
.docs-sidebar {
&.dark-sidebar {
background: #191919;
.docs-sidebar-wrapper {
.docs-version {
.version-select {
border: 1px solid #333;
select.form-control, input.form-control { .docs-version {
background: #191919; .version-select {
border-color: #191919;
color: #999;
}
input.form-control { select.form-control, input.form-control {
background: #191919; background: #000000;
border-color: #191919; color: white;
color: #999; }
&::placeholder { input.form-control {
color: #999; background: #000000;
opacity: .5; color: white;
}
}
label { &::placeholder {
background: #333; color: white;
border-color: #333; opacity: .5;
color: #ddd;
}
} }
} }
.docs-filter { label {
.form-control { background: #000000;
background: #333; border-color: #000000;
color: #999; color: #ddd;
} }
}
}
select { .docs-filter {
border: 0; .form-control {
border-radius: 6px; background: #333;
} color: #999;
}
.filter-icon { select {
i.fa { border: 0;
color: #aaa; border-radius: 6px;
} }
}
}
.docs-tree-list { .filter-icon {
ul { i.fa {
li { color: #aaa;
}
}
}
.docs-tree-list {
ul {
li {
a {
color: #aaa;
border-bottom: 0;
&:hover { a {
color: #fff; color: #aaa;
} border-bottom: 0;
.plus-icon { &:hover {
font-size: .85em; color: #fff;
transition: .3s; }
width: 18px;
height: 18px;
text-align: center;
padding: 0;
line-height: 1;
border-radius: 50%;
margin-right: 4px;
position: absolute;
left: 2px;
top: 11px;
color: #aaa;
cursor: default;
.fa-long-arrow-right {
&.no-link {
color: #555;
}
}
.fa-chevron-right { .plus-icon {
cursor: pointer; font-size: .85em;
} transition: .3s;
width: 18px;
height: 18px;
text-align: center;
padding: 0;
line-height: 1;
border-radius: 50%;
margin-right: 4px;
position: absolute;
left: 2px;
top: 11px;
color: #aaa;
cursor: default;
&.last-link { .fa-long-arrow-right {
top: 11px; &.no-link {
} color: #555;
} }
} }
.fa-chevron-right {
cursor: pointer;
}
span.tree-toggle { &.last-link {
color: #555; top: 11px;
padding: 7px 0;
display: block;
border-bottom: 0;
} }
}
}
&.selected-tree { span.tree-toggle {
> a { color: #555;
color: #fff; padding: 7px 0;
transition: .4s; display: block;
border-bottom: 0;
}
span {
.fa {
color: #fff;
}
&:not(.last-link) .fa { &.selected-tree {
transform: rotate(90deg); > a {
color: #fff; color: #fff;
} transition: .4s;
}
span {
.fa {
color: #fff;
}
&:not(.last-link) .fa {
transform: rotate(90deg);
color: #fff;
} }
} }
} }
} }
} }
} }
}
}
.docs-top { .docs-top {
.navbar-logo { .navbar-logo {
.navbar-brand { .navbar-brand {
color: #fff; color: #fff;
text-transform: uppercase; text-transform: uppercase;
white-space: unset; white-space: unset;
} }
.go-back-site { .go-back-site {
color: #fff; color: #fff;
} text-align: center;
display: block;
width: 100%;
background: #444;
padding: 6px 0 8px;
border-radius: 5px;
}
.navbar-logo-desc { .navbar-logo-desc {
color: #ddd; color: #ddd;
}
}
} }
} }
} }
} }
} }
@media (min-width: 1100px) {
.container {
max-width: 1080px;
}
}
@media (min-width: 1366px) { @media (min-width: 1366px) {
.container { .container {
max-width: 1340px; max-width: 1340px;
@ -720,7 +754,7 @@ body {
left: 0; left: 0;
width: 100%; width: 100%;
z-index: 100; z-index: 100;
background: #f5f7f9; background: #1d1d1d;
display: none; display: none;
.docs-filter { .docs-filter {
@ -732,17 +766,6 @@ body {
} }
.docs-version { .docs-version {
label {
width: 36px;
text-align: center;
padding-left: 0;
padding-right: 0;
display: inline-block;
line-height: 26px;
}
input.form-control {
padding-left: 12px !important;
}
} }
} }
@ -754,11 +777,11 @@ body {
text-align: center; text-align: center;
.navbar-brand { .navbar-brand {
font-size: 1.5rem; font-size: 1.25rem;
font-weight: 700; font-weight: 700;
display: block; display: block;
margin-right: 0em; margin-right: 0em;
padding: 7px 0 10px; padding: 10px 0 15px;
text-transform: uppercase; text-transform: uppercase;
.docs-logo { .docs-logo {
@ -971,6 +994,7 @@ div.code-toolbar > .toolbar a {
background-color: #bddcfd; background-color: #bddcfd;
border: 1px solid #bddcfd; border: 1px solid #bddcfd;
@media screen and (max-width: 1366px) { @media screen and (max-width: 1366px) {
display: none; display: none;
} }
@ -1009,4 +1033,5 @@ div.code-toolbar > .toolbar a {
display: none; display: none;
} }
} }
} }

1
modules/docs/src/Volo.Docs.Web/Volo.Docs.Web.csproj

@ -19,6 +19,7 @@
<ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc.UI.Bootstrap\Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.csproj" /> <ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc.UI.Bootstrap\Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.csproj" />
<ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc.UI.Packages\Volo.Abp.AspNetCore.Mvc.UI.Packages.csproj" /> <ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc.UI.Packages\Volo.Abp.AspNetCore.Mvc.UI.Packages.csproj" />
<ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared\Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.csproj" /> <ProjectReference Include="..\..\..\..\framework\src\Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared\Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.csproj" />
<ProjectReference Include="..\Volo.Docs.Domain\Volo.Docs.Domain.csproj" />
<ProjectReference Include="..\Volo.Docs.HttpApi\Volo.Docs.HttpApi.csproj" /> <ProjectReference Include="..\Volo.Docs.HttpApi\Volo.Docs.HttpApi.csproj" />
<PackageReference Include="Markdig.Signed" Version="0.18.0" /> <PackageReference Include="Markdig.Signed" Version="0.18.0" />
<PackageReference Include="Scriban" Version="2.1.1" /> <PackageReference Include="Scriban" Version="2.1.1" />

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

Loading…
Cancel
Save