Browse Source

Merge branch 'dev' into ui-extensions-blazor

pull/6647/head
Ilkay Ilknur 6 years ago
parent
commit
3fecd0cdd5
  1. 6
      .github/workflows/auto-pr.yml
  2. 17
      abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/en.json
  3. 6
      abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/tr.json
  4. 9
      abp_io/AbpIoLocalization/AbpIoLocalization/Commercial/Localization/Resources/en.json
  5. 43
      abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/en.json
  6. 4
      common.props
  7. 9
      docs/en/Application-Services.md
  8. 7
      docs/en/AspNet-Boilerplate-Migration-Guide.md
  9. 9
      docs/en/Best-Practices/Entity-Framework-Core-Integration.md
  10. 6
      docs/en/Best-Practices/MongoDB-Integration.md
  11. 18
      docs/en/Best-Practices/Repositories.md
  12. 241
      docs/en/Blog-Posts/2021-01-14 v4_2_Preview/POST.md
  13. BIN
      docs/en/Blog-Posts/2021-01-14 v4_2_Preview/easy-crm.png
  14. BIN
      docs/en/Blog-Posts/2021-01-14 v4_2_Preview/microservice-template-diagram.png
  15. BIN
      docs/en/Blog-Posts/2021-01-14 v4_2_Preview/public-website.jpg
  16. BIN
      docs/en/Blog-Posts/2021-01-14 v4_2_Preview/swagger-authorize-modal.png
  17. BIN
      docs/en/Blog-Posts/2021-01-14 v4_2_Preview/swagger-authorize.png
  18. 53
      docs/en/Blog-Posts/2021-01-28 v4_2_Release_Stable/POST.md
  19. 17
      docs/en/CSRF-Anti-Forgery.md
  20. 103
      docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/POST.md
  21. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/example-result.png
  22. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/initial-project.png
  23. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/table-app-contract.png
  24. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/table-application.png
  25. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/table-web.png
  26. 343
      docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/POST.md
  27. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/intro.gif
  28. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/organization-chart.jpg
  29. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/organization-units-menu-item.jpg
  30. BIN
      docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/table.gif
  31. 2
      docs/en/Dependency-Injection.md
  32. 12
      docs/en/Domain-Driven-Design-Implementation-Guide.md
  33. 94
      docs/en/Entity-Framework-Core.md
  34. 50
      docs/en/Getting-Started-Running-Solution.md
  35. 101
      docs/en/Migration-Guides/Abp-4_2.md
  36. 5
      docs/en/Migration-Guides/Index.md
  37. 57
      docs/en/MongoDB.md
  38. 200
      docs/en/Repositories.md
  39. 2
      docs/en/Road-Map.md
  40. 3
      docs/en/Samples/Index.md
  41. 6
      docs/en/Specifications.md
  42. 37
      docs/en/Tutorials/Part-10.md
  43. 13
      docs/en/Tutorials/Part-7.md
  44. 13
      docs/en/Tutorials/Part-8.md
  45. 28
      docs/en/UI/Angular/Authorization.md
  46. 83
      docs/en/UI/Angular/Ellipsis-Directive.md
  47. 248
      docs/en/UI/Angular/Modal.md
  48. 10
      docs/en/UI/Angular/Multi-Tenancy.md
  49. 64
      docs/en/UI/Angular/Page-Alerts.md
  50. 146
      docs/en/UI/Angular/Router-Events.md
  51. 16
      docs/en/UI/Angular/Testing.md
  52. BIN
      docs/en/UI/Angular/images/ellipsis-directive-before.jpg
  53. BIN
      docs/en/UI/Angular/images/ellipsis-directive-result1.jpg
  54. BIN
      docs/en/UI/Angular/images/ellipsis-directive-result2.jpg
  55. BIN
      docs/en/UI/Angular/images/modal-result-1.jpg
  56. BIN
      docs/en/UI/Angular/images/modal-result-2.jpg
  57. BIN
      docs/en/UI/Angular/images/page-alert-warning-example.png
  58. BIN
      docs/en/UI/Angular/images/page-alert-with-params-example.png
  59. 22
      docs/en/UI/AspNetCore/Bundling-Minification.md
  60. 28
      docs/en/docs-nav.json
  61. 2
      docs/zh-Hans/Customizing-Application-Modules-Overriding-Services.md
  62. 4
      docs/zh-Hans/Domain-Driven-Design-Implementation-Guide.md
  63. 24
      docs/zh-Hans/Entity-Framework-Core-Other-DBMS.md
  64. 9
      docs/zh-Hans/MongoDB.md
  65. 22
      docs/zh-Hans/UI/AspNetCore/Bundling-Minification.md
  66. 7
      framework/src/Volo.Abp.AspNetCore.MultiTenancy/Volo/Abp/AspNetCore/MultiTenancy/DomainTenantResolveContributor.cs
  67. 72
      framework/src/Volo.Abp.AspNetCore.MultiTenancy/Volo/Abp/AspNetCore/MultiTenancy/MultiTenancyMiddleware.cs
  68. 3
      framework/src/Volo.Abp.AspNetCore.Mvc.Client/Volo/Abp/AspNetCore/Mvc/Client/MvcCachedApplicationConfigurationClientHelper.cs
  69. 33
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bundling/Volo/Abp/AspNetCore/Mvc/UI/Bundling/BundleConfigurationCollection.cs
  70. 9
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js
  71. 14
      framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js
  72. 1
      framework/src/Volo.Abp.AspNetCore.Mvc.UI/Volo/Abp/AspNetCore/Mvc/UI/RazorPages/AbpPageModel.cs
  73. 1
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpController.cs
  74. 2
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpMvcOptionsExtensions.cs
  75. 1
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpViewComponent.cs
  76. 53
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
  77. 57
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProviderOptions.cs
  78. 25
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Content/InternalRemoteStreamContent.cs
  79. 11
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentInputFormatter.cs
  80. 13
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentOutputFormatter.cs
  81. 14
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Localization/AbpLanguagesController.cs
  82. 1
      framework/src/Volo.Abp.AspNetCore.SignalR/Volo/Abp/AspNetCore/SignalR/AbpHub.cs
  83. 23
      framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/RequestLocalization/AbpRequestCultureCookieHelper.cs
  84. 10
      framework/src/Volo.Abp.Authorization/Volo/Abp/Authorization/Localization/nl.json
  85. 16
      framework/src/Volo.Abp.BackgroundJobs.Quartz/Volo/Abp/BackgroundJobs/Quartz/AbpBackgroundJobQuartzOptions.cs
  86. 14
      framework/src/Volo.Abp.BackgroundJobs.Quartz/Volo/Abp/BackgroundJobs/Quartz/QuartzBackgroundJobManager.cs
  87. 20
      framework/src/Volo.Abp.BackgroundJobs.Quartz/Volo/Abp/BackgroundJobs/Quartz/QuartzJobExecutionAdapter.cs
  88. 26
      framework/src/Volo.Abp.BlazoriseUI/AbpCrudPageBase.cs
  89. 6
      framework/src/Volo.Abp.BlazoriseUI/Volo.Abp.BlazoriseUI.csproj
  90. 3
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Auth/AuthService.cs
  91. 6
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/CliPaths.cs
  92. 6
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CreateMigrationAndRunMigrator.cs
  93. 67
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/NewCommand.cs
  94. 30
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/Services/ConnectionStringProvider.cs
  95. 4
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/ModuleInfo.cs
  96. 7
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/ProjectBuildContextExtensions.cs
  97. 30
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/RemoveProjectFromSolutionStep.cs
  98. 9
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/RemovePublicRedisStep.cs
  99. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/SolutionRenameStep.cs
  100. 2
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/TemplateCodeDeleteStep.cs

6
.github/workflows/auto-pr.yml

@ -4,7 +4,7 @@ on:
branches: branches:
- rel-4.2 - rel-4.2
jobs: jobs:
merge-dev-with-rel: merge-dev-with-rel-4-2:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@ -12,8 +12,8 @@ jobs:
ref: dev ref: dev
- name: Reset promotion branch - name: Reset promotion branch
run: | run: |
git fetch origin $GITHUB_REF:$GITHUB_REF git fetch origin rel-4.2:rel-4.2
git reset --hard $GITHUB_REF git reset --hard rel-4.2
- name: Create Pull Request - name: Create Pull Request
uses: peter-evans/create-pull-request@v3 uses: peter-evans/create-pull-request@v3
with: with:

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

@ -198,6 +198,21 @@
"Language": "Language", "Language": "Language",
"Optional": "Optional", "Optional": "Optional",
"CreateArticleLanguageInfo": "The language in which the post is written", "CreateArticleLanguageInfo": "The language in which the post is written",
"Enum:ContentSource:2": "Video Post" "Enum:ContentSource:2": "Video Post",
"VideoPreview": "Video Preview",
"VideoPreviewErrorMessage": "Given video url couldn't retrieve from Youtube. This can be caused by either video is private or the given URL is not available.",
"DeleteCoverImage": "Delete Cover Image",
"DeleteCoverImageConfirmationMessage": "Are you sure you want to delete the cover image for \"{0}\"?",
"DeleteCoverImageSuccessMessage": "Cover image successfully deleted",
"PaymentsOf": "Payments of",
"ShowPaymentsOfOrganization": "Show payments",
"Date": "Date",
"Products": "Products",
"TotalAmount": "Total amount",
"Currency": "Currency",
"Gateway": "Gateway",
"State": "State",
"FailReason": "Fail reason"
} }
} }

6
abp_io/AbpIoLocalization/AbpIoLocalization/Admin/Localization/Resources/tr.json

@ -159,6 +159,10 @@
"UnlimitedQuestionCount": "Sınırsız soru sayısı", "UnlimitedQuestionCount": "Sınırsız soru sayısı",
"Language": "Dil", "Language": "Dil",
"Optional": "Opsiyonel", "Optional": "Opsiyonel",
"CreateArticleLanguageInfo": "Makalenin yazıldığı dil" "CreateArticleLanguageInfo": "Makalenin yazıldığı dil",
"Enum:ContentSource:2": "Video İçerik",
"DeleteCoverImage": "Kapak Fotoğrafını Sil",
"DeleteCoverImageConfirmationMessage": "Kapak fotoğrafını \"{0}\" isimli makale için silmek istediğinize emin misiniz?",
"DeleteCoverImageSuccessMessage": "Kapak fotoğrafı başarılı bir şekilde silinmiştir"
} }
} }

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

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

43
abp_io/AbpIoLocalization/AbpIoLocalization/Community/Localization/Resources/en.json

@ -34,8 +34,8 @@
"MyOrganizations": "My organizations", "MyOrganizations": "My organizations",
"EmailNotValid": "Please enter a valid email address.", "EmailNotValid": "Please enter a valid email address.",
"FeatureRequest": "Feature Request", "FeatureRequest": "Feature Request",
"CreateArticleTitleInfo": "Title of the article to be shown on the article list.", "CreateArticleTitleInfo": "Title of the post to be shown on the post list.",
"CreateArticleSummaryInfo": "A short summary of the article to be shown on the article list.", "CreateArticleSummaryInfo": "A short summary of the post to be shown on the post list.",
"CreateArticleCoverInfo": "For creating an effective article, add a cover photo. Upload 16:9 aspect ratio pictures for the best view. Maximum file size: 1MB.", "CreateArticleCoverInfo": "For creating an effective article, add a cover photo. Upload 16:9 aspect ratio pictures for the best view. Maximum file size: 1MB.",
"ThisExtensionIsNotAllowed": "This extension is not allowed.", "ThisExtensionIsNotAllowed": "This extension is not allowed.",
"TheFileIsTooLarge": "The file is too large.", "TheFileIsTooLarge": "The file is too large.",
@ -100,17 +100,42 @@
"ArticleRequestMessageTitle": "<a href=\"https://github.com/abpframework/abp/issues/new\">Open an issue</a> on the GitHub to request an article/tutorial you want to see on this web site.", "ArticleRequestMessageTitle": "<a href=\"https://github.com/abpframework/abp/issues/new\">Open an issue</a> on the GitHub to request an article/tutorial you want to see on this web site.",
"ArticleRequestMessageBody": "Here, the list of the requested articles by the community. Do you want to write a requested article? Please click to the request and join to the discussion.", "ArticleRequestMessageBody": "Here, the list of the requested articles by the community. Do you want to write a requested article? Please click to the request and join to the discussion.",
"Language": "Language", "Language": "Language",
"CreateArticleLanguageInfo": "The language in which the article is written", "CreateArticleLanguageInfo": "The language for the post content.",
"VideoPost": "Video Post", "VideoPost": "Video Post",
"Article": "Article", "Article": "Article",
"Read": "Read", "Read": "Read",
"CreateGithubArticleUrlInfo": "Original GitHub URL of the article.", "CreateGithubArticleUrlInfo": "Original GitHub URL of the article.",
"CreateVideoContentUrlInfo": "Original Youtube URL of the article.", "CreateVideoContentUrlInfo": "Original Youtube URL of the post.",
"CreateExternalArticleUrlInfo": "Original External Url of the article.", "CreateExternalArticleUrlInfo": "Original External Url of the article.",
"VideoContentForm": "Video Content Form", "VideoContentForm": "Submit Video on YouTube",
"GithubPostForm": "Github Post Form", "GithubPostForm": "Submit Article on GitHub",
"ExternalPostForm": "External Post Form", "ExternalPostForm": "Submit an External Content",
"PostSourceTypeChooses": "We accept three source types for the posts;", "HowToPost": "How to Post?",
"Posts": "Posts" "Posts": "Posts",
"VideoUrl": "Video Url",
"GithubArticleUrl": "Github Article Url",
"ExternalArticleUrl": "External Article Url",
"CreatePostCoverInfo": "For creating an effective post, add a cover photo. Upload 16:9 aspect ratio pictures for the best view. Maximum file size: 1MB.",
"ThankYouForContribution": "Thank you for contributing to the ABP Community.",
"GithubArticle": "Github Article",
"GithubArticleSubmitStepOne": "<span class=\"font-weight-bold\">1.</span> Write an article on any public GitHub repository with the Markdown format. <a target=\"_blank\" href=\"https://github.com/abpframework/abp/blob/dev/docs/en/Community-Articles/2020-12-04-Event-Organizer/Post.md\">example</a>",
"GithubArticleSubmitStepTwo": "<span class=\"font-weight-bold\">2.</span> Submit your article URL using the form.",
"GithubArticleSubmitStepThree": "<span class=\"font-weight-bold\">3.</span> Your article will be rendered in this web site.",
"YoutubeVideo": "Youtube Video",
"YoutubeVideoSubmitStepOne": "<span class=\"font-weight-bold\">1.</span> Publish your video on YouTube.",
"YoutubeVideoSubmitStepTwo": "<span class=\"font-weight-bold\">2.</span> Submit the video URL using the form.",
"YoutubeVideoSubmitStepThree": "<span class=\"font-weight-bold\">3.</span> Visitors will be able to watch your video content directly on this website.",
"ExternalContent": "External Content",
"ExternalContentSubmitStepOne": "<span class=\"font-weight-bold\">1.</span> Create a content on any public platform (medium, your own blog or anywhere you like).",
"ExternalContentSubmitStepTwo": "<span class=\"font-weight-bold\">2.</span> Submit your content URL using the form.",
"ExternalContentSubmitStepThree": "<span class=\"font-weight-bold\">3.</span> Visitors are redirected to the content on the original website.",
"ChooseYourContentType": "Please choose the way you want to add your content.",
"PostContentViaGithub": "I want to add my article with <span class=\"font-weight-bold\"><i class=\"fa fa-github\"></i> GitHub</span> in accordance with the markdown rules.",
"PostContentViaYoutube": "I want to share my videos available on <span class=\"font-weight-bold\"><i class=\"fa fa-youtube\"></i> Youtube</span> here.",
"PostContentViaExternalSource": "I want to add the content I published on <span class=\"font-weight-bold\">another platform</span> here.",
"GitHubUserNameValidationMessage": "Your Github username can not include whitespace, please be sure your Github username is correct.",
"PersonalSiteUrlValidationMessage": "Your personal site URL can not include whitespace, please be sure your personal site URL is correct.",
"TwitterUserNameValidationMessage": "Your Twitter username can not include whitespace, please be sure your Twitter username is correct.",
"LinkedinUrlValidationMessage": "Your Linkedin URL can not include whitespace, please be sure your Linkedin URL is correct."
} }
} }

4
common.props

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

9
docs/en/Application-Services.md

@ -43,12 +43,14 @@ public class Book : AggregateRoot<Guid>
{ {
if (string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
{ {
throw new ArgumentException($"name can not be empty or white space!"); throw new ArgumentException(
$"name can not be empty or white space!");
} }
if (name.Length > MaxNameLength) if (name.Length > MaxNameLength)
{ {
throw new ArgumentException($"name can not be longer than {MaxNameLength} chars!"); throw new ArgumentException(
$"name can not be longer than {MaxNameLength} chars!");
} }
return name; return name;
@ -349,8 +351,9 @@ public class DistrictAppService
protected async override Task<District> GetEntityByIdAsync(DistrictKey id) protected async override Task<District> GetEntityByIdAsync(DistrictKey id)
{ {
var queryable = await Repository.GetQueryableAsync();
return await AsyncQueryableExecuter.FirstOrDefaultAsync( return await AsyncQueryableExecuter.FirstOrDefaultAsync(
Repository.Where(d => d.CityId == id.CityId && d.Name == id.Name) queryable.Where(d => d.CityId == id.CityId && d.Name == id.Name)
); );
} }
} }

7
docs/en/AspNet-Boilerplate-Migration-Guide.md

@ -184,7 +184,7 @@ public class PersonAppService : ApplicationService, IPersonAppService
} }
```` ````
ABP Framework's repository doesn't have this method. Instead, it implements the `IQueryable` itself. So, you can directly use LINQ on the repository: ABP Framework's repository have `GetQueryableAsync` instead:
````csharp ````csharp
public class PersonAppService : ApplicationService, IPersonAppService public class PersonAppService : ApplicationService, IPersonAppService
@ -198,14 +198,15 @@ public class PersonAppService : ApplicationService, IPersonAppService
public async Task DoIt() public async Task DoIt()
{ {
var people = await _personRepository var queryable = await _personRepository.GetQueryableAsync();
var people = await queryable
.Where(p => p.BirthYear > 2000) //Use LINQ extension methods .Where(p => p.BirthYear > 2000) //Use LINQ extension methods
.ToListAsync(); .ToListAsync();
} }
} }
```` ````
> Note that in order to use the async LINQ extension methods (like `ToListAsync` here), you may need to depend on the database provider (like EF Core) since these methods are defined in the database provider package, they are not standard LINQ methods. > Note that in order to use the async LINQ extension methods (like `ToListAsync` here), you may need to depend on the database provider (like EF Core) since these methods are defined in the database provider package, they are not standard LINQ methods. See the [repository document](Repositories.md) for alternative approaches for async query execution.
#### FirstOrDefault(predicate), Single()... Methods #### FirstOrDefault(predicate), Single()... Methods

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

@ -144,7 +144,7 @@ public virtual async Task<IdentityUser> FindByNormalizedUserNameAsync(
bool includeDetails = true, bool includeDetails = true,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
return await DbSet return await (await GetDbSetAsync())
.IncludeDetails(includeDetails) .IncludeDetails(includeDetails)
.FirstOrDefaultAsync( .FirstOrDefaultAsync(
u => u.NormalizedUserName == normalizedUserName, u => u.NormalizedUserName == normalizedUserName,
@ -175,14 +175,15 @@ public static IQueryable<IdentityUser> IncludeDetails(
} }
```` ````
* **Do** use the `IncludeDetails` extension method in the repository methods just like used in the example code above (see FindByNormalizedUserNameAsync). * **Do** use the `IncludeDetails` extension method in the repository methods just like used in the example code above (see `FindByNormalizedUserNameAsync`).
- **Do** override `WithDetails` method of the repository for aggregates root which have **sub collections**. Example: - **Do** override `WithDetails` method of the repository for aggregates root which have **sub collections**. Example:
````C# ````C#
public override IQueryable<IdentityUser> WithDetails() public override async Task<IQueryable<IdentityUser>> WithDetailsAsync()
{ {
return GetQueryable().IncludeDetails(); // Uses the extension method defined above // Uses the extension method defined above
return (await GetQueryableAsync()).IncludeDetails();
} }
```` ````

6
docs/en/Best-Practices/MongoDB-Integration.md

@ -128,7 +128,7 @@ public async Task<IdentityUser> FindByNormalizedUserNameAsync(
bool includeDetails = true, bool includeDetails = true,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
return await GetMongoQueryable() return await (await GetMongoQueryableAsync())
.FirstOrDefaultAsync( .FirstOrDefaultAsync(
u => u.NormalizedUserName == normalizedUserName, u => u.NormalizedUserName == normalizedUserName,
GetCancellationToken(cancellationToken) GetCancellationToken(cancellationToken)
@ -139,8 +139,8 @@ public async Task<IdentityUser> FindByNormalizedUserNameAsync(
`GetCancellationToken` fallbacks to the `ICancellationTokenProvider.Token` to obtain the cancellation token if it is not provided by the caller code. `GetCancellationToken` fallbacks to the `ICancellationTokenProvider.Token` to obtain the cancellation token if it is not provided by the caller code.
* **Do** ignore the `includeDetails` parameters for the repository implementation since MongoDB loads the aggregate root as a whole (including sub collections) by default. * **Do** ignore the `includeDetails` parameters for the repository implementation since MongoDB loads the aggregate root as a whole (including sub collections) by default.
* **Do** use the `GetMongoQueryable()` method to obtain an `IQueryable<TEntity>` to perform queries wherever possible. Because; * **Do** use the `GetMongoQueryableAsync()` method to obtain an `IQueryable<TEntity>` to perform queries wherever possible. Because;
* `GetMongoQueryable()` method automatically uses the `ApplyDataFilters` method to filter the data based on the current data filters (like soft delete and multi-tenancy). * `GetMongoQueryableAsync()` method automatically uses the `ApplyDataFilters` method to filter the data based on the current data filters (like soft delete and multi-tenancy).
* Using `IQueryable<TEntity>` makes the code as much as similar to the EF Core repository implementation and easy to write and read. * Using `IQueryable<TEntity>` makes the code as much as similar to the EF Core repository implementation and easy to write and read.
* **Do** implement data filtering if it is not possible to use the `GetMongoQueryable()` method. * **Do** implement data filtering if it is not possible to use the `GetMongoQueryable()` method.

18
docs/en/Best-Practices/Repositories.md

@ -42,24 +42,6 @@ Task<IdentityUser> FindByNormalizedUserNameAsync(
); );
```` ````
* **Do** create a **synchronous extension** method for each asynchronous repository method. Example:
````C#
public static class IdentityUserRepositoryExtensions
{
public static IdentityUser FindByNormalizedUserName(
this IIdentityUserRepository repository,
[NotNull] string normalizedUserName)
{
return AsyncHelper.RunSync(
() => repository.FindByNormalizedUserNameAsync(normalizedUserName)
);
}
}
````
This will allow synchronous code to use the repository methods easier.
* **Do** add an optional `bool includeDetails = true` parameter (default value is `true`) for every repository method which returns a **single entity**. Example: * **Do** add an optional `bool includeDetails = true` parameter (default value is `true`) for every repository method which returns a **single entity**. Example:
````C# ````C#

241
docs/en/Blog-Posts/2021-01-14 v4_2_Preview/POST.md

@ -0,0 +1,241 @@
# ABP Framework 4.2 RC Has Been Published
Today, we have released the [ABP Framework](https://abp.io/) and the [ABP Commercial](https://commercial.abp.io/) 4.2.0 RC (Release Candidate). This blog post introduces the new features and important changes in this new version.
> **The planned release date for the [4.2.0 final](https://github.com/abpframework/abp/milestone/48) version is January 28, 2021**.
## Get Started with the 4.2 RC
If you want to try the version `4.2.0` today, follow the steps below;
1) **Upgrade** the ABP CLI to the version `4.2.0-rc.2` using a command line terminal:
````bash
dotnet tool update Volo.Abp.Cli -g --version 4.2.0-rc.2
````
**or install** if you haven't installed before:
````bash
dotnet tool install Volo.Abp.Cli -g --version 4.2.0-rc.2
````
2) Create a **new application** with the `--preview` option:
````bash
abp new BookStore --preview
````
See the [ABP CLI documentation](https://docs.abp.io/en/abp/latest/CLI) for all the available options.
> You can also use the *Direct Download* tab on the [Get Started](https://abp.io/get-started) page by selecting the **Preview checkbox**.
## What's new with the ABP Framework 4.2
## IRepository.GetQueryableAsync()
> **This version comes with an important change about using `IQueryable` features over the [repositories](https://docs.abp.io/en/abp/4.2/Repositories). It is suggested to read this section carefully and apply in your applications.**
`IRepository` interface inherits `IQueryable`, so you can directly use the standard LINQ extension methods, like `Where`, `OrderBy`, `First`, `Sum`... etc.
**Example: Using LINQ directly over the repository object**
````csharp
public class BookAppService : ApplicationService, IBookAppService
{
private readonly IRepository<Book, Guid> _bookRepository;
public BookAppService(IRepository<Book, Guid> bookRepository)
{
_bookRepository = bookRepository;
}
public async Task DoItInOldWayAsync()
{
//Apply any standard LINQ extension method
var query = _bookRepository
.Where(x => x.Price > 10)
.OrderBy(x => x.Name);
//Execute the query asynchronously
var books = await AsyncExecuter.ToListAsync(query);
}
}
````
*See [the documentation](https://docs.abp.io/en/abp/4.2/Repositories#iqueryable-async-operations) if you wonder what is the `AsyncExecuter`.*
Beginning from the version 4.2, the recommended way is using `IRepository.GetQueryableAsync()` to obtain an `IQueryable`, then use the LINQ extension methods over it.
**Example: Using the new GetQueryableAsync method**
````csharp
public async Task DoItInNewWayAsync()
{
//Use GetQueryableAsync to obtain the IQueryable<Book> first
var queryable = await _bookRepository.GetQueryableAsync();
//Then apply any standard LINQ extension method
var query = queryable
.Where(x => x.Price > 10)
.OrderBy(x => x.Name);
//Finally, execute the query asynchronously
var books = await AsyncExecuter.ToListAsync(query);
}
````
ABP may start a database transaction when you get an `IQueryable` (If current [Unit Of Work](https://docs.abp.io/en/abp/latest/Unit-Of-Work) is transactional). In this new way, it is possible to **start the database transaction in an asynchronous way**. Previously, we could not get the advantage of asynchronous while starting the transactions.
> **The new way has a significant performance and scalability gain. The old usage (directly using LINQ over the repositories) will be removed in the next major version.** You have a lot of time for the change, but we recommend to immediately take the action since the old usage has a big scalability problem.
#### About IRepository Async Extension Methods
Using IRepository Async Extension Methods has no such a problem. The examples below are pretty fine:
````csharp
var countAll = await _personRepository
.CountAsync();
var count = await _personRepository
.CountAsync(x => x.Name.StartsWith("A"));
var book1984 = await _bookRepository
.FirstOrDefaultAsync(x => x.Name == "John");
````
See the [repository documentation](https://docs.abp.io/en/abp/4.2/Repositories#iqueryable-async-operations) to understand the relation between `IQueryable` and asynchronous operations.
### Repository Bulk Operations
This version adds the following methods to the repositories:
* `InsertManyAsync`
* `UpdateManyAsync`
* `DeleteManyAsync`
The purpose of these methods to insert, update or delete many entities in one call with a better performance.
Currently, **MongoDB** provider implements these methods as a single bulk operation since MongoDB API natively supports. But current **Entity Framework Core** implementation is not a real bulk operation. Instead, it does its best with the native API of the EF Core. If you want to implement in a more performant way, you can [customize the bulk operations](https://docs.abp.io/en/abp/4.2/Entity-Framework-Core#customize-bulk-operations) with your own implementation or by using a library. We could find a good open source library for EF Core 5.0 to implement it.
### Selecting DBMS on Template Creation
[ABP CLI](https://docs.abp.io/en/abp/4.2/CLI#new) now has an option to specify the DBMS when you use EF Core as the database provider.
**Example: Select MySQL as the DBMS**
````bash
abp new BookStore -dbms mysql --preview
````
Available options: `SqlServer` (default), `MySQL`, `SQLite`, `Oracle-Devart`, `PostgreSQL`. See the [documentation](https://docs.abp.io/en/abp/latest/Entity-Framework-Core-Other-DBMS) to use any other DBMS or switch the DBMS later.
One change related to this feature is that: Now, the startup template doesn't come with an **initial migration** file. This is because the database migrations are different based on your DBMS preference and should be re-created. However, when you first run the `.DbMigrator` application, it will create the initial migration and create the database just like before.
> See The Initial Migration section in the [Getting Started](https://docs.abp.io/en/abp/4.2/Getting-Started-Running-Solution?DB=EF#database-migrations) document if you have problems on running the `.DbMigrator` application first time.
### Swagger UI Login / Authorization
Testing the swagger UI was requiring some additional work, especially your authentication server is separated from the application that hosts the Swagger UI.
With the version 4.2, the startup templates come with the authorization pre-configured for you. An Authorize button is available when you open the Swagger UI:
![swagger-authorize](swagger-authorize.png)
When you click, it opens a modal to authorize:
![swagger-authorize](swagger-authorize-modal.png)
When you click to the Authorize button here, you are redirected to the login page to login with your username and password (default username is `admin` and password is `1q2w3E*`).
> Remember to select the Scopes (typically **select all**) you want to use before clicking to the Authorize button.
### Angular Unit Testing
We've improved the modules and the startup template to setup and write unit tests easier with the Angular UI. See the [Angular Unit Testing document](https://docs.abp.io/en/abp/4.2/UI/Angular/Testing) for details.
### Other News
* Improved HTTP **request-response performance** by resolving dependencies in a deferred way in the action/page filters, interceptors and some other services.
* Removed `MultipleActiveResultSets` from connection strings for new templates for SQL Server, since the new EF Core gives a warning when using it. If you want to use it, you need to change the connection string yourself.
* Added `HardDeleteAsync` extension method that takes a predicate to delete multiple entities. This extension method is available if the entity [Soft Delete](https://docs.abp.io/en/abp/latest/Data-Filtering).
* Implemented the [Page Alerts](https://docs.abp.io/en/abp/4.2/UI/Angular/Page-Alerts) for the **Angular UI**.
* Implemented [Page Progress](https://docs.abp.io/en/abp/4.2/UI/Blazor/Page-Progress) for the **Blazor UI**. It automatically shows an undetermined progress bar on top of the page while performing an AJAX request. It also proves an API to you if you need to show/hide the progress bar in your code.
## What's new with the ABP Commercial 4.2
### Microservice Startup Template
The new [Microservice Startup Template](https://docs.abp.io/en/commercial/4.2/startup-templates/microservice/index) is a generic solution to start a new microservice solution.
While we accept that every microservice solution will be different and every system has its own design requirements and trade-offs, we believe such a startup solution is a very useful starting point for most of the solutions, and a useful example for others.
![microservice-template-diagram](microservice-template-diagram.png)
*Figure: A simplified overall diagram of the microservice solution.*
You can [follow the documentation](https://docs.abp.io/en/commercial/4.2/startup-templates/microservice/index) to get started with this startup template. **This template should be considered as an early release**. We will improve it and write a lot of guides.
If you want to use the ABP Suite to create your solution, then you need to first upgrade it:
````bash
abp suite update
````
If you want, you can directly create a new solution from the command line:
````bash
abp new Volosoft.MyMicroserviceSystem -t microservice-pro --preview
````
Company Name is optional. Solution name could be *MyMicroserviceSystem* for this example.
### Public Website in the Startup Templates
As mentioned in the previous release post, we've added a *Public Website* application to the startup templates. It is configured to authenticate through the IdentityServer with a single sign-on system.
You can use this application to create a landing page for your actual application or a corporate website for your business. An example screenshot:
![public-website](public-website.jpg)
It uses the same *Lepton Theme*, so you can apply [all the styles](https://commercial.abp.io/themes). The Public Website has a different layout and also has a different setting for the styling (that can be configured in the *Settings / Lepton Theme* page of the main web application).
> *Public Website* is optional and you need to select the "Public Website" option while creating a new solution using the ABP Suite, or use the `--with-public-website` option while using the `abp new` CLI command.
### Easy CRM Blazor UI
[Easy CRM](https://docs.abp.io/en/commercial/latest/samples/easy-crm) is an example application built with the ABP Commercial. MVC (Razor Pages) and Angular UI implementations were already provided. With the version 4.2, we are providing the Blazor UI implementation for this application.
![easy-crm](easy-crm.png)
### Other News
* Implemented Iyzico as a payment gateway provider for the [payment module](https://commercial.abp.io/modules/Volo.Payment) in addition to Paypal, Stripe, 2Checkout and Payu providers.
* ABP Suite supports the new microservice template creation, public website and DBMS selection options.
* Swagger authorization and other features mentioned in the ABP Framework section are already implemented for the ABP Commercial too.
## ABP Community News
### Sharing Video Contents
[community.abp.io](https://community.abp.io/) is a place to share ABP related contents. It started with publishing articles. Now, it supports to publish video contents. [See this example](https://community.abp.io/articles/be-a-superhero-on-day-1-with-abp.io-wvifcy9s). All you need to do is to create a video and upload to YouTube. Then you can [submit](https://community.abp.io/articles/submit) the YouTube link to the ABP Community website.
### Multi-language support
We planned ABP Community to publish English-only contents. However, we see that people want to share contents in other languages too. Now, **it is possible to submit a content in any language**. Just select the Language option while submitting your content.
**When you submit a non-English content, it is not visible to all the visitors by default**. Visitors can see a non-English content only if their browser language or the selected language matches to the content language (there is a language selection at the end of the website).
### External Contents
If you want to publish your content anywhere else, but want to post a link of your content, you can select *External Content* option while submitting the post. For example, [this article](https://community.abp.io/articles/aspnet-boilerplate-to-abp-framework-xml-to-json-localization-conversion-0mxyjrzj) is an external article and also written in Chinese language.
## About the Next Release
The next feature version will be 4.3.0. It is planned to release the 4.3 RC (Release Candidate) on March 11 and the final version on March 25, 2021.
We decided to slow down the feature development for the [next milestone](https://github.com/abpframework/abp/milestone/49). We will continue to improve the existing features and introduce new ones, sure, but wanted to have more time for the planning, documentation, creating guides and improving the development experience.
## Feedback
Please check out the ABP Framework 4.2.0 RC and [provide feedback](https://github.com/abpframework/abp/issues/new) to help us to release a more stable version. **The planned release date for the [4.2.0 final](https://github.com/abpframework/abp/milestone/48) version is January 28, 2021**.

BIN
docs/en/Blog-Posts/2021-01-14 v4_2_Preview/easy-crm.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

BIN
docs/en/Blog-Posts/2021-01-14 v4_2_Preview/microservice-template-diagram.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

BIN
docs/en/Blog-Posts/2021-01-14 v4_2_Preview/public-website.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 284 KiB

BIN
docs/en/Blog-Posts/2021-01-14 v4_2_Preview/swagger-authorize-modal.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

BIN
docs/en/Blog-Posts/2021-01-14 v4_2_Preview/swagger-authorize.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

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

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

17
docs/en/CSRF-Anti-Forgery.md

@ -144,4 +144,19 @@ Let's talk about why.
First, take a look at [Angular's code](https://github.com/angular/angular/blob/master/packages/common/http/src/xsrf.ts#L81) First, take a look at [Angular's code](https://github.com/angular/angular/blob/master/packages/common/http/src/xsrf.ts#L81)
It does not intercept any request that starts with `http://` or `https://`. There is a good reason for that. Any cross-site request does not need this token for security. This verification is only valid if the request is made to the same domain from which the web page is served. So, simply put, if you serve everything from a single domain, you just use a relative path. It does not intercept any request that starts with `http://` or `https://`. There is a good reason for that. Any cross-site request does not need this token for security. This verification is only valid if the request is made to the same domain from which the web page is served. So, simply put, if you serve everything from a single domain, you just use a relative path.
If you serve your APIs from the root, i.e. no context root (https://testdomain.com/api/identity/users), leave `url` empty as follows:
```typescript
export const environment = {
production: true,
// ....
apis: {
default: {
url: '', // <- should be empty string, not '/'
// ...
},
},
} as Config.Environment;
```

103
docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/POST.md

@ -0,0 +1,103 @@
## Using MatBlazor UI Components With the ABP Framework
Hi, in this step by step article, I will show you how to integrate [MatBlazor](https://www.matblazor.com/), a blazor UI components into ABP Framework-based applications.
![example-result](example-result.png)
*(A screenshot from the example application developed in this article)*
## Create the Project
> First thing is to create the project. ABP Framework offers startup templates to get into business faster.
In this article, I will create a new startup template with EF Core as a database provider and Blazor for UI framework. But if you already have a project with Blazor UI, you don't need to create a new startup template, you can directly implement the following steps to your existing project.
> If you already have a project with the Blazor UI, you can skip this section.
* Before starting the development, we will create a new solution named `MatBlazorSample` (or whatever you want). We will create a new startup template with EF Core as a database provider and Blazor for UI framework by using [ABP CLI](https://docs.abp.io/en/abp/latest/CLI):
````bash
abp new MatBlazorSample -u blazor
````
This will create new project inside of `aspnet-core`, so:
````bash
cd aspnet-core
````
and
````bash
dotnet restore
````
* Our project boilerplate will be ready after the download is finished. Then, we can open the solution in the Visual Studio (or any other IDE) and run the `MatBlazorSample.DbMigrator` to create the database and seed initial data (which creates the admin user, admin role, permissions etc.)
![initial-project](initial-project.png)
* After database and initial data created,
* Run the `MatBlazorSample.HttpApi.Host` to see our server side working and
* Run the `MatBlazorSample.Blazor` to see our UI working properly.
> _Default login credentials for admin: username is **admin** and password is **1q2w3E\***_
## Install MatBlazor
You can follow [this documentation](https://www.matblazor.com/) to install MatBlazor packages into your computer.
### Adding MatBlazor NuGet Packages
```bash
Install-Package MatBlazor
```
### Register MatBlazor Resources
1. Add the following line to the HEAD section of the `wwwroot/index.html` file within the `MatBlazorSample.Blazor` project:
```Razor
<head>
<!--...-->
<script src="_content/MatBlazor/dist/matBlazor.js"></script>
<link href="_content/MatBlazor/dist/matBlazor.css" rel="stylesheet" />
</head>
```
2. In the `MatBlazorSampleBlazorModule` class, call the `AddMatBlazor()` method from your project's `ConfigureServices()` method:
```csharp
public override void ConfigureServices(ServiceConfigurationContext context)
{
var environment = context.Services.GetSingletonInstance<IWebAssemblyHostEnvironment>();
var builder = context.Services.GetSingletonInstance<WebAssemblyHostBuilder>();
// ...
builder.Services.AddMatBlazor();
}
```
3. Register the **MatBlazorSample.Blazor** namespace in the `_Imports.razor` file:
```Razor
@using MatBlazor
```
## The Sample Application
We have created a sample application with [Table](https://www.matblazor.com/Table) example.
### The Source Code
You can download the source code from [here](https://github.com/abpframework/abp-samples/tree/master/MatBlazorSample).
The related files for this example are marked in the following screenshots.
![table-app-contract](table-app-contract.png)
![table-application](table-application.png)
![table-web](table-web.png)
## Conclusion
In this article, I've explained how to use [MatBlazor](https://www.matblazor.com/) components in your application. ABP Framework is designed so that it can work with any UI library/framework.

BIN
docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/example-result.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/initial-project.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/table-app-contract.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/table-application.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Integrate-the-MatBlazor-Blazor-Component/table-web.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

343
docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/POST.md

@ -0,0 +1,343 @@
# How to Use PrimeNG Components with the ABP Angular UI
## Introduction
In this article, we will use components of the [PrimeNG](https://www.primefaces.org/primeng/) that is a popular UI component library for Angular with the ABP Framework Angular UI that will be generated via [ABP CLI](https://docs.abp.io/en/abp/latest/CLI).
We will create an organization units page and use PrimeNG's [OrganizationChart](https://primefaces.org/primeng/showcase/#/organizationchart) and [Table](https://primefaces.org/primeng/showcase/#/table) components on the page.
![Introduction](intro.gif)
<small>The UI shown above contains many PrimeNG components. You can reach the source code of this rich UI. Take a look at the source code section below.</small>
> This article does not cover any backend code. I used mock data to provide data source to the components.
## Pre-Requirements
The following tools should be installed on your development machine:
* [.NET Core 5.0+](https://www.microsoft.com/net/download/dotnet-core/)
* [Node v12 or v14](https://nodejs.org/)
* [VS Code](https://code.visualstudio.com/) or another IDE
## Source Code
I have prepared a sample project that contains more PrimeNG components than described in this article. You can download the source code [on GitHub](https://github.com/abpframework/abp-samples/tree/master/PrimengSample).
## Creating a New Solution
In this step, we will create a new solution that contains Angular UI and backend startup templates. If you have a startup template with Angular UI, you can skip this step.
Run the following command to install the ABP CLI:
```bash
dotnet tool install -g Volo.Abp.Cli
```
...or update:
```bash
dotnet tool update -g Volo.Abp.Cli
```
Create a new solution named `AbpPrimengSample` by running the following command:
```bash
abp new AbpPrimengSample -u angular -csf
```
See the [ABP CLI documentation](https://docs.abp.io/en/abp/latest/CLI) for all available options.
You can also use the Direct Download tab on the [Get Started](https://abp.io/get-started) page.
## Running the Solution
You can run the solution as described in [here](https://docs.abp.io/en/abp/latest/Getting-Started-Running-Solution?UI=NG&DB=EF&Tiered=No).
## PrimeNG Setup
Open the `angular` folder and run the following command to install packages:
```bash
npm install
```
Next, we need to install `primeng` and required packages (`primeicons` and `@angular/cdk`) for the library. Run the command below to install these packages:
```bash
npm install primeng primeicons @angular/cdk --save
```
The packages we have installed;
- `primeng` is the main package that is a component library.
- `primeicons` is an icon font library. Many PrimeNG components use this font internally.
- `@angular/cdk` is a component dev kit created by the Angular team. Some PrimeNG modules depend on it.
As the last step of the setup, we should add the required style files for the library to `angular.json`:
```js
//angular.json
"projects": {
"AbpPrimengSample": {
//...
"styles": {
"node_modules/primeicons/primeicons.css",
"node_modules/primeng/resources/themes/saga-blue/theme.css",
"node_modules/primeng/resources/primeng.min.css",
//...other styles
}
}
}
```
We have added the `primeng.min.css`, Saga Blue theme's `theme.css`, and `primeicons.css` files to the project. You can choose another theme instead of the Sage Blue. See available themes on the [Get Started](https://www.primefaces.org/primeng/showcase/#/setup) document of the PrimeNG.
> You have to restart the running `ng serve` process to see the effect of the changes you made in the `angular.json`.
## Creating the Organization Units Page
Run the following command to create a new module named `OrganizationUnits`:
```bash
npm run ng -- generate module organization-units --route organization-units --module app.module
```
Then open the `src/route.provider.ts` and add a new route as an array element to add a navigation link labeled "Organization Units" to the menu:
```js
//route.provider.ts
import { eThemeSharedRouteNames } from '@abp/ng.theme.shared';
//...
routesService.add([
//...
{
path: '/organization-units',
name: 'Organization Units',
parentName: eThemeSharedRouteNames.Administration,
iconClass: 'fas fa-sitemap',
layout: eLayoutType.application,
},
]);
```
We have created a lazy-loadable module and defined a menu navigation link. We can navigate to the page as shown below:
![organization units menu navigation item](organization-units-menu-item.jpg)
## Using the PrimeNG Components
### Implementing the Organization Chart Component
When you would like to use any component from PrimeNG, you have to import the component's module to your module. Since we will use the `OrganizationChart` on the organization units page, we need to import `OrganizationChartModule` into `OrganizationUnitsModule`.
Open the `src/organization-units/organization-units.module.ts` and add the `OrganizationChartModule` to the imports array as shown below:
```js
import { OrganizationChartModule } from 'primeng/organizationchart';
//...
@NgModule({
//...
imports: [
//...
OrganizationChartModule
],
})
export class OrganizationUnitsModule {}
```
> Since NGCC need to work in some cases, restarting the `ng serve` process would be good when you import any modules from `primeng` package to your module.
Let's define a mock data source for the `OrganizationChartComponent` and add the component to the page.
Open the `src/organization-units/organization-units.component.ts` and add two variables as shown below:
```js
//...
import { TreeNode } from 'primeng/api';
@Component(/* component metadata*/)
export class OrganizationUnitsComponent implements OnInit {
//...
organizationUnits: TreeNode[] = [
{
label: 'Management',
expanded: true,
children: [
{
label: 'Selling',
expanded: true,
children: [
{
label: 'Customer Relations',
},
{
label: 'Marketing',
},
],
},
{
label: 'Supporting',
expanded: true,
children: [
{
label: 'Buying',
},
{
label: 'Human Resources',
},
],
},
],
},
];
selectedUnit: TreeNode;
```
- First variable is `organizationUnits`. It provides mock data source to `OrganizationChartComponent`.
- Second variable is `selectedUnit`. It keeps chosen unit on the chart.
Then, open the `src/organization-units/organization-units.component.html` and replace the file content with the following:
```html
<div class="card">
<div class="card-header">
<h5>Organization Units</h5>
</div>
<div class="card-body">
<p-organizationChart
[value]="organizationUnits"
selectionMode="single"
[(selection)]="selectedUnit"
></p-organizationChart>
</div>
</div>
```
We have implemented the `OrganizationChart`. The final UI looks like below:
![organization chart](organization-chart.jpg)
## Implementing the Table Component
In order to use the `TableComponent`, we have to import the `TableModule` to the `OrganizationUnitsModule`.
Open the `organization-units.module.ts` and add `TableModule` to the imports array as shown below:
```js
import { TableModule } from 'primeng/table';
//...
@NgModule({
//...
imports: [
//...
TableModule
],
})
export class OrganizationUnitsModule {}
```
Open the `organization-units.component.ts` and add a variable named `members` with initial value and add a getter named `tableData` as shown below:
```js
//...
export class OrganizationUnitsComponent implements OnInit {
//...
members = [
{
fullName: 'John Doe',
username: 'John.Doe',
phone: '+1-202-555-0125',
email: 'john.doe@example.com',
parent: 'Customer Relations',
},
{
fullName: 'Darrion Walter',
username: 'Darrion.Walter',
phone: '+1-262-155-0355',
email: 'Darrion_Walter@example.com',
parent: 'Marketing',
},
{
fullName: 'Rosa Labadie',
username: 'Rosa.Labadie',
phone: '+1-262-723-2255',
email: 'Rosa.Labadie@example.com',
parent: 'Marketing',
},
{
fullName: 'Adelle Hills',
username: 'Adelle.Hills',
phone: '+1-491-112-9011',
email: 'Adelle.Hills@example.com',
parent: 'Buying',
},
{
fullName: 'Brian Hane',
username: 'Brian.Hane',
phone: '+1-772-509-1823',
email: 'Brian.Hane@example.com',
parent: 'Human Resources',
},
];
get tableData() {
return this.members.filter(user => user.parent === this.selectedUnit.label);
}
```
What we have done above?
- We defined a variable named `members` to provide mock data to the table.
- We have defined a getter named `tableData` to provide filtered data source to the table using `members` variable.
We are now ready to add the table to the HTML template.
Open the `organization-units.component.html`, find the `p-organizationChart` tag and place the following code to the bottom of this tag:
```html
<div class="p-3" *ngIf="selectedUnit">
<h6>Members of {{ selectedUnit.label }}</h6>
<p-table [value]="tableData">
<ng-template pTemplate="header">
<tr>
<th>Name</th>
<th>Username</th>
<th>Email</th>
<th>Phone</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-member>
<tr>
<td>{{ member.fullName }}</td>
<td>{{ member.username }}</td>
<td>{{ member.email }}</td>
<td>{{ member.phone }}</td>
</tr>
</ng-template>
</p-table>
</div>
```
We have added a new `div` that contains the `TableComponent`. The table appears when an organization unit is selected.
The table contains 4 columns which are name, username, email, and phone for displaying the members' information.
After adding the table, the final UI looks like this:
![PrimeNG TableComponent](table.gif)
## Conclusion
We have implemented the PrimeNG component library on the ABP Angular UI project and used two components on a page in a short time. You can use any PrimeNG components by following the documentation. The ABP Angular UI will not block you in any case.

BIN
docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/intro.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/organization-chart.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/organization-units-menu-item.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
docs/en/Community-Articles/2021-01-20-How-to-Use-PrimeNG-Components-with-the-ABP-Angular-UI/table.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 KiB

2
docs/en/Dependency-Injection.md

@ -1,6 +1,6 @@
# Dependency Injection # Dependency Injection
ABP's Dependency Injection system is developed based on Microsoft's [dependency injection extension](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection) library (Microsoft.Extensions.DependencyInjection nuget package). So, it's documentation is valid in ABP too. ABP's Dependency Injection system is developed based on Microsoft's [dependency injection extension](https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96) library (Microsoft.Extensions.DependencyInjection nuget package). So, it's documentation is valid in ABP too.
> While ABP has no core dependency to any 3rd-party DI provider, it's required to use a provider that supports dynamic proxying and some other advanced features to make some ABP features properly work. Startup templates come with Autofac installed. See [Autofac integration](Autofac-Integration.md) document for more information. > While ABP has no core dependency to any 3rd-party DI provider, it's required to use a provider that supports dynamic proxying and some other advanced features to make some ABP features properly work. Startup templates come with Autofac installed. See [Autofac integration](Autofac-Integration.md) document for more information.

12
docs/en/Domain-Driven-Design-Implementation-Guide.md

@ -754,7 +754,8 @@ namespace IssueTracking.Issues
{ {
var daysAgo30 = DateTime.Now.Subtract(TimeSpan.FromDays(30)); var daysAgo30 = DateTime.Now.Subtract(TimeSpan.FromDays(30));
return await DbSet.Where(i => var dbSet = await GetDbSetAsync();
return await dbSet.Where(i =>
//Open //Open
!i.IsClosed && !i.IsClosed &&
@ -906,7 +907,8 @@ public class EfCoreIssueRepository :
public async Task<List<Issue>> GetIssuesAsync(ISpecification<Issue> spec) public async Task<List<Issue>> GetIssuesAsync(ISpecification<Issue> spec)
{ {
return await DbSet var dbSet = await GetDbSetAsync();
return await dbSet
.Where(spec.ToExpression()) .Where(spec.ToExpression())
.ToListAsync(); .ToListAsync();
} }
@ -952,8 +954,9 @@ public class IssueAppService : ApplicationService, IIssueAppService
public async Task DoItAsync() public async Task DoItAsync()
{ {
var queryable = await _issueRepository.GetQueryableAsync();
var issues = AsyncExecuter.ToListAsync( var issues = AsyncExecuter.ToListAsync(
_issueRepository.Where(new InActiveIssueSpecification()) queryable.Where(new InActiveIssueSpecification())
); );
} }
} }
@ -996,8 +999,9 @@ public class IssueAppService : ApplicationService, IIssueAppService
public async Task DoItAsync(Guid milestoneId) public async Task DoItAsync(Guid milestoneId)
{ {
var queryable = await _issueRepository.GetQueryableAsync();
var issues = AsyncExecuter.ToListAsync( var issues = AsyncExecuter.ToListAsync(
_issueRepository queryable
.Where( .Where(
new InActiveIssueSpecification() new InActiveIssueSpecification()
.And(new MilestoneSpecification(milestoneId)) .And(new MilestoneSpecification(milestoneId))

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

@ -236,7 +236,8 @@ public class BookRepository
public async Task DeleteBooksByType(BookType type) public async Task DeleteBooksByType(BookType type)
{ {
await DbContext.Database.ExecuteSqlRawAsync( var dbContext = await GetDbContextAsync();
await dbContext.Database.ExecuteSqlRawAsync(
$"DELETE FROM Books WHERE Type = {(int)type}" $"DELETE FROM Books WHERE Type = {(int)type}"
); );
} }
@ -344,7 +345,7 @@ You have different options when you want to load the related entities while quer
#### Repository.WithDetails #### Repository.WithDetails
`IRepository.WithDetails(...)` can be used to include one relation collection/property to the query. `IRepository.WithDetailsAsync(...)` can be used to get an `IQueryable<T>` by including one relation collection/property.
**Example: Get an order with lines** **Example: Get an order with lines**
@ -355,7 +356,7 @@ using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services; using Volo.Abp.Domain.Services;
namespace MyCrm namespace AbpDemo.Orders
{ {
public class OrderManager : DomainService public class OrderManager : DomainService
{ {
@ -368,35 +369,39 @@ namespace MyCrm
public async Task TestWithDetails(Guid id) public async Task TestWithDetails(Guid id)
{ {
var query = _orderRepository //Get a IQueryable<T> by including sub collections
.WithDetails(x => x.Lines) var queryable = await _orderRepository.WithDetailsAsync(x => x.Lines);
.Where(x => x.Id == id);
//Apply additional LINQ extension methods
var query = queryable.Where(x => x.Id == id);
//Execute the query and get the result
var order = await AsyncExecuter.FirstOrDefaultAsync(query); var order = await AsyncExecuter.FirstOrDefaultAsync(query);
} }
} }
} }
```` ````
> `AsyncExecuter` is used to execute async LINQ extensions without depending on the EF Core. If you add EF Core NuGet package reference to your project, then you can directly use `await _orderRepository.WithDetails(x => x.Lines).FirstOrDefaultAsync()`. But, this time you depend on the EF Core in your domain layer. See the [repository document](Repositories.md) to learn more. > `AsyncExecuter` is used to execute async LINQ extensions without depending on the EF Core. If you add EF Core NuGet package reference to your project, then you can directly use `await query.FirstOrDefaultAsync()`. But, this time you depend on the EF Core in your domain layer. See the [repository document](Repositories.md) to learn more.
**Example: Get a list of orders with their lines** **Example: Get a list of orders with their lines**
````csharp ````csharp
public async Task TestWithDetails() public async Task TestWithDetails()
{ {
var query = _orderRepository //Get a IQueryable<T> by including sub collections
.WithDetails(x => x.Lines); var queryable = await _orderRepository.WithDetailsAsync(x => x.Lines);
var orders = await AsyncExecuter.ToListAsync(query); //Execute the query and get the result
var orders = await AsyncExecuter.ToListAsync(queryable);
} }
```` ````
> `WithDetails` method can get more than one expression parameter if you need to include more than one navigation property or collection. > `WithDetailsAsync` method can get more than one expression parameter if you need to include more than one navigation property or collection.
#### DefaultWithDetailsFunc #### DefaultWithDetailsFunc
If you don't pass any expression to the `WithDetails` method, then it includes all the details using the `DefaultWithDetailsFunc` option you provide. If you don't pass any expression to the `WithDetailsAsync` method, then it includes all the details using the `DefaultWithDetailsFunc` option you provide.
You can configure `DefaultWithDetailsFunc` for an entity in the `ConfigureServices` method of your [module](Module-Development-Basics.md) in your `EntityFrameworkCore` project. You can configure `DefaultWithDetailsFunc` for an entity in the `ConfigureServices` method of your [module](Module-Development-Basics.md) in your `EntityFrameworkCore` project.
@ -419,12 +424,15 @@ Then you can use the `WithDetails` without any parameter:
````csharp ````csharp
public async Task TestWithDetails() public async Task TestWithDetails()
{ {
var query = _orderRepository.WithDetails(); //Get a IQueryable<T> by including all sub collections
var orders = await AsyncExecuter.ToListAsync(query); var queryable = await _orderRepository.WithDetailsAsync();
//Execute the query and get the result
var orders = await AsyncExecuter.ToListAsync(queryable);
} }
```` ````
`WithDetails()` executes the expression you've setup as the `DefaultWithDetailsFunc`. `WithDetailsAsync()` executes the expression you've setup as the `DefaultWithDetailsFunc`.
#### Repository Get/Find Methods #### Repository Get/Find Methods
@ -466,7 +474,7 @@ public async Task TestWithDetails()
#### Alternatives #### Alternatives
The repository patters tries to encapsulate the EF Core, so your options are limited. If you need an advanced scenario, you can follow one of the options; The repository pattern tries to encapsulate the EF Core, so your options are limited. If you need an advanced scenario, you can follow one of the options;
* Create a custom repository method and use the complete EF Core API. * Create a custom repository method and use the complete EF Core API.
* Reference to the `Volo.Abp.EntityFrameworkCore` package from your project. In this way, you can directly use `Include` and `ThenInclude` in your code. * Reference to the `Volo.Abp.EntityFrameworkCore` package from your project. In this way, you can directly use `Include` and `ThenInclude` in your code.
@ -550,24 +558,15 @@ See also [lazy loading document](https://docs.microsoft.com/en-us/ef/core/queryi
In most cases, you want to hide EF Core APIs behind a repository (this is the main purpose of the repository pattern). However, if you want to access the `DbContext` instance over the repository, you can use `GetDbContext()` or `GetDbSet()` extension methods. Example: In most cases, you want to hide EF Core APIs behind a repository (this is the main purpose of the repository pattern). However, if you want to access the `DbContext` instance over the repository, you can use `GetDbContext()` or `GetDbSet()` extension methods. Example:
````csharp ````csharp
public class BookService public async Task TestAsync()
{ {
private readonly IRepository<Book, Guid> _bookRepository; var dbContext = await _orderRepository.GetDbContextAsync();
var dbSet = await _orderRepository.GetDbSetAsync();
public BookService(IRepository<Book, Guid> bookRepository) //var dbSet = dbContext.Set<Order>(); //Alternative, when you have the DbContext
{
_bookRepository = bookRepository;
}
public void Foo()
{
DbContext dbContext = _bookRepository.GetDbContext();
DbSet<Book> books = _bookRepository.GetDbSet();
}
} }
```` ````
* `GetDbContext` returns a `DbContext` reference instead of `BookStoreDbContext`. You can cast it, however in most cases you don't need it. * `GetDbContextAsync` returns a `DbContext` reference instead of `BookStoreDbContext`. You can cast it if you need. However, you don't need it in most cases.
> 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.
@ -742,32 +741,36 @@ If you have better logic or using an external library for bulk operations, you c
- You may use example template below: - You may use example template below:
```csharp ```csharp
public class MyCustomEfCoreBulkOperationProvider : IEfCoreBulkOperationProvider, ITransientDependency public class MyCustomEfCoreBulkOperationProvider
{ : IEfCoreBulkOperationProvider, ITransientDependency
public async Task DeleteManyAsync<TDbContext, TEntity>(IEfCoreRepository<TEntity> repository, {
IEnumerable<TEntity> entities, public async Task DeleteManyAsync<TDbContext, TEntity>(
bool autoSave, IEfCoreRepository<TEntity> repository,
CancellationToken cancellationToken) IEnumerable<TEntity> entities,
bool autoSave,
CancellationToken cancellationToken)
where TDbContext : IEfCoreDbContext where TDbContext : IEfCoreDbContext
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
// Your logic here. // Your logic here.
} }
public async Task InsertManyAsync<TDbContext, TEntity>(IEfCoreRepository<TEntity> repository, public async Task InsertManyAsync<TDbContext, TEntity>(
IEnumerable<TEntity> entities, IEfCoreRepository<TEntity> repository,
bool autoSave, IEnumerable<TEntity> entities,
CancellationToken cancellationToken) bool autoSave,
CancellationToken cancellationToken)
where TDbContext : IEfCoreDbContext where TDbContext : IEfCoreDbContext
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
// Your logic here. // Your logic here.
} }
public async Task UpdateManyAsync<TDbContext, TEntity>(IEfCoreRepository<TEntity> repository, public async Task UpdateManyAsync<TDbContext, TEntity>(
IEnumerable<TEntity> entities, IEfCoreRepository<TEntity> repository,
bool autoSave, IEnumerable<TEntity> entities,
CancellationToken cancellationToken) bool autoSave,
CancellationToken cancellationToken)
where TDbContext : IEfCoreDbContext where TDbContext : IEfCoreDbContext
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
@ -779,3 +782,4 @@ public class MyCustomEfCoreBulkOperationProvider : IEfCoreBulkOperationProvider,
## See Also ## See Also
* [Entities](Entities.md) * [Entities](Entities.md)
* [Repositories](Repositories.md)

50
docs/en/Getting-Started-Running-Solution.md

@ -25,53 +25,41 @@ Check the **connection string** in the `appsettings.json` file under the {{if Ti
} }
```` ````
The solution is configured to use **Entity Framework Core** with **MS SQL Server** by default. EF Core supports [various](https://docs.microsoft.com/en-us/ef/core/providers/) database providers, so you can use any supported DBMS. See [the Entity Framework integration document](Entity-Framework-Core.md) to learn how to [switch to another DBMS](Entity-Framework-Core-Other-DBMS.md). > **About the Connection Strings and Database Management Systems**
>
### Apply the Migrations > The solution is configured to use **Entity Framework Core** with **MS SQL Server** by default. However, if you've selected another DBMS using the `-dbms` parameter on the ABP CLI `new` command (like `-dbms MySQL`), the connection string might be different for you.
>
The solution uses the [Entity Framework Core Code First Migrations](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli). So, you need to apply migrations to create the database. There are two ways of applying the database migrations. > EF Core supports [various](https://docs.microsoft.com/en-us/ef/core/providers/) database providers and you can use any supported DBMS. See [the Entity Framework integration document](Entity-Framework-Core.md) to learn how to [switch to another DBMS](Entity-Framework-Core-Other-DBMS.md) if you need later.
#### Apply Migrations Using the DbMigrator ### Database Migrations
The solution comes with a `.DbMigrator` console application which applies migrations and also **seeds the initial data**. It is useful on **development** as well as on **production** environment. The solution uses the [Entity Framework Core Code First Migrations](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli). It comes with a `.DbMigrator` console application which **applies the migrations** and also **seeds the initial data**. It is useful on **development** as well as on **production** environment.
> `.DbMigrator` project has its own `appsettings.json`. So, if you have changed the connection string above, you should also change this one. > `.DbMigrator` project has its own `appsettings.json`. So, if you have changed the connection string above, you should also change this one.
Right click to the `.DbMigrator` project and select **Set as StartUp Project** ### The Initial Migration
![set-as-startup-project](images/set-as-startup-project.png)
Hit F5 (or Ctrl+F5) to run the application. It will have an output like shown below:
![db-migrator-output](images/db-migrator-output.png) `.DbMigrator` application automatically **creates the Initial migration** on first run.
> Initial [seed data](Data-Seeding.md) creates the `admin` user in the database (with the password is `1q2w3E*`) which is then used to login to the application. So, you need to use `.DbMigrator` at least once for a new database.
#### Using EF Core Update-Database Command **If you are using Visual Studio, you can skip to the *Running the DbMigrator* section.** However, other IDEs (e.g. Rider) may have problems for the first run since it adds the initial migration and compiles the project. In this case, open a command line terminal in the folder of the `.DbMigrator` project and run the following command:
Ef Core has `Update-Database` command which creates database if necessary and applies pending migrations. ````bash
dotnet run
{{ if UI == "MVC" }} ````
Right click to the {{if Tiered == "Yes"}}`.IdentityServer`{{else}}`.Web`{{end}} project and select **Set as StartUp project**:
{{ else if UI != "MVC" }} For the next time, you can just run it in your IDE as you normally do.
Right click to the `.HttpApi.Host` project and select **Set as StartUp Project**: ### Running the DbMigrator
{{ end }} Right click to the `.DbMigrator` project and select **Set as StartUp Project**
![set-as-startup-project](images/set-as-startup-project.png) ![set-as-startup-project](images/set-as-startup-project.png)
Open the **Package Manager Console**, select `.EntityFrameworkCore.DbMigrations` project as the **Default Project** and run the `Update-Database` command: Hit F5 (or Ctrl+F5) to run the application. It will have an output like shown below:
![package-manager-console-update-database](images/package-manager-console-update-database.png)
This will create a new database based on the configured connection string. ![db-migrator-output](images/db-migrator-output.png)
> **Using the `.DbMigrator` tool is the suggested way**, because it also seeds the initial data to be able to properly run the web application. > Initial [seed data](Data-Seeding.md) creates the `admin` user in the database (with the password is `1q2w3E*`) which is then used to login to the application. So, you need to use `.DbMigrator` at least once for a new database.
>
> If you just use the `Update-Database` command, you will have an empty database, so you can not login to the application since there is no initial admin user in the database. You can use the `Update-Database` command in development time when you don't need to seed the database. However, using the `.DbMigrator` application is easier and you can always use it to migrate the schema and seed the database.
{{ else if DB == "Mongo" }} {{ else if DB == "Mongo" }}

101
docs/en/Migration-Guides/Abp-4_2.md

@ -0,0 +1,101 @@
# ABP version 4.2 Migration Guide
This version has no breaking changes but there is an important change on the repositories that should be applied for your application for an important performance and scalability gain.
## IRepository.GetQueryableAsync
`IRepository` interface inherits `IQueryable`, so you can directly use the standard LINQ extension methods, like `Where`, `OrderBy`, `First`, `Sum`... etc.
**Example: Using LINQ directly over the repository object**
````csharp
public class BookAppService : ApplicationService, IBookAppService
{
private readonly IRepository<Book, Guid> _bookRepository;
public BookAppService(IRepository<Book, Guid> bookRepository)
{
_bookRepository = bookRepository;
}
public async Task DoItInOldWayAsync()
{
//Apply any standard LINQ extension method
var query = _bookRepository
.Where(x => x.Price > 10)
.OrderBy(x => x.Name);
//Execute the query asynchronously
var books = await AsyncExecuter.ToListAsync(query);
}
}
````
*See [the documentation](https://docs.abp.io/en/abp/4.2/Repositories#iqueryable-async-operations) if you wonder what is the `AsyncExecuter`.*
**Beginning from the version 4.2, the recommended way is using `IRepository.GetQueryableAsync()` to obtain an `IQueryable`, then use the LINQ extension methods over it.**
**Example: Using the new GetQueryableAsync method**
````csharp
public async Task DoItInNewWayAsync()
{
//Use GetQueryableAsync to obtain the IQueryable<Book> first
var queryable = await _bookRepository.GetQueryableAsync();
//Then apply any standard LINQ extension method
var query = queryable
.Where(x => x.Price > 10)
.OrderBy(x => x.Name);
//Finally, execute the query asynchronously
var books = await AsyncExecuter.ToListAsync(query);
}
````
ABP may start a database transaction when you get an `IQueryable` (If current [Unit Of Work](https://docs.abp.io/en/abp/latest/Unit-Of-Work) is transactional). In this new way, it is possible to **start the database transaction in an asynchronous way**. Previously, we could not get the advantage of asynchronous while starting the transactions.
> **The new way has a significant performance and scalability gain. The old usage (directly using LINQ over the repositories) will be removed in the next major version (5.0).** You have a lot of time for the change, but we recommend to immediately take the action since the old usage has a big **scalability problem**.
### Actions to Take
* Use the repository's queryable feature as explained before.
* If you've overridden `CreateFilteredQuery` in a class derived from `CrudAppService`, you should override the `CreateFilteredQueryAsync` instead and remove the `CreateFilteredQuery` in your class.
* If you've overridden `WithDetails` in your custom repositories, remove it and override `WithDetailsAsync` instead.
* If you've used `DbContext` or `DbSet` properties in your custom repositories, use `GetDbContextAsync()` and `GetDbSetAsync()` methods instead of them.
You can re-build your solution and check the `Obsolete` warnings to find some of the usages need to change.
#### About IRepository Async Extension Methods
Using IRepository Async Extension Methods has no such a problem. The examples below are pretty fine:
````csharp
var countAll = await _personRepository
.CountAsync();
var count = await _personRepository
.CountAsync(x => x.Name.StartsWith("A"));
var book1984 = await _bookRepository
.FirstOrDefaultAsync(x => x.Name == "John");
````
See the [repository documentation](https://docs.abp.io/en/abp/4.2/Repositories#iqueryable-async-operations) to understand the relation between `IQueryable` and asynchronous operations.
## .NET Package Upgrades
ABP uses the latest 5.0.* .NET packages. If your application is using 5.0.0 packages, you may get an error on build. We recommend to depend on the .NET packages like `5.0.*` in the `.csproj` files to use the latest patch versions.
Example:
````xml
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.*" />
````
## Blazorise Library Upgrade
If you are upgrading to 4.2, you also need also upgrade the following packages in your Blazor application;
* `Blazorise.Bootstrap` to `0.9.3-preview6`
* `Blazorise.Icons.FontAwesome` to `0.9.3-preview6`

5
docs/en/Migration-Guides/Index.md

@ -1,5 +1,6 @@
# ABP Framework Migration Guides # ABP Framework Migration Guides
* [3.3.x to 4.0 Migration Guide](Abp-4_0.md) * [4.x to 4.2](Abp-4_2.md)
* [2.9.x to 3.0 Migration Guide](../UI/Angular/Migration-Guide-v3.md) * [3.3.x to 4.0](Abp-4_0.md)
* [2.9.x to 3.0](../UI/Angular/Migration-Guide-v3.md)

57
docs/en/MongoDB.md

@ -149,7 +149,7 @@ public class Book : AggregateRoot<Guid>
} }
``` ```
(`BookType` is a simple enum here) And you want to create a new `Book` entity in a [domain service](Domain-Services.md): (`BookType` is a simple `enum` here) And you want to create a new `Book` entity in a [domain service](Domain-Services.md):
```csharp ```csharp
public class BookManager : DomainService public class BookManager : DomainService
@ -215,7 +215,8 @@ public class BookRepository :
BookType type, BookType type,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
await Collection.DeleteManyAsync( var collection = await GetCollectionAsync(cancellationToken);
await collection.DeleteManyAsync(
Builders<Book>.Filter.Eq(b => b.Type, type), Builders<Book>.Filter.Eq(b => b.Type, type),
cancellationToken cancellationToken
); );
@ -253,7 +254,7 @@ public async override Task DeleteAsync(
### Access to the MongoDB API ### Access to the MongoDB API
In most cases, you want to hide MongoDB APIs behind a repository (this is the main purpose of the repository). However, if you want to access the MongoDB API over the repository, you can use `GetDatabase()` or `GetCollection()` extension methods. Example: In most cases, you want to hide MongoDB APIs behind a repository (this is the main purpose of the repository). However, if you want to access the MongoDB API over the repository, you can use `GetDatabaseAsync()`, `GetCollectionAsync()` or `GetAggregateAsync()` extension methods. Example:
```csharp ```csharp
public class BookService public class BookService
@ -265,10 +266,11 @@ public class BookService
_bookRepository = bookRepository; _bookRepository = bookRepository;
} }
public void Foo() public async Task FooAsync()
{ {
IMongoDatabase database = _bookRepository.GetDatabase(); IMongoDatabase database = await _bookRepository.GetDatabaseAsync();
IMongoCollection<Book> books = _bookRepository.GetCollection(); IMongoCollection<Book> books = await _bookRepository.GetCollectionAsync();
IAggregateFluent<Book> bookAggregate = await _bookRepository.GetAggregateAsync();
} }
} }
``` ```
@ -390,36 +392,45 @@ If you have better logic or using an external library for bulk operations, you c
- You may use example template below: - You may use example template below:
```csharp ```csharp
public class MyCustomMongoDbBulkOperationProvider : IMongoDbBulkOperationProvider, ITransientDependency public class MyCustomMongoDbBulkOperationProvider
: IMongoDbBulkOperationProvider, ITransientDependency
{ {
public async Task DeleteManyAsync<TEntity>(IMongoDbRepository<TEntity> repository, public async Task DeleteManyAsync<TEntity>(
IEnumerable<TEntity> entities, IMongoDbRepository<TEntity> repository,
IClientSessionHandle sessionHandle, IEnumerable<TEntity> entities,
bool autoSave, IClientSessionHandle sessionHandle,
CancellationToken cancellationToken) bool autoSave,
CancellationToken cancellationToken)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
// Your logic here. // Your logic here.
} }
public async Task InsertManyAsync<TEntity>(IMongoDbRepository<TEntity> repository, public async Task InsertManyAsync<TEntity>(
IEnumerable<TEntity> entities, IMongoDbRepository<TEntity> repository,
IClientSessionHandle sessionHandle, IEnumerable<TEntity> entities,
bool autoSave, IClientSessionHandle sessionHandle,
CancellationToken cancellationToken) bool autoSave,
CancellationToken cancellationToken)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
// Your logic here. // Your logic here.
} }
public async Task UpdateManyAsync<TEntity>(IMongoDbRepository<TEntity> repository, public async Task UpdateManyAsync<TEntity>(
IEnumerable<TEntity> entities, IMongoDbRepository<TEntity> repository,
IClientSessionHandle sessionHandle, IEnumerable<TEntity> entities,
bool autoSave, IClientSessionHandle sessionHandle,
CancellationToken cancellationToken) bool autoSave,
CancellationToken cancellationToken)
where TEntity : class, IEntity where TEntity : class, IEntity
{ {
// Your logic here. // Your logic here.
} }
} }
``` ```
## See Also
* [Entities](Entities.md)
* [Repositories](Repositories.md)

200
docs/en/Repositories.md

@ -13,84 +13,178 @@ ABP can provide a **default generic repository** for each aggregate root or enti
**Example usage of a default generic repository:** **Example usage of a default generic repository:**
````C# ````C#
public class PersonAppService : ApplicationService using System;
{ using System.Threading.Tasks;
private readonly IRepository<Person, Guid> _personRepository; using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
public PersonAppService(IRepository<Person, Guid> personRepository) namespace Demo
{
public class PersonAppService : ApplicationService
{ {
_personRepository = personRepository; private readonly IRepository<Person, Guid> _personRepository;
}
public async Task Create(CreatePersonDto input) public PersonAppService(IRepository<Person, Guid> personRepository)
{ {
var person = new Person { Name = input.Name, Age = input.Age }; _personRepository = personRepository;
}
await _personRepository.InsertAsync(person); public async Task CreateAsync(CreatePersonDto input)
} {
var person = new Person(input.Name);
public List<PersonDto> GetList(string nameFilter) await _personRepository.InsertAsync(person);
{ }
var people = _personRepository
.Where(p => p.Name.Contains(nameFilter))
.ToList();
return people public async Task<int> GetCountAsync(string filter)
.Select(p => new PersonDto {Id = p.Id, Name = p.Name, Age = p.Age}) {
.ToList(); return await _personRepository.CountAsync(p => p.Name.Contains(filter));
}
} }
} }
```` ````
> See the "*IQueryable & Async Operations*" section below to understand how you can use **async extension methods**, like `ToListAsync()` (which is strongly suggested) instead of `ToList()`.
In this example; In this example;
* `PersonAppService` simply injects `IRepository<Person, Guid>` in it's constructor. * `PersonAppService` simply injects `IRepository<Person, Guid>` in it's constructor.
* `Create` method uses `InsertAsync` to save a newly created entity. * `CreateAsync` method uses `InsertAsync` to save the new entity.
* `GetList` method uses the standard LINQ `Where` and `ToList` methods to filter and get a list of people from the data source. * `GetCountAsync` method gets a filtered count of all people in the database.
> The example above uses hand-made mapping between [entities](Entities.md) and [DTO](Data-Transfer-Objects.md)s. See [object to object mapping document](Object-To-Object-Mapping.md) for an automatic way of mapping. ### Standard Repository Methods
Generic Repositories provides some standard CRUD features out of the box: Generic Repositories provides some standard CRUD features out of the box:
* Provides `Insert` method to save a new entity. * `GetAsync`: Returns a single entity by its `Id` or a predicate (lambda expression).
* Throws `EntityNotFoundException` if the requested entity was not found.
* Throws `InvalidOperationException` if there are multiple entities with given predicate.
* `FindAsync`: Returns a single entity by its `Id` or a predicate (lambda expression).
* Returns `null` if the requested entity was not found.
* Throws `InvalidOperationException` if there are multiple entities with given predicate.
* `InsertAsync`: Inserts a new entity to the database.
* `UpdateAsync`: Updates an existing entity in the database.
* `DeleteAsync`: Deletes the given entity from database.
* This method has an overload that takes a predicate (lambda expression) to delete multiple entities satisfies the given condition.
* `GetListAsync`: Returns the list of all entities in the database.
* `GetPagedListAsync`: Returns a limited list of entities. Gets `skipCount`, `maxResultCount` and `sorting` parameters.
* `GetCountAsync`: Gets count of all entities in the database.
There are overloads of these methods.
* Provides `Update` and `Delete` methods to update or delete an entity by entity object or it's id. * Provides `Update` and `Delete` methods to update or delete an entity by entity object or it's id.
* Provides `Delete` method to delete multiple entities by a filter. * Provides `Delete` method to delete multiple entities by a filter.
* Implements `IQueryable<TEntity>`, so you can use LINQ and extension methods like `FirstOrDefault`, `Where`, `OrderBy`, `ToList` and so on...
### Basic Repositories ### Querying / LINQ over the Repositories
Standard `IRepository<TEntity, TKey>` interface extends standard `IQueryable<TEntity>` and you can freely query using standard LINQ methods. However, some ORM providers or database systems may not support standard `IQueryable` interface. Repositories provide the `GetQueryableAsync()` method that returns an `IQueryable<TEntity>` object. You can use this object to perform LINQ queries on the entities in the database.
ABP provides `IBasicRepository<TEntity, TPrimaryKey>` and `IBasicRepository<TEntity>` interfaces to support such scenarios. You can extend these interfaces (and optionally derive from `BasicRepositoryBase`) to create custom repositories for your entities. **Example: Use LINQ with the repositories**
Depending on `IBasicRepository` but not depending on `IRepository` has an advantage to make possible to work with all data sources even if they don't support `IQueryable`. But major vendors, like Entity Framework, NHibernate or MongoDb already support `IQueryable`. ````csharp
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
So, working with `IRepository` is the **suggested** way for typical applications. But reusable module developers may consider `IBasicRepository` to support a wider range of data sources. namespace Demo
{
public class PersonAppService : ApplicationService
{
private readonly IRepository<Person, Guid> _personRepository;
### Read Only Repositories public PersonAppService(IRepository<Person, Guid> personRepository)
{
_personRepository = personRepository;
}
There are also `IReadOnlyRepository<TEntity, TKey>` and `IReadOnlyBasicRepository<Tentity, TKey>` interfaces for who only want to depend on querying capabilities of the repositories. public async Task<List<PersonDto>> GetListAsync(string filter)
{
//Obtain the IQueryable<Person>
IQueryable<Person> queryable = await _personRepository.GetQueryableAsync();
### Generic Repository without a Primary Key //Create a query
var query = from person in queryable
where person.Name == filter
orderby person.Name
select person;
If your entity does not have an Id primary key (it may have a composite primary key for instance) then you cannot use the `IRepository<TEntity, TKey>` (or basic/readonly versions) defined above. In that case, you can inject and use `IRepository<TEntity>` for your entity. //Execute the query to get list of people
var people = query.ToList();
> `IRepository<TEntity>` has a few missing methods those normally works with the `Id` property of an entity. Because of the entity has no `Id` property in that case, these methods are not available. One example is the `Get` method that gets an id and returns the entity with given id. However, you can still use `IQueryable<TEntity>` features to query entities by standard LINQ methods. //Convert to DTO and return to the client
return people.Select(p => new PersonDto {Name = p.Name}).ToList();
}
}
}
````
You could also use the LINQ extension methods:
````csharp
public async Task<List<PersonDto>> GetListAsync(string filter)
{
//Obtain the IQueryable<Person>
IQueryable<Person> queryable = await _personRepository.GetQueryableAsync();
//Execute a query
var people = queryable
.Where(p => p.Name.Contains(filter))
.OrderBy(p => p.Name)
.ToList();
//Convert to DTO and return to the client
return people.Select(p => new PersonDto {Name = p.Name}).ToList();
}
````
Any standard LINQ method can be used over the `IQueryable` returned from the repository.
> This sample uses `ToList()` method, but it is **strongly suggested to use the asynchronous methods** to perform database queries, like `ToListAsync()` for this example.
>
> See the **IQueryable & Async Operations** section to learn how you can do it.
### Bulk Operations
There are some methods to perform bulk operations in the database;
* `InsertManyAsync`
* `UpdateManyAsync`
* `DeleteManyAsync`
These methods work with multiple entities and can take advantage of bulk operations if supported by the underlying database provider.
> Optimistic concurrency control may not be possible when you use `UpdateManyAsync` and `DeleteManyAsync` methods.
### Soft / Hard Delete ### Soft / Hard Delete
`DeleteAsync` method of the repository doesn't delete the entity if the entity is a **soft-delete** entity (that implements `ISoftDelete`). Soft-delete entities are marked as "deleted" in the database. Data Filter system ensures that the soft deleted entities are not retrieved from database normally. `DeleteAsync` method of the repository doesn't delete the entity if the entity is a **soft-delete** entity (that implements `ISoftDelete`). Soft-delete entities are marked as "deleted" in the database. Data Filter system ensures that the soft deleted entities are not retrieved from database normally.
If your entity is a soft-delete entity, you can use the `HardDeleteAsync` method to really delete the entity from database in case of you need it. If your entity is a soft-delete entity, you can use the `HardDeleteAsync` method to physically delete the entity from database in case of you need it.
> See the [Data Filtering](Data-Filtering.md) documentation for more about soft-delete.
## Other Generic Repository Types
Standard `IRepository<TEntity, TKey>` interface exposes the standard `IQueryable<TEntity>` and you can freely query using the standard LINQ methods. This is fine for most of the applications. However, some ORM providers or database systems may not support standard `IQueryable` interface. If you want to use such providers, you can't rely on the `IQueryable`.
### Basic Repositories
ABP provides `IBasicRepository<TEntity, TPrimaryKey>` and `IBasicRepository<TEntity>` interfaces to support such scenarios. You can extend these interfaces (and optionally derive from `BasicRepositoryBase`) to create custom repositories for your entities.
Depending on `IBasicRepository` but not depending on `IRepository` has an advantage to make possible to work with all data sources even if they don't support `IQueryable`.
See the [Data Filtering](Data-Filtering.md) documentation for more about soft-delete. Major vendors, like Entity Framework, NHibernate or MongoDB already support `IQueryable`. So, working with `IRepository` is the **suggested** way for typical applications. But reusable module developers may consider `IBasicRepository` to support a wider range of data sources.
## Bulk Operations ### Read Only Repositories
You can execute bulk operations with `InsertManyAsync`, `UpdateManyAsync`, `DeleteManyAsync` methods.
> **WARNING:** ConcurrencyStamp can't be checked at bulk operations! There are also `IReadOnlyRepository<TEntity, TKey>` and `IReadOnlyBasicRepository<Tentity, TKey>` interfaces for who only want to depend on querying capabilities of the repositories.
### Generic Repository without a Primary Key
If your entity does not have an Id primary key (it may have a composite primary key for instance) then you cannot use the `IRepository<TEntity, TKey>` (or basic/readonly versions) defined above. In that case, you can inject and use `IRepository<TEntity>` for your entity.
> `IRepository<TEntity>` has a few missing methods those normally works with the `Id` property of an entity. Because of the entity has no `Id` property in that case, these methods are not available. One example is the `Get` method that gets an id and returns the entity with given id. However, you can still use `IQueryable<TEntity>` features to query entities by standard LINQ methods.
## Custom Repositories ## Custom Repositories
@ -128,7 +222,8 @@ public class PersonRepository : EfCoreRepository<MyDbContext, Person, Guid>, IPe
public async Task<Person> FindByNameAsync(string name) public async Task<Person> FindByNameAsync(string name)
{ {
return await DbContext.Set<Person>() var dbSet = await GetDbSetAsync();
return await dbSet.Set<Person>()
.Where(p => p.Name == name) .Where(p => p.Name == name)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
} }
@ -141,12 +236,13 @@ You can directly access the data access provider (`DbContext` in this case) to p
## IQueryable & Async Operations ## IQueryable & Async Operations
`IRepository` inherits from `IQueryable`, that means you can **directly use LINQ extension methods** on it, as shown in the example of the "*Generic Repositories*" section above. `IRepository` provides `GetQueryableAsync()` to obtain an `IQueryable`, that means you can **directly use LINQ extension methods** on it, as shown in the example of the "*Querying / LINQ over the Repositories*" section above.
**Example: Using the `Where(...)` and the `ToList()` extension methods** **Example: Using the `Where(...)` and the `ToList()` extension methods**
````csharp ````csharp
var people = _personRepository var queryable = await _personRepository.GetQueryableAsync();
var people = queryable
.Where(p => p.Name.Contains(nameFilter)) .Where(p => p.Name.Contains(nameFilter))
.ToList(); .ToList();
```` ````
@ -175,7 +271,8 @@ When you add the NuGet package to your project, you can take full power of the E
**Example: Directly using the `ToListAsync()` after adding the EF Core package** **Example: Directly using the `ToListAsync()` after adding the EF Core package**
````csharp ````csharp
var people = _personRepository var queryable = await _personRepository.GetQueryableAsync();
var people = queryable
.Where(p => p.Name.Contains(nameFilter)) .Where(p => p.Name.Contains(nameFilter))
.ToListAsync(); .ToListAsync();
```` ````
@ -191,7 +288,8 @@ If you are using [MongoDB](MongoDB.md), you need to add the [Volo.Abp.MongoDB](h
**Example: Cast `IQueryable<T>` to `IMongoQueryable<T>` and use `ToListAsync()`** **Example: Cast `IQueryable<T>` to `IMongoQueryable<T>` and use `ToListAsync()`**
````csharp ````csharp
var people = ((IMongoQueryable<Person>)_personRepository var queryable = await _personRepository.GetQueryableAsync();
var people = ((IMongoQueryable<Person>) queryable
.Where(p => p.Name.Contains(nameFilter))) .Where(p => p.Name.Contains(nameFilter)))
.ToListAsync(); .ToListAsync();
```` ````
@ -218,10 +316,11 @@ The standard LINQ extension methods are supported: *AllAsync, AnyAsync, AverageA
This approach still **has a limitation**. You need to call the extension method directly on the repository object. For example, the below usage is **not supported**: This approach still **has a limitation**. You need to call the extension method directly on the repository object. For example, the below usage is **not supported**:
```csharp ```csharp
var count = await _bookRepository.Where(x => x.Name.Contains("A")).CountAsync(); var queryable = await _bookRepository.GetQueryableAsync();
var count = await queryable.Where(x => x.Name.Contains("A")).CountAsync();
``` ```
This is because the object returned from the `Where` method is not a repository object, it is a standard `IQueryable` interface. See the other options for such cases. This is because the `CountAsync()` method in this example is called on a `IQueryable` interface, not on the repository object. See the other options for such cases.
This method is suggested **wherever possible**. This method is suggested **wherever possible**.
@ -258,8 +357,11 @@ namespace AbpDemo
public async Task<ListResultDto<ProductDto>> GetListAsync(string name) public async Task<ListResultDto<ProductDto>> GetListAsync(string name)
{ {
//Obtain the IQueryable<T>
var queryable = await _productRepository.GetQueryableAsync();
//Create the query //Create the query
var query = _productRepository var query = queryable
.Where(p => p.Name.Contains(name)) .Where(p => p.Name.Contains(name))
.OrderBy(p => p.Name); .OrderBy(p => p.Name);

2
docs/en/Road-Map.md

@ -18,4 +18,4 @@ You can always check the milestone planning and the prioritized backlog issues o
The backlog items are subject to change. We are adding new items and changing priorities based on the community feedbacks and goals of the project. The backlog items are subject to change. We are adding new items and changing priorities based on the community feedbacks and goals of the project.
Vote for your favorite feature on the related GitHub issues (and write your thoughts). You can create an issue on [the GitHub repository](https://github.com/abpframework/abp) for your feature requests, but first search in in the existing issues. Vote for your favorite feature on the related GitHub issues (and write your thoughts). You can create an issue on [the GitHub repository](https://github.com/abpframework/abp) for your feature requests, but first search in the existing issues.

3
docs/en/Samples/Index.md

@ -17,6 +17,9 @@ A simple CRUD application to show basic principles of developing an application
* **Book Store: Razor Pages UI & Entity Framework Core** * **Book Store: Razor Pages UI & Entity Framework Core**
* [Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=MVC&DB=EF) * [Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=MVC&DB=EF)
* [Source code](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore) * [Source code](https://github.com/abpframework/abp-samples/tree/master/BookStore-Mvc-EfCore)
* **Book Store: Blazor UI & Entity Framework Core**
* [Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=Blazor&DB=EF)
* [Source code](https://github.com/abpframework/abp-samples/tree/master/BookStore-Blazor-EfCore)
* **Book Store: Angular UI & MongoDB** * **Book Store: Angular UI & MongoDB**
* [Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=NG&DB=Mongo) * [Tutorial](https://docs.abp.io/en/abp/latest/Tutorials/Part-1?UI=NG&DB=Mongo)
* [Source code](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb) * [Source code](https://github.com/abpframework/abp-samples/tree/master/BookStore-Angular-MongoDb)

6
docs/en/Specifications.md

@ -122,7 +122,8 @@ namespace MyProject
public async Task<List<Customer>> GetCustomersCanBuyAlcohol() public async Task<List<Customer>> GetCustomersCanBuyAlcohol()
{ {
var query = _customerRepository.Where( var queryable = await _customerRepository.GetQueryableAsync();
var query = queryable.Where(
new Age18PlusCustomerSpecification().ToExpression() new Age18PlusCustomerSpecification().ToExpression()
); );
@ -137,7 +138,8 @@ namespace MyProject
Actually, using the `ToExpression()` method is not necessary since the specifications are automatically casted to Expressions. This would also work: Actually, using the `ToExpression()` method is not necessary since the specifications are automatically casted to Expressions. This would also work:
````csharp ````csharp
var query = _customerRepository.Where( var queryable = await _customerRepository.GetQueryableAsync();
var query = queryable.Where(
new Age18PlusCustomerSpecification() new Age18PlusCustomerSpecification()
); );
```` ````

37
docs/en/Tutorials/Part-10.md

@ -364,10 +364,11 @@ namespace Acme.BookStore.Books
public override async Task<BookDto> GetAsync(Guid id) public override async Task<BookDto> GetAsync(Guid id)
{ {
await CheckGetPolicyAsync(); //Get the IQueryable<Book> from the repository
var queryable = await Repository.GetQueryableAsync();
//Prepare a query to join books and authors //Prepare a query to join books and authors
var query = from book in Repository var query = from book in queryable
join author in _authorRepository on book.AuthorId equals author.Id join author in _authorRepository on book.AuthorId equals author.Id
where book.Id == id where book.Id == id
select new { book, author }; select new { book, author };
@ -384,17 +385,24 @@ namespace Acme.BookStore.Books
return bookDto; return bookDto;
} }
public override async Task<PagedResultDto<BookDto>> GetListAsync( public override async Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input)
PagedAndSortedResultRequestDto input)
{ {
await CheckGetListPolicyAsync(); //Set a default sorting, if not provided
if (input.Sorting.IsNullOrWhiteSpace())
{
input.Sorting = nameof(Book.Name);
}
//Get the IQueryable<Book> from the repository
var queryable = await Repository.GetQueryableAsync();
//Prepare a query to join books and authors //Prepare a query to join books and authors
var query = from book in Repository var query = from book in queryable
join author in _authorRepository on book.AuthorId equals author.Id join author in _authorRepository on book.AuthorId equals author.Id
orderby input.Sorting orderby input.Sorting //TODO: Can not sort like that!
select new {book, author}; select new {book, author};
//Paging
query = query query = query
.Skip(input.SkipCount) .Skip(input.SkipCount)
.Take(input.MaxResultCount); .Take(input.MaxResultCount);
@ -437,7 +445,7 @@ Let's see the changes we've done:
* Injected `IAuthorRepository` to query from the authors. * Injected `IAuthorRepository` to query from the authors.
* Overrode the `GetAsync` method of the base `CrudAppService`, which returns a single `BookDto` object with the given `id`. * Overrode the `GetAsync` method of the base `CrudAppService`, which returns a single `BookDto` object with the given `id`.
* Used a simple LINQ expression to join books and authors and query them together for the given book id. * Used a simple LINQ expression to join books and authors and query them together for the given book id.
* Used `AsyncExecuter.FirstOrDefaultAsync(...)` to execute the query and get a result. `AsyncExecuter` was previously used in the `AuthorAppService`. Check the [repository documentation](../Repositories.md) to understand why we've used it. * Used `AsyncExecuter.FirstOrDefaultAsync(...)` to execute the query and get a result. It is a way to use asynchronous LINQ extensions without depending on the database provider API. Check the [repository documentation](../Repositories.md) to understand why we've used it.
* Throws an `EntityNotFoundException` which results an `HTTP 404` (not found) result if requested book was not present in the database. * Throws an `EntityNotFoundException` which results an `HTTP 404` (not found) result if requested book was not present in the database.
* Finally, created a `BookDto` object using the `ObjectMapper`, then assigning the `AuthorName` manually. * Finally, created a `BookDto` object using the `ObjectMapper`, then assigning the `AuthorName` manually.
* Overrode the `GetListAsync` method of the base `CrudAppService`, which returns a list of books. The logic is similar to the previous method, so you can easily understand the code. * Overrode the `GetListAsync` method of the base `CrudAppService`, which returns a list of books. The logic is similar to the previous method, so you can easily understand the code.
@ -487,8 +495,6 @@ namespace Acme.BookStore.Books
public async override Task<BookDto> GetAsync(Guid id) public async override Task<BookDto> GetAsync(Guid id)
{ {
await CheckGetPolicyAsync();
var book = await Repository.GetAsync(id); var book = await Repository.GetAsync(id);
var bookDto = ObjectMapper.Map<Book, BookDto>(book); var bookDto = ObjectMapper.Map<Book, BookDto>(book);
@ -501,17 +507,18 @@ namespace Acme.BookStore.Books
public async override Task<PagedResultDto<BookDto>> public async override Task<PagedResultDto<BookDto>>
GetListAsync(PagedAndSortedResultRequestDto input) GetListAsync(PagedAndSortedResultRequestDto input)
{ {
await CheckGetListPolicyAsync();
//Set a default sorting, if not provided //Set a default sorting, if not provided
if (input.Sorting.IsNullOrWhiteSpace()) if (input.Sorting.IsNullOrWhiteSpace())
{ {
input.Sorting = nameof(Book.Name); input.Sorting = nameof(Book.Name);
} }
//Get the IQueryable<Book> from the repository
var queryable = await Repository.GetQueryableAsync();
//Get the books //Get the books
var books = await AsyncExecuter.ToListAsync( var books = await AsyncExecuter.ToListAsync(
Repository queryable
.OrderBy(input.Sorting) .OrderBy(input.Sorting)
.Skip(input.SkipCount) .Skip(input.SkipCount)
.Take(input.MaxResultCount) .Take(input.MaxResultCount)
@ -553,8 +560,10 @@ namespace Acme.BookStore.Books
.Distinct() .Distinct()
.ToArray(); .ToArray();
var queryable = await _authorRepository.GetQueryableAsync();
var authors = await AsyncExecuter.ToListAsync( var authors = await AsyncExecuter.ToListAsync(
_authorRepository.Where(a => authorIds.Contains(a.Id)) queryable.Where(a => authorIds.Contains(a.Id))
); );
return authors.ToDictionary(x => x.Id, x => x); return authors.ToDictionary(x => x.Id, x => x);

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

@ -127,7 +127,8 @@ namespace Acme.BookStore.Authors
public async Task<Author> FindByNameAsync(string name) public async Task<Author> FindByNameAsync(string name)
{ {
return await DbSet.FirstOrDefaultAsync(author => author.Name == name); var dbSet = await GetDbSetAsync();
return await dbSet.FirstOrDefaultAsync(author => author.Name == name);
} }
public async Task<List<Author>> GetListAsync( public async Task<List<Author>> GetListAsync(
@ -136,7 +137,8 @@ namespace Acme.BookStore.Authors
string sorting, string sorting,
string filter = null) string filter = null)
{ {
return await DbSet var dbSet = await GetDbSetAsync();
return await dbSet
.WhereIf( .WhereIf(
!filter.IsNullOrWhiteSpace(), !filter.IsNullOrWhiteSpace(),
author => author.Name.Contains(filter) author => author.Name.Contains(filter)
@ -186,8 +188,8 @@ namespace Acme.BookStore.Authors
public async Task<Author> FindByNameAsync(string name) public async Task<Author> FindByNameAsync(string name)
{ {
return await GetMongoQueryable() var queryable = await GetMongoQueryableAsync();
.FirstOrDefaultAsync(author => author.Name == name); return await queryable.FirstOrDefaultAsync(author => author.Name == name);
} }
public async Task<List<Author>> GetListAsync( public async Task<List<Author>> GetListAsync(
@ -196,7 +198,8 @@ namespace Acme.BookStore.Authors
string sorting, string sorting,
string filter = null) string filter = null)
{ {
return await GetMongoQueryable() var queryable = await GetMongoQueryableAsync();
return await queryable
.WhereIf<Author, IMongoQueryable<Author>>( .WhereIf<Author, IMongoQueryable<Author>>(
!filter.IsNullOrWhiteSpace(), !filter.IsNullOrWhiteSpace(),
author => author.Name.Contains(filter) author => author.Name.Contains(filter)

13
docs/en/Tutorials/Part-8.md

@ -172,6 +172,7 @@ using System.Threading.Tasks;
using Acme.BookStore.Permissions; using Acme.BookStore.Permissions;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
namespace Acme.BookStore.Authors namespace Acme.BookStore.Authors
{ {
@ -230,12 +231,10 @@ public async Task<PagedResultDto<AuthorDto>> GetListAsync(GetAuthorListDto input
input.Filter input.Filter
); );
var totalCount = await AsyncExecuter.CountAsync( var totalCount = input.Filter == null
_authorRepository.WhereIf( ? await _authorRepository.CountAsync()
!input.Filter.IsNullOrWhiteSpace(), : await _authorRepository.CountAsync(
author => author.Name.Contains(input.Filter) author => author.Name.Contains(input.Filter));
)
);
return new PagedResultDto<AuthorDto>( return new PagedResultDto<AuthorDto>(
totalCount, totalCount,
@ -246,7 +245,7 @@ public async Task<PagedResultDto<AuthorDto>> GetListAsync(GetAuthorListDto input
* Default sorting is "by author name" which is done in the beginning of the method in case of it wasn't sent by the client. * Default sorting is "by author name" which is done in the beginning of the method in case of it wasn't sent by the client.
* Used the `IAuthorRepository.GetListAsync` to get a paged, sorted and filtered list of authors from the database. We had implemented it in the previous part of this tutorial. Again, it actually was not needed to create such a method since we could directly query over the repository, but wanted to demonstrate how to create custom repository methods. * Used the `IAuthorRepository.GetListAsync` to get a paged, sorted and filtered list of authors from the database. We had implemented it in the previous part of this tutorial. Again, it actually was not needed to create such a method since we could directly query over the repository, but wanted to demonstrate how to create custom repository methods.
* Directly queried from the `AuthorRepository` while getting the count of the authors. We preferred to use the `AsyncExecuter` service which allows us to perform async queries without depending on the EF Core. However, you could depend on the EF Core package and directly use the `_authorRepository.WhereIf(...).ToListAsync()` method. See the [repository document](../Repositories.md) to read the alternative approaches and the discussion. * Directly queried from the `AuthorRepository` while getting the count of the authors. If a filter is sent, then we are using it to filter entities while getting the count.
* Finally, returning a paged result by mapping the list of `Author`s to a list of `AuthorDto`s. * Finally, returning a paged result by mapping the list of `Author`s to a list of `AuthorDto`s.
### CreateAsync ### CreateAsync

28
docs/en/UI/Angular/Authorization.md

@ -0,0 +1,28 @@
# Authorization in Angular UI
OAuth is preconfigured in Angular application templates. So, when you start a project using the CLI (or Suite, for that matter), authorization already works. You can find **OAuth configuration** in the _environment.ts_ files.
```js
import { Config } from '@abp/ng.core';
const baseUrl = 'http://localhost:4200';
export const environment = {
// other options removed for sake of brevity
oAuthConfig: {
issuer: 'https://localhost:44305',
redirectUri: baseUrl,
clientId: 'MyProjectName_App',
responseType: 'code',
scope: 'offline_access MyProjectName',
},
// other options removed for sake of brevity
} as Config.Environment;
```
This configuration results in an [OAuth authorization code flow with PKCE](https://tools.ietf.org/html/rfc7636) and we are using [angular-oauth2-oidc library](https://github.com/manfredsteyer/angular-oauth2-oidc#logging-in) for managing OAuth in the Angular client.
According to this flow, the user is redirected to an external login page which is built with MVC. So, if you need **to customize the login page**, please follow [this community article](https://community.abp.io/articles/how-to-customize-the-login-page-for-mvc-razor-page-applications-9a40f3cd).

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

@ -0,0 +1,83 @@
# Ellipsis
Text inside an HTML element can be truncated easily with an ellipsis by using CSS. To make this even easier, you can use the `EllipsisDirective` which has been exposed by the `@abp/ng.theme.shared` package.
## Getting Started
In order to use the `EllipsisDirective` in an HTML template, the **`ThemeSharedModule`** should be imported into your module like this:
```js
// ...
import { ThemeSharedModule } from '@abp/ng.theme.shared';
@NgModule({
//...
imports: [..., ThemeSharedModule],
})
export class MyFeatureModule {}
```
or **if you would not like to import** the `ThemeSharedModule`, you can import the **`EllipsisModule`** as shown below:
```js
// ...
import { EllipsisModule } from '@abp/ng.theme.shared';
@NgModule({
//...
imports: [..., EllipsisModule],
})
export class MyFeatureModule {}
```
## Usage
The `EllipsisDirective` is very easy to use. The directive's selector is **`abpEllipsis`**. By adding the `abpEllipsis` attribute to an HTML element, you can activate the `EllipsisDirective` for the HTML element.
See an example usage:
```html
<p abpEllipsis>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam commodi quae aspernatur,
corporis velit et suscipit id consequuntur amet minima expedita cum reiciendis dolorum
cupiditate? Voluptas eaque voluptatum odio deleniti quo vel illum nemo accusamus nulla ratione
impedit dolorum expedita necessitatibus fugiat ullam beatae, optio eum cupiditate ducimus
architecto.
</p>
```
The `abpEllipsis` attribute has been added to the `<p>` element that containing very long text inside to activate the `EllipsisDirective`.
See the result:
![Ellipsis directive result](./images/ellipsis-directive-result1.jpg)
The long text has been truncated by using the directive.
The UI before using the directive looks like this:
![Before using the EllipsisDirective](./images/ellipsis-directive-before.jpg)
### Specifying Max Width of an HTML Element
An HTML element max width can be specified as shown below:
```html
<div [abpEllipsis]="'100px'">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque, optio!
</div>
<div [abpEllipsis]="'15vw'">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque, optio!
</div>
<div [abpEllipsis]="'50%'">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque, optio!
</div>
```
See the result:
![Ellipsis directive result 2](./images/ellipsis-directive-result2.jpg)

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

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

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

@ -1,4 +1,4 @@
# Multi Tenancy in Angular UI # Multi-Tenancy in Angular UI
ABP Angular UI supports the multi-tenancy. The following features related to multi-tenancy are available in the startup templates. ABP Angular UI supports the multi-tenancy. The following features related to multi-tenancy are available in the startup templates.
@ -8,7 +8,7 @@ ABP Angular UI supports the multi-tenancy. The following features related to mul
On the page above, you can; On the page above, you can;
- See the all tenants. - See all tenants.
- Create a new tenant. - Create a new tenant.
- Edit an existing tenant. - Edit an existing tenant.
- Delete a tenant. - Delete a tenant.
@ -17,9 +17,11 @@ On the page above, you can;
<p style="font-size:small;text-align:center;">Tenant Switching Component</p> <p style="font-size:small;text-align:center;">Tenant Switching Component</p>
You can switch between existing tenants by using the tenant switching component in the child pages of the `AccountLayoutComponent` (like Login page). Angular UI sends the selected tenant id to the backend as `__tenant` header on each request. You can switch between existing tenants by using the tenant switching box in the child pages of the MVC Account Public Module (like Login page). Angular UI gets selected tenant from `application-configuration` response and sends the tenant id to the backend as `__tenant` header on each request.
## Domain Tenant Resolver ## Domain/Subdomain Tenant Resolver
> **Note:** If you are going to implement the steps below, you should also implement the domain/subdomain tenant resolver feature for the backend. See the [Domain/Subdomain Tenant Resolver section in Multi-Tenancy document](../../Multi-Tenancy#domain-subdomain-tenant-resolver) to learn the backend implementation.
Angular UI can get the tenant name from the app running URL. You can determine the current tenant by subdomain (like mytenant1.mydomain.com) or by the whole domain (like mytenant.com). To do this, you need to set the `application.baseUrl` property in the environment: Angular UI can get the tenant name from the app running URL. You can determine the current tenant by subdomain (like mytenant1.mydomain.com) or by the whole domain (like mytenant.com). To do this, you need to set the `application.baseUrl` property in the environment:

64
docs/en/UI/Angular/Page-Alerts.md

@ -0,0 +1,64 @@
# Page Alerts
A page alert is useful for displaying an important message to the user. The ABP Framework provides an easy way to show the following alert to the user.
![angular-page-alert-example](./images/page-alert-warning-example.png)
You can simply import `PageAlertService` from `@abp/ng.theme.shared` and utilize it as follows:
```js
import { PageAlertService } from '@abp/ng.theme.shared';
@Component({
// ...
})
export class MyComponent {
constructor(private service: PageAlertService) {}
showWarning() {
this.service.show({
type: 'warning',
message:
'We will have a service interruption between 02:00 AM and 04:00 AM at October 23, 2023!',
title: 'Service Interruption',
});
}
}
```
## `SHOW`
The method `show` accepts a single object that is type of `PageAlert`
```js
export interface PageAlert {
type: 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'light' | 'dark';
message: string;
title?: string;
dismissible?: boolean;
messageLocalizationParams?: string[];
titleLocalizationParams?: string[];
}
```
* `type` (Required): Defines what type of alert will be shown
* `message` (Required): The message who will be shown, also works with localization as well.
* `title` (Optional): The title of the message. If it is not provided, the title will be hidden.
* `dismissible` (Optional): Default is `true`. If enabled, a button on the top right corner will be shown to the users so that they can dismiss the message.
* `messageLocalizationParams` and `titleLocalizationParams` (Optional): If the message and/or the title is a key for localization service and contains some parameters, these fields could be used to pass those parameters.
### An example with Localization
```typescript
this.service.show({
type: 'danger',
message: 'AbpAccount::PagerInfo{0}{1}{2}',
messageLocalizationParams: ['10', '20', '30'],
title: 'AbpAccount::EntityNotFoundErrorMessage',
titleLocalizationParams: ['Test', 'id123'],
});
```
![angular-page-alert-with-params-example](./images/page-alert-with-params-example.png)

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

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

16
docs/en/UI/Angular/Testing.md

@ -10,7 +10,7 @@ In Angular, unit tests use [Karma](https://karma-runner.github.io/) and [Jasmine
An over-simplified spec file looks like this: An over-simplified spec file looks like this:
```ts ```js
import { CoreTestingModule } from "@abp/ng.core/testing"; import { CoreTestingModule } from "@abp/ng.core/testing";
import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing"; import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing";
import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing"; import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";
@ -59,7 +59,7 @@ Although you can test your code with Angular TestBed, you may find [Angular Test
The simple example above can be written with Angular Testing Library as follows: The simple example above can be written with Angular Testing Library as follows:
```ts ```js
import { CoreTestingModule } from "@abp/ng.core/testing"; import { CoreTestingModule } from "@abp/ng.core/testing";
import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing"; import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing";
import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing"; import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";
@ -95,7 +95,7 @@ describe("MyComponent", () => {
Very similar, as you can see. The real difference kicks in when we use queries and fire events. Very similar, as you can see. The real difference kicks in when we use queries and fire events.
```ts ```js
// other imports // other imports
import { getByLabelText, screen } from "@testing-library/angular"; import { getByLabelText, screen } from "@testing-library/angular";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
@ -131,7 +131,7 @@ One thing to remember is that Karma runs tests in real browser instances. That m
We have prepared a simple function with which you can clear any leftover DOM elements after each test. We have prepared a simple function with which you can clear any leftover DOM elements after each test.
```ts ```js
// other imports // other imports
import { clearPage } from "@abp/ng.core/testing"; import { clearPage } from "@abp/ng.core/testing";
@ -159,7 +159,7 @@ Some components, modals, in particular, work off-detection-cycle. In other words
For this purpose, we have prepared a `wait` function. For this purpose, we have prepared a `wait` function.
```ts ```js
// other imports // other imports
import { wait } from "@abp/ng.core/testing"; import { wait } from "@abp/ng.core/testing";
@ -187,7 +187,7 @@ The `wait` function takes a second parameter, i.e. timeout (default: `0`). Try n
Here is an example test suite. It doesn't cover all, but gives quite a good idea about what the testing experience will be like. Here is an example test suite. It doesn't cover all, but gives quite a good idea about what the testing experience will be like.
```ts ```js
import { clearPage, CoreTestingModule, wait } from "@abp/ng.core/testing"; import { clearPage, CoreTestingModule, wait } from "@abp/ng.core/testing";
import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing"; import { ThemeBasicTestingModule } from "@abp/ng.theme.basic/testing";
import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing"; import { ThemeSharedTestingModule } from "@abp/ng.theme.shared/testing";
@ -374,3 +374,7 @@ Finally, don't forget to run your CI tests with the following command:
```sh ```sh
npm test -- --prod npm test -- --prod
``` ```
## See Also
* [ABP Community Video - Unit Testing with the Angular UI](https://community.abp.io/articles/unit-testing-with-the-angular-ui-p4l550q3)

BIN
docs/en/UI/Angular/images/ellipsis-directive-before.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
docs/en/UI/Angular/images/ellipsis-directive-result1.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
docs/en/UI/Angular/images/ellipsis-directive-result2.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

BIN
docs/en/UI/Angular/images/page-alert-warning-example.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

BIN
docs/en/UI/Angular/images/page-alert-with-params-example.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

22
docs/en/UI/AspNetCore/Bundling-Minification.md

@ -165,7 +165,27 @@ public class MyWebExtensionModule : AbpModule
} }
```` ````
> It's not possible to configure unnamed bundle tag helpers by code, because their name are not known at the development time. It's suggested to always use a name for a bundle tag helper. You can also use the `ConfigureAll` method to configure all existing bundles:
````C#
[DependsOn(typeof(MyWebModule))]
public class MyWebExtensionModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpBundlingOptions>(options =>
{
options
.ScriptBundles
.ConfigureAll(bundle => {
bundle.AddFiles(
"/scripts/my-extension-script.js"
);
});
});
}
}
````
## Bundle Contributors ## Bundle Contributors

28
docs/en/docs-nav.json

@ -681,6 +681,10 @@
{ {
"text": "Page Alerts", "text": "Page Alerts",
"path": "UI/Blazor/Page-Alerts.md" "path": "UI/Blazor/Page-Alerts.md"
},
{
"text": "Page Progress",
"path": "UI/Blazor/Page-Progress.md"
} }
] ]
}, },
@ -754,6 +758,10 @@
"text": "Config State Service", "text": "Config State Service",
"path": "UI/Angular/Config-State-Service.md" "path": "UI/Angular/Config-State-Service.md"
}, },
{
"text": "Authorization",
"path": "UI/Angular/Authorization.md"
},
{ {
"text": "HTTP Requests", "text": "HTTP Requests",
"path": "UI/Angular/HTTP-Requests.md" "path": "UI/Angular/HTTP-Requests.md"
@ -799,6 +807,10 @@
"text": "Easy *ngFor trackBy", "text": "Easy *ngFor trackBy",
"path": "UI/Angular/Track-By-Service.md" "path": "UI/Angular/Track-By-Service.md"
}, },
{
"text": "Router Events",
"path": "UI/Angular/Router-Events.md"
},
{ {
"text": "Inserting Scripts & Styles to DOM", "text": "Inserting Scripts & Styles to DOM",
"path": "UI/Angular/Dom-Insertion-Service.md" "path": "UI/Angular/Dom-Insertion-Service.md"
@ -811,6 +823,10 @@
"text": "Projecting Angular Content", "text": "Projecting Angular Content",
"path": "UI/Angular/Content-Projection-Service.md" "path": "UI/Angular/Content-Projection-Service.md"
}, },
{
"text": "Modal",
"path": "UI/Angular/Modal.md"
},
{ {
"text": "Confirmation Popup", "text": "Confirmation Popup",
"path": "UI/Angular/Confirmation-Service.md" "path": "UI/Angular/Confirmation-Service.md"
@ -818,6 +834,14 @@
{ {
"text": "Toast Overlay", "text": "Toast Overlay",
"path": "UI/Angular/Toaster-Service.md" "path": "UI/Angular/Toaster-Service.md"
},
{
"text": "Page Alerts",
"path": "UI/Angular/Page-Alerts.md"
},
{
"text": "Ellipsis",
"path": "UI/Angular/Ellipsis-Directive.md"
} }
] ]
}, },
@ -1044,10 +1068,6 @@
{ {
"text": "CLI", "text": "CLI",
"path": "CLI.md" "path": "CLI.md"
},
{
"text": "API Documentation",
"path": "{ApiDocumentationUrl}"
} }
] ]
}, },

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

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

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

@ -1767,7 +1767,7 @@ public async Task ChangeTitleAsync(Issue issue, string title)
如前所述,领域驱动设计中的*业务逻辑*分为两部分(各层):领域逻辑和应用逻辑 如前所述,领域驱动设计中的*业务逻辑*分为两部分(各层):领域逻辑和应用逻辑
![domain-driven-design-domain-vs-application-logic](../../../abpframework.abp/docs/en/images/domain-driven-design-domain-vs-application-logic.png) ![domain-driven-design-domain-vs-application-logic](images/domain-driven-design-domain-vs-application-logic.png)
领域逻辑是系统的*核心领域规则*组成,而应用逻辑则满足特定的*用例*. 领域逻辑是系统的*核心领域规则*组成,而应用逻辑则满足特定的*用例*.
@ -1783,7 +1783,7 @@ public async Task ChangeTitleAsync(Issue issue, string title)
* 一个**后台管理系统**,UI使用Angular,通过REST API请求数据.内部员工使用这个系统来维护数据(例如,编辑商品说明). * 一个**后台管理系统**,UI使用Angular,通过REST API请求数据.内部员工使用这个系统来维护数据(例如,编辑商品说明).
* 一个**移动端应用程序**,它比公开的网站UI上更加简洁.它通过REST API或其它技术(例如,TCP sockets)请求数据. * 一个**移动端应用程序**,它比公开的网站UI上更加简洁.它通过REST API或其它技术(例如,TCP sockets)请求数据.
![domain-driven-design-multiple-applications](../../../abpframework.abp/docs/en/images/domain-driven-design-multiple-applications.png) ![domain-driven-design-multiple-applications](images/domain-driven-design-multiple-applications.png)
每个应用程序都有不同的**需求**,不同的**用例**(应用服务方法),不同的DTO,不同的**验证**和**授权**规则等. 每个应用程序都有不同的**需求**,不同的**用例**(应用服务方法),不同的DTO,不同的**验证**和**授权**规则等.

24
docs/zh-Hans/Entity-Framework-Core-Other-DBMS.md

@ -62,22 +62,25 @@ MySQL连接字符串与SQL Server连接字符串不同. 所以检查你的解决
通常需要更改 `.DbMigrator` 和 `.Web` 项目里面的 `appsettings.json` ,但它取决于你的解决方案结构. 通常需要更改 `.DbMigrator` 和 `.Web` 项目里面的 `appsettings.json` ,但它取决于你的解决方案结构.
## 更改迁移DbContext ## 更改迁移DbContext Factory
MySQL DBMS与SQL Server有一些细微的差异. 某些模块数据库映射配置(尤其是字段长度)会导致MySQL出现问题. 例如某些[IdentityServer模块](Modules/IdentityServer.md)表就存在这样的问题,它提供了一个选项可以根据你的DBMS配置字段. 启动模板包含***YourProjectName*MigrationsDbContextFactory**类,这是EF Core控制台命令所必须的类(比如[Add-Migration](https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/#generating--running-migrations)和[Update-Database](https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/#generating--running-migrations)),在切换到MySql数据库时,我们同时也需要修改`DbContextOptionsBuilder`
启动模板包含*YourProjectName*MigrationsDbContext,它负责维护和迁移数据库架构. 此DbContext基本上调用依赖模块的扩展方法来配置其数据库表. 在 *YourProjectName*MigrationsDbContextFactory 类中找到以下代码:
打开 *YourProjectName*MigrationsDbContext 更改 `builder.ConfigureIdentityServer();` 行,如下所示: ````csharp
var builder = new DbContextOptionsBuilder<YourProjectNameMigrationsDbContext>()
.UseSqlServer(configuration.GetConnectionString("Default"));
````
将其替换为:
````csharp ````csharp
builder.ConfigureIdentityServer(options => var builder = new DbContextOptionsBuilder<YourProjectNameMigrationsDbContext>()
{ .UseMySql(configuration.GetConnectionString("Default"));
options.DatabaseProvider = EfCoreDatabaseProvider.MySql;
});
```` ````
然后 `ConfigureIdentityServer()` 方法会将字段长度设置为超过MySQL的限制. 如果在创建或执行数据库迁移时遇到任何问题请参考相关的模块文档. 如果在创建或执行数据库迁移时遇到任何问题,请参考相关模块文档
## 重新生成迁移 ## 重新生成迁移
@ -105,5 +108,6 @@ builder.ConfigureIdentityServer(options =>
options.DatabaseProvider = EfCoreDatabaseProvider.MySql; options.DatabaseProvider = EfCoreDatabaseProvider.MySql;
}); });
``` ```
v2.9+版本无需手动设置 ([版本历史](https://github.com/abpframework/abp/blob/dev/modules/identityserver/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/IdentityServerModelBuilderConfigurationOptions.cs))
相关讨论: https://github.com/abpframework/abp/issues/1920 相关讨论: https://github.com/abpframework/abp/issues/1920

9
docs/zh-Hans/MongoDB.md

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

22
docs/zh-Hans/UI/AspNetCore/Bundling-Minification.md

@ -167,7 +167,27 @@ public class MyWebExtensionModule : AbpModule
} }
```` ````
> 无法通过代码配置未命名的bundle tag helpers, 因为它们的名称在开发时是未知的. 建议始终使用bundle tag helper的名称. 你也可以使用 `ConfigureAll` 方法配置所有现有的捆绑包:
````C#
[DependsOn(typeof(MyWebModule))]
public class MyWebExtensionModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpBundlingOptions>(options =>
{
options
.ScriptBundles
.ConfigureAll(bundle => {
bundle.AddFiles(
"/scripts/my-extension-script.js"
);
});
});
}
}
````
### Bundle 贡献者 ### Bundle 贡献者

7
framework/src/Volo.Abp.AspNetCore.MultiTenancy/Volo/Abp/AspNetCore/MultiTenancy/DomainTenantResolveContributor.cs

@ -25,7 +25,12 @@ namespace Volo.Abp.AspNetCore.MultiTenancy
protected override Task<string> GetTenantIdOrNameFromHttpContextOrNullAsync(ITenantResolveContext context, HttpContext httpContext) protected override Task<string> GetTenantIdOrNameFromHttpContextOrNullAsync(ITenantResolveContext context, HttpContext httpContext)
{ {
var hostName = httpContext.Request.Host.Host.RemovePreFix(ProtocolPrefixes); if (!httpContext.Request.Host.HasValue)
{
return Task.FromResult<string>(null);
}
var hostName = httpContext.Request.Host.Value.RemovePreFix(ProtocolPrefixes);
var extractResult = FormattedStringValueExtracter.Extract(hostName, _domainFormat, ignoreCase: true); var extractResult = FormattedStringValueExtracter.Extract(hostName, _domainFormat, ignoreCase: true);
context.Handled = true; context.Handled = true;

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

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

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

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

33
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bundling/Volo/Abp/AspNetCore/Mvc/UI/Bundling/BundleConfigurationCollection.cs

@ -9,11 +9,13 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.Bundling
{ {
private readonly ConcurrentDictionary<string, BundleConfiguration> _bundles; private readonly ConcurrentDictionary<string, BundleConfiguration> _bundles;
private readonly ConcurrentDictionary<string, List<Action<BundleConfiguration>>> _lazyBundleConfigurationActions; private readonly ConcurrentDictionary<string, List<Action<BundleConfiguration>>> _lazyBundleConfigurationActions;
private readonly List<Action<BundleConfiguration>> _lazyAllBundleConfigurationActions;
public BundleConfigurationCollection() public BundleConfigurationCollection()
{ {
_bundles = new ConcurrentDictionary<string, BundleConfiguration>(); _bundles = new ConcurrentDictionary<string, BundleConfiguration>();
_lazyBundleConfigurationActions = new ConcurrentDictionary<string, List<Action<BundleConfiguration>>>(); _lazyBundleConfigurationActions = new ConcurrentDictionary<string, List<Action<BundleConfiguration>>>();
_lazyAllBundleConfigurationActions = new List<Action<BundleConfiguration>>();
} }
/// <summary> /// <summary>
@ -90,6 +92,12 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.Bundling
} }
} }
lock (_lazyAllBundleConfigurationActions)
{
_lazyAllBundleConfigurationActions.ForEach(c => c.Invoke(bundle));
}
return bundle; return bundle;
} }
@ -123,6 +131,29 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.Bundling
return this; return this;
} }
/// <summary>
/// Configures all bundles.
/// This method also works for lazy bundles (those are created using razor tag helpers).
/// </summary>
/// <param name="configureAction">Configure action</param>
/// <returns>Returns this object for chained calls.</returns>
public BundleConfigurationCollection ConfigureAll([NotNull] Action<BundleConfiguration> configureAction)
{
Check.NotNull(configureAction, nameof(configureAction));
foreach (var bundle in _bundles)
{
configureAction.Invoke(bundle.Value);
}
lock (_lazyAllBundleConfigurationActions)
{
_lazyAllBundleConfigurationActions.Add(configureAction);
}
return this;
}
/// <summary> /// <summary>
/// Gets a bundle. /// Gets a bundle.
/// </summary> /// </summary>
@ -140,4 +171,4 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.Bundling
return bundle; return bundle;
} }
} }
} }

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

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

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

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

1
framework/src/Volo.Abp.AspNetCore.Mvc.UI/Volo/Abp/AspNetCore/Mvc/UI/RazorPages/AbpPageModel.cs

@ -27,6 +27,7 @@ namespace Volo.Abp.AspNetCore.Mvc.UI.RazorPages
{ {
public IAbpLazyServiceProvider LazyServiceProvider { get; set; } public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
[Obsolete("Use LazyServiceProvider instead.")]
public IServiceProvider ServiceProvider { get; set; } public IServiceProvider ServiceProvider { get; set; }
protected IClock Clock => LazyServiceProvider.LazyGetRequiredService<IClock>(); protected IClock Clock => LazyServiceProvider.LazyGetRequiredService<IClock>();

1
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpController.cs

@ -25,6 +25,7 @@ namespace Volo.Abp.AspNetCore.Mvc
{ {
public IAbpLazyServiceProvider LazyServiceProvider { get; set; } public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
[Obsolete("Use LazyServiceProvider instead.")]
public IServiceProvider ServiceProvider { get; set; } public IServiceProvider ServiceProvider { get; set; }
protected IUnitOfWorkManager UnitOfWorkManager => LazyServiceProvider.LazyGetRequiredService<IUnitOfWorkManager>(); protected IUnitOfWorkManager UnitOfWorkManager => LazyServiceProvider.LazyGetRequiredService<IUnitOfWorkManager>();

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

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

1
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpViewComponent.cs

@ -10,6 +10,7 @@ namespace Volo.Abp.AspNetCore.Mvc
{ {
public IAbpLazyServiceProvider LazyServiceProvider { get; set; } public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
[Obsolete("Use LazyServiceProvider instead.")]
public IServiceProvider ServiceProvider { get; set; } public IServiceProvider ServiceProvider { get; set; }
protected Type ObjectMapperContext { get; set; } protected Type ObjectMapperContext { get; set; }

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

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

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

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

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

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

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

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

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

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

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

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

1
framework/src/Volo.Abp.AspNetCore.SignalR/Volo/Abp/AspNetCore/SignalR/AbpHub.cs

@ -17,6 +17,7 @@ namespace Volo.Abp.AspNetCore.SignalR
{ {
public IAbpLazyServiceProvider LazyServiceProvider { get; set; } public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
[Obsolete("Use LazyServiceProvider instead.")]
public IServiceProvider ServiceProvider { get; set; } public IServiceProvider ServiceProvider { get; set; }
protected ILoggerFactory LoggerFactory => LazyServiceProvider.LazyGetService<ILoggerFactory>(); protected ILoggerFactory LoggerFactory => LazyServiceProvider.LazyGetService<ILoggerFactory>();

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

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

10
framework/src/Volo.Abp.Authorization/Volo/Abp/Authorization/Localization/nl.json

@ -0,0 +1,10 @@
{
"culture": "nl",
"texts": {
"Volo.Authorization:010001": "Autorisatie mislukt! De benodigde policy is niet aan u verleend.",
"Volo.Authorization:010002": "Autorisatie mislukt! De benodigde policy: '{PolicyName}' is niet aan u verleend.",
"Volo.Authorization:010003": "Autorisatie mislukt! De benodigde policy is niet aan de opgegeven resource: '{ResourceName}' verleend.",
"Volo.Authorization:010004": "Autorisatie mislukt! De benodigde requirement is niet aan de opgegeven resource: '{ResourceName}' verleend.",
"Volo.Authorization:010005": "Autorisatie mislukt! De benodigde requirements zijn niet aan de opgegeven resource: '{ResourceName}' verleend."
}
}

16
framework/src/Volo.Abp.BackgroundJobs.Quartz/Volo/Abp/BackgroundJobs/Quartz/AbpBackgroundJobQuartzOptions.cs

@ -10,7 +10,7 @@ namespace Volo.Abp.BackgroundJobs.Quartz
public int RetryCount { get; set; } public int RetryCount { get; set; }
public int RetryIntervalMillisecond { get; set; } public int RetryIntervalMillisecond { get; set; }
[NotNull] [NotNull]
public Func<int, IJobExecutionContext, JobExecutionException,Task> RetryStrategy public Func<int, IJobExecutionContext, JobExecutionException,Task> RetryStrategy
@ -19,28 +19,28 @@ namespace Volo.Abp.BackgroundJobs.Quartz
set => _retryStrategy = Check.NotNull(value, nameof(value)); set => _retryStrategy = Check.NotNull(value, nameof(value));
} }
private Func<int, IJobExecutionContext, JobExecutionException,Task> _retryStrategy; private Func<int, IJobExecutionContext, JobExecutionException,Task> _retryStrategy;
public AbpBackgroundJobQuartzOptions() public AbpBackgroundJobQuartzOptions()
{ {
RetryCount = 3; RetryCount = 3;
RetryIntervalMillisecond = 3000; RetryIntervalMillisecond = 3000;
_retryStrategy = DefaultRetryStrategy; _retryStrategy = DefaultRetryStrategy;
} }
private async Task DefaultRetryStrategy(int retryIndex, IJobExecutionContext executionContext, JobExecutionException exception) private async Task DefaultRetryStrategy(int retryIndex, IJobExecutionContext executionContext, JobExecutionException exception)
{ {
exception.RefireImmediately = true; exception.RefireImmediately = true;
var retryCount = executionContext.JobDetail.JobDataMap.GetIntValue(QuartzBackgroundJobManager.JobDataPrefix+ nameof(RetryCount)); var retryCount = executionContext.JobDetail.JobDataMap.GetString(QuartzBackgroundJobManager.JobDataPrefix+ nameof(RetryCount)).To<int>();
if (retryIndex > retryCount) if (retryIndex > retryCount)
{ {
exception.RefireImmediately = false; exception.RefireImmediately = false;
exception.UnscheduleAllTriggers = true; exception.UnscheduleAllTriggers = true;
return; return;
} }
var retryInterval = executionContext.JobDetail.JobDataMap.GetIntValue(QuartzBackgroundJobManager.JobDataPrefix+ nameof(RetryIntervalMillisecond)); var retryInterval = executionContext.JobDetail.JobDataMap.GetString(QuartzBackgroundJobManager.JobDataPrefix+ nameof(RetryIntervalMillisecond)).To<int>();
await Task.Delay(retryInterval); await Task.Delay(retryInterval);
} }
} }
} }

14
framework/src/Volo.Abp.BackgroundJobs.Quartz/Volo/Abp/BackgroundJobs/Quartz/QuartzBackgroundJobManager.cs

@ -3,6 +3,7 @@ using System.Threading.Tasks;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Quartz; using Quartz;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Volo.Abp.Json;
namespace Volo.Abp.BackgroundJobs.Quartz namespace Volo.Abp.BackgroundJobs.Quartz
{ {
@ -16,9 +17,12 @@ namespace Volo.Abp.BackgroundJobs.Quartz
protected AbpBackgroundJobQuartzOptions Options { get; } protected AbpBackgroundJobQuartzOptions Options { get; }
public QuartzBackgroundJobManager(IScheduler scheduler, IOptions<AbpBackgroundJobQuartzOptions> options) protected IJsonSerializer JsonSerializer { get; }
public QuartzBackgroundJobManager(IScheduler scheduler, IOptions<AbpBackgroundJobQuartzOptions> options, IJsonSerializer jsonSerializer)
{ {
Scheduler = scheduler; Scheduler = scheduler;
JsonSerializer = jsonSerializer;
Options = options.Value; Options = options.Value;
} }
@ -33,10 +37,10 @@ namespace Volo.Abp.BackgroundJobs.Quartz
{ {
var jobDataMap = new JobDataMap var jobDataMap = new JobDataMap
{ {
{nameof(TArgs), args}, {nameof(TArgs), JsonSerializer.Serialize(args)},
{JobDataPrefix+ nameof(Options.RetryCount), retryCount}, {JobDataPrefix+ nameof(Options.RetryCount), retryCount.ToString()},
{JobDataPrefix+ nameof(Options.RetryIntervalMillisecond), retryIntervalMillisecond}, {JobDataPrefix+ nameof(Options.RetryIntervalMillisecond), retryIntervalMillisecond.ToString()},
{JobDataPrefix+ RetryIndex, 0} {JobDataPrefix+ RetryIndex, "0"}
}; };
var jobDetail = JobBuilder.Create<QuartzJobExecutionAdapter<TArgs>>().RequestRecovery().SetJobData(jobDataMap).Build(); var jobDetail = JobBuilder.Create<QuartzJobExecutionAdapter<TArgs>>().RequestRecovery().SetJobData(jobDataMap).Build();

20
framework/src/Volo.Abp.BackgroundJobs.Quartz/Volo/Abp/BackgroundJobs/Quartz/QuartzJobExecutionAdapter.cs

@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Quartz; using Quartz;
using Volo.Abp.Json;
namespace Volo.Abp.BackgroundJobs.Quartz namespace Volo.Abp.BackgroundJobs.Quartz
{ {
@ -16,15 +17,18 @@ namespace Volo.Abp.BackgroundJobs.Quartz
protected AbpBackgroundJobQuartzOptions BackgroundJobQuartzOptions { get; } protected AbpBackgroundJobQuartzOptions BackgroundJobQuartzOptions { get; }
protected IServiceScopeFactory ServiceScopeFactory { get; } protected IServiceScopeFactory ServiceScopeFactory { get; }
protected IBackgroundJobExecuter JobExecuter { get; } protected IBackgroundJobExecuter JobExecuter { get; }
protected IJsonSerializer JsonSerializer { get; }
public QuartzJobExecutionAdapter( public QuartzJobExecutionAdapter(
IOptions<AbpBackgroundJobOptions> options, IOptions<AbpBackgroundJobOptions> options,
IOptions<AbpBackgroundJobQuartzOptions> backgroundJobQuartzOptions, IOptions<AbpBackgroundJobQuartzOptions> backgroundJobQuartzOptions,
IBackgroundJobExecuter jobExecuter, IBackgroundJobExecuter jobExecuter,
IServiceScopeFactory serviceScopeFactory) IServiceScopeFactory serviceScopeFactory,
IJsonSerializer jsonSerializer)
{ {
JobExecuter = jobExecuter; JobExecuter = jobExecuter;
ServiceScopeFactory = serviceScopeFactory; ServiceScopeFactory = serviceScopeFactory;
JsonSerializer = jsonSerializer;
Options = options.Value; Options = options.Value;
BackgroundJobQuartzOptions = backgroundJobQuartzOptions.Value; BackgroundJobQuartzOptions = backgroundJobQuartzOptions.Value;
Logger = NullLogger<QuartzJobExecutionAdapter<TArgs>>.Instance; Logger = NullLogger<QuartzJobExecutionAdapter<TArgs>>.Instance;
@ -34,7 +38,7 @@ namespace Volo.Abp.BackgroundJobs.Quartz
{ {
using (var scope = ServiceScopeFactory.CreateScope()) using (var scope = ServiceScopeFactory.CreateScope())
{ {
var args = (TArgs) context.JobDetail.JobDataMap.Get(nameof(TArgs)); var args = JsonSerializer.Deserialize<TArgs>(context.JobDetail.JobDataMap.GetString(nameof(TArgs)));
var jobType = Options.GetJob(typeof(TArgs)).JobType; var jobType = Options.GetJob(typeof(TArgs)).JobType;
var jobContext = new JobExecutionContext(scope.ServiceProvider, jobType, args); var jobContext = new JobExecutionContext(scope.ServiceProvider, jobType, args);
try try
@ -44,16 +48,16 @@ namespace Volo.Abp.BackgroundJobs.Quartz
catch (Exception exception) catch (Exception exception)
{ {
var jobExecutionException = new JobExecutionException(exception); var jobExecutionException = new JobExecutionException(exception);
var retryIndex = context.JobDetail.JobDataMap.GetIntValue(QuartzBackgroundJobManager.JobDataPrefix+ QuartzBackgroundJobManager.RetryIndex); var retryIndex = context.JobDetail.JobDataMap.GetString(QuartzBackgroundJobManager.JobDataPrefix+ QuartzBackgroundJobManager.RetryIndex).To<int>();
retryIndex++; retryIndex++;
context.JobDetail.JobDataMap.Put(QuartzBackgroundJobManager.JobDataPrefix+ QuartzBackgroundJobManager.RetryIndex, retryIndex); context.JobDetail.JobDataMap.Put(QuartzBackgroundJobManager.JobDataPrefix+ QuartzBackgroundJobManager.RetryIndex, retryIndex.ToString());
await BackgroundJobQuartzOptions.RetryStrategy.Invoke(retryIndex, context, jobExecutionException); await BackgroundJobQuartzOptions.RetryStrategy.Invoke(retryIndex, context, jobExecutionException);
throw jobExecutionException; throw jobExecutionException;
} }
} }
} }
} }
} }

26
framework/src/Volo.Abp.BlazoriseUI/AbpCrudPageBase.cs

@ -280,7 +280,7 @@ namespace Volo.Abp.BlazoriseUI
await GetEntitiesAsync(); await GetEntitiesAsync();
StateHasChanged(); await InvokeAsync(StateHasChanged);
} }
protected virtual async Task OnDataGridReadAsync(DataGridReadDataEventArgs<TListViewModel> e) protected virtual async Task OnDataGridReadAsync(DataGridReadDataEventArgs<TListViewModel> e)
@ -293,7 +293,7 @@ namespace Volo.Abp.BlazoriseUI
await GetEntitiesAsync(); await GetEntitiesAsync();
StateHasChanged(); await InvokeAsync(StateHasChanged);
} }
protected virtual async Task OpenCreateModalAsync() protected virtual async Task OpenCreateModalAsync()
@ -306,7 +306,7 @@ namespace Volo.Abp.BlazoriseUI
// Mapper will not notify Blazor that binded values are changed // Mapper will not notify Blazor that binded values are changed
// so we need to notify it manually by calling StateHasChanged // so we need to notify it manually by calling StateHasChanged
await InvokeAsync(() => StateHasChanged()); await InvokeAsync(StateHasChanged);
CreateModal.Show(); CreateModal.Show();
} }
@ -328,7 +328,7 @@ namespace Volo.Abp.BlazoriseUI
EditingEntityId = entity.Id; EditingEntityId = entity.Id;
EditingEntity = MapToEditingEntity(entityDto); EditingEntity = MapToEditingEntity(entityDto);
await InvokeAsync(() => StateHasChanged()); await InvokeAsync(StateHasChanged);
EditModal.Show(); EditModal.Show();
} }
@ -373,11 +373,8 @@ namespace Volo.Abp.BlazoriseUI
await CheckCreatePolicyAsync(); await CheckCreatePolicyAsync();
var createInput = MapToCreateInput(NewEntity); var createInput = MapToCreateInput(NewEntity);
await AppService.CreateAsync(createInput); await AppService.CreateAsync(createInput);
await GetEntitiesAsync();
await OnCreatedEntityAsync(); await OnCreatedEntityAsync();
CreateModal.Hide();
} }
} }
@ -386,9 +383,11 @@ namespace Volo.Abp.BlazoriseUI
return Task.CompletedTask; return Task.CompletedTask;
} }
protected virtual Task OnCreatedEntityAsync() protected virtual async Task OnCreatedEntityAsync()
{ {
return Task.CompletedTask; await GetEntitiesAsync();
CreateModal.Hide();
} }
protected virtual async Task UpdateEntityAsync() protected virtual async Task UpdateEntityAsync()
@ -400,11 +399,8 @@ namespace Volo.Abp.BlazoriseUI
await CheckUpdatePolicyAsync(); await CheckUpdatePolicyAsync();
var updateInput = MapToUpdateInput(EditingEntity); var updateInput = MapToUpdateInput(EditingEntity);
await AppService.UpdateAsync(EditingEntityId, updateInput); await AppService.UpdateAsync(EditingEntityId, updateInput);
await GetEntitiesAsync();
await OnUpdatedEntityAsync(); await OnUpdatedEntityAsync();
EditModal.Hide();
} }
} }
@ -413,9 +409,11 @@ namespace Volo.Abp.BlazoriseUI
return Task.CompletedTask; return Task.CompletedTask;
} }
protected virtual Task OnUpdatedEntityAsync() protected virtual async Task OnUpdatedEntityAsync()
{ {
return Task.CompletedTask; await GetEntitiesAsync();
EditModal.Hide();
} }
protected virtual async Task DeleteEntityAsync(TListViewModel entity) protected virtual async Task DeleteEntityAsync(TListViewModel entity)

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

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

3
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Auth/AuthService.cs

@ -22,7 +22,7 @@ namespace Volo.Abp.Cli.Auth
{ {
var configuration = new IdentityClientConfiguration( var configuration = new IdentityClientConfiguration(
CliUrls.AccountAbpIo, CliUrls.AccountAbpIo,
"role email abpio abpio_www abpio_commercial offline_access", "role email abpio abpio_www abpio_commercial offline_access",
"abp-cli", "abp-cli",
"1q2w3e*", "1q2w3e*",
OidcConstants.GrantTypes.Password, OidcConstants.GrantTypes.Password,
@ -43,6 +43,7 @@ namespace Volo.Abp.Cli.Auth
public Task LogoutAsync() public Task LogoutAsync()
{ {
FileHelper.DeleteIfExists(CliPaths.AccessToken); FileHelper.DeleteIfExists(CliPaths.AccessToken);
FileHelper.DeleteIfExists(CliPaths.Lic);
return Task.CompletedTask; return Task.CompletedTask;
} }

6
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/CliPaths.cs

@ -1,5 +1,6 @@
using System; using System;
using System.IO; using System.IO;
using System.Text;
namespace Volo.Abp.Cli namespace Volo.Abp.Cli
{ {
@ -10,7 +11,8 @@ namespace Volo.Abp.Cli
public static string Root => Path.Combine(AbpRootPath, "cli"); public static string Root => Path.Combine(AbpRootPath, "cli");
public static string AccessToken => Path.Combine(AbpRootPath, "cli", "access-token.bin"); public static string AccessToken => Path.Combine(AbpRootPath, "cli", "access-token.bin");
public static string Build => Path.Combine(AbpRootPath, "build"); public static string Build => Path.Combine(AbpRootPath, "build");
public static string Lic => Path.Combine(Path.GetTempPath(), Encoding.ASCII.GetString(new byte[] { 65, 98, 112, 76, 105, 99, 101, 110, 115, 101, 46, 98, 105, 110 }));
private static readonly string AbpRootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".abp"); private static readonly string AbpRootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".abp");
} }
} }

6
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/CreateMigrationAndRunMigrator.cs

@ -26,12 +26,16 @@ namespace Volo.Abp.Cli.Commands
throw new Exception("DbMigrator is not found!"); throw new Exception("DbMigrator is not found!");
} }
var output = CmdHelper.RunCmdAndGetOutput("cd \"" + commandLineArgs.Target + "\" && dotnet ef migrations add Initial -s " + dbMigratorProjectPath); var output = CmdHelper.RunCmdAndGetOutput($"cd \"{commandLineArgs.Target}\" && dotnet ef migrations add Initial -s \"{dbMigratorProjectPath}\"");
if (output.Contains("Done.") && output.Contains("To undo this action") && output.Contains("ef migrations remove")) // Migration added successfully if (output.Contains("Done.") && output.Contains("To undo this action") && output.Contains("ef migrations remove")) // Migration added successfully
{ {
CmdHelper.RunCmd("cd \"" + Path.GetDirectoryName(dbMigratorProjectPath) + "\" && dotnet run"); CmdHelper.RunCmd("cd \"" + Path.GetDirectoryName(dbMigratorProjectPath) + "\" && dotnet run");
} }
else
{
throw new Exception("Migrations failed: " + output);
}
} }
private string GetDbMigratorProjectPath(string dbMigrationsFolderPath) private string GetDbMigratorProjectPath(string dbMigrationsFolderPath)

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

@ -12,11 +12,13 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.Cli.Args; using Volo.Abp.Cli.Args;
using Volo.Abp.Cli.Auth; using Volo.Abp.Cli.Auth;
using Volo.Abp.Cli.Commands.Services;
using Volo.Abp.Cli.Http; using Volo.Abp.Cli.Http;
using Volo.Abp.Cli.ProjectBuilding; using Volo.Abp.Cli.ProjectBuilding;
using Volo.Abp.Cli.ProjectBuilding.Building; using Volo.Abp.Cli.ProjectBuilding.Building;
using Volo.Abp.Cli.ProjectBuilding.Templates.App; using Volo.Abp.Cli.ProjectBuilding.Templates.App;
using Volo.Abp.Cli.ProjectBuilding.Templates.Console; using Volo.Abp.Cli.ProjectBuilding.Templates.Console;
using Volo.Abp.Cli.ProjectBuilding.Templates.Microservice;
using Volo.Abp.Cli.ProjectModification; using Volo.Abp.Cli.ProjectModification;
using Volo.Abp.Cli.Utils; using Volo.Abp.Cli.Utils;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
@ -31,14 +33,17 @@ namespace Volo.Abp.Cli.Commands
protected TemplateProjectBuilder TemplateProjectBuilder { get; } protected TemplateProjectBuilder TemplateProjectBuilder { get; }
public ITemplateInfoProvider TemplateInfoProvider { get; } public ITemplateInfoProvider TemplateInfoProvider { get; }
public ConnectionStringProvider ConnectionStringProvider { get; }
public NewCommand(TemplateProjectBuilder templateProjectBuilder public NewCommand(TemplateProjectBuilder templateProjectBuilder
, ITemplateInfoProvider templateInfoProvider, , ITemplateInfoProvider templateInfoProvider,
EfCoreMigrationManager efCoreMigrationManager) EfCoreMigrationManager efCoreMigrationManager,
ConnectionStringProvider connectionStringProvider)
{ {
_efCoreMigrationManager = efCoreMigrationManager; _efCoreMigrationManager = efCoreMigrationManager;
TemplateProjectBuilder = templateProjectBuilder; TemplateProjectBuilder = templateProjectBuilder;
TemplateInfoProvider = templateInfoProvider; TemplateInfoProvider = templateInfoProvider;
ConnectionStringProvider = connectionStringProvider;
Logger = NullLogger<NewCommand>.Instance; Logger = NullLogger<NewCommand>.Instance;
} }
@ -164,7 +169,7 @@ namespace Volo.Abp.Cli.Commands
databaseManagementSystem != DatabaseManagementSystem.NotSpecified && databaseManagementSystem != DatabaseManagementSystem.NotSpecified &&
databaseManagementSystem != DatabaseManagementSystem.SQLServer) databaseManagementSystem != DatabaseManagementSystem.SQLServer)
{ {
connectionString = GetNewConnectionStringByDbms(databaseManagementSystem, outputFolder); connectionString = ConnectionStringProvider.GetByDbms(databaseManagementSystem, outputFolder);
} }
commandLineArgs.Options.Add(CliConsts.Command, commandLineArgs.Command); commandLineArgs.Options.Add(CliConsts.Command, commandLineArgs.Command);
@ -226,8 +231,6 @@ namespace Volo.Abp.Cli.Commands
} }
} }
DeleteMigrationsIfNeeded(databaseProvider, databaseManagementSystem, outputFolder);
Logger.LogInformation($"'{projectName}' has been successfully created to '{outputFolder}'"); Logger.LogInformation($"'{projectName}' has been successfully created to '{outputFolder}'");
@ -236,41 +239,10 @@ namespace Volo.Abp.Cli.Commands
var isCommercial = template == AppProTemplate.TemplateName; var isCommercial = template == AppProTemplate.TemplateName;
OpenThanksPage(uiFramework, databaseProvider, isTiered || commandLineArgs.Options.ContainsKey("separate-identity-server"), isCommercial); OpenThanksPage(uiFramework, databaseProvider, isTiered || commandLineArgs.Options.ContainsKey("separate-identity-server"), isCommercial);
} }
} else if (MicroserviceTemplateBase.IsMicroserviceTemplate(template))
private string GetNewConnectionStringByDbms(DatabaseManagementSystem databaseManagementSystem, string outputFolder)
{
switch (databaseManagementSystem)
{
case DatabaseManagementSystem.MySQL:
return "Server=localhost;Port=3306;Database=MyProjectName;Uid=root;Pwd=myPassword;";
case DatabaseManagementSystem.PostgreSQL:
return "User ID=root;Password=myPassword;Host=localhost;Port=5432;Database=MyProjectName;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;";
//case DatabaseManagementSystem.Oracle:
case DatabaseManagementSystem.OracleDevart:
return "Data Source=MyProjectName;Integrated Security=yes;";
case DatabaseManagementSystem.SQLite:
return $"Data Source={Path.Combine(outputFolder,"database\\MyProjectName.db")};Version=3;";
default:
return null;
}
}
private void DeleteMigrationsIfNeeded(DatabaseProvider databaseProvider, DatabaseManagementSystem databaseManagementSystem, string outputFolder)
{
if (databaseManagementSystem == DatabaseManagementSystem.NotSpecified || databaseManagementSystem == DatabaseManagementSystem.SQLServer)
{
return;
}
if (databaseProvider != DatabaseProvider.NotSpecified && databaseProvider != DatabaseProvider.EntityFrameworkCore)
{ {
return; OpenMicroserviceDocumentPage();
} }
Logger.LogInformation($"Deleting migrations...");
_efCoreMigrationManager.RemoveAllMigrations(outputFolder);
} }
private void OpenThanksPage(UiFramework uiFramework, DatabaseProvider databaseProvider, bool tiered, bool commercial) private void OpenThanksPage(UiFramework uiFramework, DatabaseProvider databaseProvider, bool tiered, bool commercial)
@ -282,19 +254,14 @@ namespace Volo.Abp.Cli.Commands
var tieredYesNo = tiered ? "yes" : "no"; var tieredYesNo = tiered ? "yes" : "no";
var url = $"https://{urlPrefix}.abp.io/project-created-success?ui={uiFramework:g}&db={databaseProvider:g}&tiered={tieredYesNo}"; var url = $"https://{urlPrefix}.abp.io/project-created-success?ui={uiFramework:g}&db={databaseProvider:g}&tiered={tieredYesNo}";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) CmdHelper.OpenWebPage(url);
{ }
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); private void OpenMicroserviceDocumentPage()
} {
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) var url = "https://docs.abp.io/en/commercial/latest/startup-templates/microservice/index";
{
Process.Start("xdg-open", url); CmdHelper.OpenWebPage(url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
} }
private bool GetCreateSolutionFolderPreference(CommandLineArgs commandLineArgs) private bool GetCreateSolutionFolderPreference(CommandLineArgs commandLineArgs)

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

@ -0,0 +1,30 @@
using System.IO;
using Volo.Abp.Cli.ProjectBuilding.Building;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.Cli.Commands.Services
{
public class ConnectionStringProvider : ITransientDependency
{
public string GetByDbms(DatabaseManagementSystem databaseManagementSystem, string outputFolder = "")
{
switch (databaseManagementSystem)
{
case DatabaseManagementSystem.NotSpecified:
case DatabaseManagementSystem.SQLServer:
return "Server=localhost;Database=MyProjectName;Trusted_Connection=True";
case DatabaseManagementSystem.MySQL:
return "Server=localhost;Port=3306;Database=MyProjectName;Uid=root;Pwd=myPassword;";
case DatabaseManagementSystem.PostgreSQL:
return "Host=localhost;Port=5432;Database=MyProjectName;User ID=root;Password=myPassword;Pooling=true;MinimumPoolSize=0;MaximumPoolSize=100;Connection Lifetime=0;";
//case DatabaseManagementSystem.Oracle:
case DatabaseManagementSystem.OracleDevart:
return "Data Source=MyProjectName;Integrated Security=yes;";
case DatabaseManagementSystem.SQLite:
return $"Data Source={Path.Combine(outputFolder , "MyProjectName.db")};".Replace("\\", "\\\\");
default:
return null;
}
}
}
}

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

@ -21,5 +21,7 @@
public bool AngularUi { get; set; } public bool AngularUi { get; set; }
public bool MvcUi { get; set; } public bool MvcUi { get; set; }
public bool BlazorUi { get; set; }
} }
} }

7
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/ProjectBuildContextExtensions.cs

@ -16,5 +16,10 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building
return file; return file;
} }
public static FileEntry FindFile(this ProjectBuildContext context, string filePath)
{
return context.Files.FirstOrDefault(f => f.Name == filePath);
}
} }
} }

30
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/RemoveProjectFromSolutionStep.cs

@ -7,8 +7,8 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
public class RemoveProjectFromSolutionStep : ProjectBuildPipelineStep public class RemoveProjectFromSolutionStep : ProjectBuildPipelineStep
{ {
private readonly string _projectName; private readonly string _projectName;
private readonly string _solutionFilePath; private string _solutionFilePath;
private readonly string _projectFolderPath; private string _projectFolderPath;
private string ProjectNameWithQuotes => $"\"{_projectName}\""; private string ProjectNameWithQuotes => $"\"{_projectName}\"";
@ -18,12 +18,19 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
string projectFolderPath = null) string projectFolderPath = null)
{ {
_projectName = projectName; _projectName = projectName;
_solutionFilePath = solutionFilePath ?? "/aspnet-core/MyCompanyName.MyProjectName.sln"; _solutionFilePath = solutionFilePath;
_projectFolderPath = projectFolderPath ?? ("/aspnet-core/src/" + projectName); _projectFolderPath = projectFolderPath;
} }
public override void Execute(ProjectBuildContext context) public override void Execute(ProjectBuildContext context)
{ {
SetSolutionAndProjectPathsIfNull(context);
if (_solutionFilePath == null || _projectFolderPath == null)
{
return;
}
new RemoveFolderStep(_projectFolderPath).Execute(context); new RemoveFolderStep(_projectFolderPath).Execute(context);
var solutionFile = context.GetFile(_solutionFilePath); var solutionFile = context.GetFile(_solutionFilePath);
solutionFile.NormalizeLineEndings(); solutionFile.NormalizeLineEndings();
@ -75,5 +82,20 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
return null; return null;
} }
private void SetSolutionAndProjectPathsIfNull(ProjectBuildContext context)
{
if (_solutionFilePath == null)
{
_solutionFilePath = context.FindFile("/aspnet-core/MyCompanyName.MyProjectName.sln")?.Name ??
context.FindFile("/MyCompanyName.MyProjectName.sln")?.Name;
}
if (_projectFolderPath == null)
{
_projectFolderPath = context.FindFile("/aspnet-core/src/" + _projectName.EnsureEndsWith('/'))?.Name ??
context.FindFile("/src/" + _projectName.EnsureEndsWith('/'))?.Name;
}
}
} }
} }

9
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectBuilding/Building/Steps/RemovePublicRedisStep.cs

@ -1,4 +1,5 @@
using System.Linq; using System;
using System.Linq;
using Volo.Abp.Cli.ProjectBuilding.Files; using Volo.Abp.Cli.ProjectBuilding.Files;
namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
@ -12,6 +13,12 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
context.Files.FirstOrDefault(f => f.Name.EndsWith("MyCompanyName.MyProjectName.HttpApi.HostWithIds.csproj"))?.RemoveTemplateCodeIfNot("PUBLIC-REDIS"); context.Files.FirstOrDefault(f => f.Name.EndsWith("MyCompanyName.MyProjectName.HttpApi.HostWithIds.csproj"))?.RemoveTemplateCodeIfNot("PUBLIC-REDIS");
context.Files.FirstOrDefault(f => f.Name.EndsWith("MyCompanyName.MyProjectName.HttpApi.Host.csproj"))?.RemoveTemplateCodeIfNot("PUBLIC-REDIS"); context.Files.FirstOrDefault(f => f.Name.EndsWith("MyCompanyName.MyProjectName.HttpApi.Host.csproj"))?.RemoveTemplateCodeIfNot("PUBLIC-REDIS");
context.Files.FirstOrDefault(f => f.Name.EndsWith("MyProjectNameHttpApiHostModule.cs"))?.RemoveTemplateCodeIfNot("PUBLIC-REDIS"); context.Files.FirstOrDefault(f => f.Name.EndsWith("MyProjectNameHttpApiHostModule.cs"))?.RemoveTemplateCodeIfNot("PUBLIC-REDIS");
var appSettingsFiles = context.Files.Where(f => f.Name.EndsWith("appSettings.json", StringComparison.InvariantCultureIgnoreCase)).ToList();
foreach (var appSettings in appSettingsFiles)
{
appSettings.RemoveTemplateCodeIfNot("PUBLIC-REDIS");
}
} }
} }
} }

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

@ -54,10 +54,12 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
if (_companyName != null) if (_companyName != null)
{ {
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder, _companyName); RenameHelper.RenameAll(_entries, _companyNamePlaceHolder, _companyName);
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder.ToCamelCase(), _companyName.ToCamelCase());
} }
else else
{ {
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder + "." + _projectNamePlaceHolder, _projectNamePlaceHolder); RenameHelper.RenameAll(_entries, _companyNamePlaceHolder + "." + _projectNamePlaceHolder, _projectNamePlaceHolder);
RenameHelper.RenameAll(_entries, _companyNamePlaceHolder.ToCamelCase() + "." + _projectNamePlaceHolder.ToCamelCase(), _projectNamePlaceHolder.ToCamelCase());
} }
} }

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

@ -8,7 +8,7 @@ namespace Volo.Abp.Cli.ProjectBuilding.Building.Steps
{ {
foreach (var file in context.Files) foreach (var file in context.Files)
{ {
if (file.Name.EndsWith(".cs") || file.Name.EndsWith(".csproj") || file.Name.EndsWith(".cshtml")) if (file.Name.EndsWith(".cs") || file.Name.EndsWith(".csproj") || file.Name.EndsWith(".cshtml") || file.Name.EndsWith(".json"))
{ {
file.RemoveTemplateCode(); file.RemoveTemplateCode();
file.RemoveTemplateCodeMarkers(); file.RemoveTemplateCodeMarkers();

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

Loading…
Cancel
Save