@ -0,0 +1,267 @@ |
|||
# ABP.IO Platform 7.3 RC Has Been Released |
|||
|
|||
Today, we are happy to release the [ABP Framework](https://abp.io/) and [ABP Commercial](https://commercial.abp.io/) version **7.3 RC** (Release Candidate). This blog post introduces the new features and important changes in this new version. |
|||
|
|||
Try this version and provide feedback for a more stable version of ABP v7.3! Thanks to all of you. |
|||
|
|||
## Get Started with the 7.3 RC |
|||
|
|||
Follow the steps below to try version 7.3.0 RC today: |
|||
|
|||
1) **Upgrade** the ABP CLI to version `7.3.0-rc.1` using a command line terminal: |
|||
|
|||
````bash |
|||
dotnet tool update Volo.Abp.Cli -g --version 7.3.0-rc.1 |
|||
```` |
|||
|
|||
**or install** it if you haven't before: |
|||
|
|||
````bash |
|||
dotnet tool install Volo.Abp.Cli -g --version 7.3.0-rc.1 |
|||
```` |
|||
|
|||
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 [Get Started](https://abp.io/get-started) page to generate a CLI command to create a new application. |
|||
|
|||
You can use any IDE that supports .NET 7.x, like [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/). |
|||
|
|||
## Migration Guides |
|||
|
|||
There are a few breaking changes in this version that may affect your application. |
|||
Please see the following migration documents, if you are upgrading from v7.2: |
|||
|
|||
* [ABP Framework 7.2 to 7.3 Migration Guide](https://docs.abp.io/en/abp/7.3/Migration-Guides/Abp-7_3) |
|||
|
|||
> If you are using the CMS Kit or CMS Kit Pro module, please don't forget to create a new migration and apply it to your database. |
|||
|
|||
## What's New with ABP Framework 7.3? |
|||
|
|||
In this section, I will introduce some major features released in this version. Here is a brief list of the titles that will be explained in the next sections: |
|||
|
|||
* Introducing the Volo.Abp.Imaging packages |
|||
* ABP CLI: switch-to-local command |
|||
* Monitoring Distributed Events |
|||
* Ordering of the Local Event Handlers |
|||
* Nonce attribute support for Content Security Policy (CSP) |
|||
* Other News |
|||
|
|||
### Introducing the Volo.Abp.Imaging packages |
|||
|
|||
ABP Framework provides some packages to compress and resize images. Currently, there are four official packages: |
|||
|
|||
* `Volo.Abp.Imaging.Abstractions`: Provides common services for compression and resizing purposes. |
|||
* `Volo.Abp.Imaging.AspNetCore`: Provides some attributes for controller actions that can automatically compress and/or resize uploaded files. |
|||
* `Volo.Abp.Imaging.ImageSharp`: Implements the image compression & resize operations using the [ImageSharp](https://github.com/SixLabors/ImageSharp) library. |
|||
* `Volo.Abp.Imaging.MagickNet`: Implements the image compression & resize operations using the [Magick.NET](https://github.com/dlemstra/Magick.NET) library. |
|||
|
|||
You can use one of these official providers (`ImageSharp` or `Magick.NET`) or implement your own image resizer/compressor contributor and use it in your application. |
|||
|
|||
> See the [Image Manipulation](https://docs.abp.io/en/abp/7.3/Image-Manipulation) documentation to learn more and see the required configurations. |
|||
|
|||
### ABP CLI: switch-to-local command |
|||
|
|||
In this version, ABP CLI introduces a new CLI command: **"switch-to-local"**. The `switch-to-local` command changes all NuGet package references on a solution to local project references for all the `.csproj` files in the specified folder (and all its subfolders with any depth). |
|||
|
|||
**Usage:** |
|||
|
|||
```bash |
|||
abp switch-to-local --paths "C:\Github\abp" |
|||
``` |
|||
|
|||
### Monitoring Distributed Events |
|||
|
|||
ABP Framework allows you to stay informed when your application **receives** or **sends** a distributed event. This enables you to track the event flow within your application and take appropriate actions based on the received or sent distributed events. |
|||
|
|||
You just need to subscribe to one of the `DistributedEventReceived` or `DistributedEventSent` events and take additional actions according to your cases. |
|||
|
|||
**Example: Get informed when your application sends an event to the distributed event bus** |
|||
|
|||
```csharp |
|||
public class DistributedEventSentHandler : ILocalEventHandler<DistributedEventSent>, ITransientDependency |
|||
{ |
|||
public async Task HandleEventAsync(DistributedEventSent eventData) |
|||
{ |
|||
// TODO: IMPLEMENT YOUR LOGIC... |
|||
} |
|||
} |
|||
``` |
|||
|
|||
> See the documentation to learn more: [https://docs.abp.io/en/abp/7.3/Distributed-Event-Bus](https://docs.abp.io/en/abp/7.3/Distributed-Event-Bus) |
|||
|
|||
### Ordering of the Local Event Handlers |
|||
|
|||
In this version, ABP Framework introduces the `LocalEventHandlerOrder` attribute, which can be used to set the execution order for the event handlers. This can be helpful if you want to handle your local event handlers in a specific order. |
|||
|
|||
**Example:** |
|||
|
|||
```csharp |
|||
[LocalEventHandlerOrder(-1)] |
|||
public class MyHandler |
|||
: ILocalEventHandler<StockCountChangedEvent>, |
|||
ITransientDependency |
|||
{ |
|||
public async Task HandleEventAsync(StockCountChangedEvent eventData) |
|||
{ |
|||
//TODO: your implementation |
|||
} |
|||
} |
|||
``` |
|||
|
|||
By default, all event handlers have an order value of 0. Thus, if you want to take certain event handlers to be executed before other event handlers, you can set the order value as a negative value. |
|||
|
|||
> See the documentation to learn more: [https://docs.abp.io/en/abp/7.3/Local-Event-Bus](https://docs.abp.io/en/abp/7.3/Local-Event-Bus) |
|||
|
|||
### Nonce attribute support for Content Security Policy (CSP) |
|||
|
|||
ABP Framework supports adding unique value to nonce attribute for script tags which can be used by Content Security Policy to determine whether or not a given fetch will be allowed to proceed for a given element. In other words, it provides a mechanism to execute only correct script tags with the correct nonce value. |
|||
|
|||
This feature is disabled by default. You can enable it by setting the *UseContentSecurityPolicyScriptNonce* property of the `AbpSecurityHeadersOptions` class to **true**: |
|||
|
|||
```csharp |
|||
Configure<AbpSecurityHeadersOptions>(options => |
|||
{ |
|||
//adding script-src nonce |
|||
options.UseContentSecurityPolicyScriptNonce = true; //false by default |
|||
}); |
|||
``` |
|||
|
|||
> See the [Security Headers](https://docs.abp.io/en/abp/7.3/UI/AspNetCore/Security-Headers) documentation for more information. |
|||
|
|||
### Other News |
|||
|
|||
* Upgraded the [Blazorise](https://blazorise.com/) library to v1.2.3 for Blazor UI. After the upgrade, ensure that all Blazorise-related packages are using v1.2.3 in your application. |
|||
* Module Entity Extension support has been added for the CMS Kit module. See [#16572](https://github.com/abpframework/abp/issues/16572) for more information. |
|||
|
|||
If you want to see more details, you can check [the release on GitHub](https://github.com/abpframework/abp/releases/tag/5.3.0-rc.1), which contains a list of all the issues and pull requests were closed with this version. |
|||
|
|||
## What's New with ABP Commercial 7.3? |
|||
|
|||
We've also worked on [ABP Commercial](https://commercial.abp.io/) to align the features and changes made in the ABP Framework. The following sections introduce a few new features coming with ABP Commercial 7.3. |
|||
|
|||
### Account Module - Using Authenticator App for Two-Factor Authentication |
|||
|
|||
In this version, ABP Commercial provides a new **Two-Factor Authentication (2FA) provider** that allows you to log in to an application by scanning a QR Code with an Authenticator App, such as Microsoft Authenticator or Google Authenticator. |
|||
|
|||
You need to apply the following actions to configure an Authenticator and then you are free to log in by using the Authenticator App: |
|||
|
|||
**Step 1 - Enable Two Factor Authentication and Scan the QR Code:** |
|||
|
|||
 |
|||
|
|||
**Step 2 - Verify the QR Code with an authenticator app:** |
|||
|
|||
 |
|||
|
|||
**Step 3 - Save the recovery codes for later use in case of not being able to login by verifying the QR code:** |
|||
|
|||
 |
|||
|
|||
You can disable the two-factor authentication and reset the Authenticator App anytime you want, just by disabling the two-factor authentication or resetting the authenticator: |
|||
|
|||
 |
|||
|
|||
### Upgrade Blazorise to v1.2.3 |
|||
|
|||
Upgraded the [Blazorise](https://blazorise.com/) library to v1.2.3 for Blazor UI. If you are upgrading your project to v7.3.0, please ensure that all the Blazorise-related packages are using v1.2.3 in your application. Otherwise, you might get errors due to incompatible versions. |
|||
|
|||
### CMS Kit: Module Entity Extensions |
|||
|
|||
Module entity extension system is a high-level extension system that allows you to define new properties for existing entities of the dependent modules. ABP Framework and ABP Commercial use this system to allow developers to extend entities in different modules. |
|||
|
|||
In this version, Module Entity Extension support has been added for the CMS Kit Pro module. |
|||
|
|||
You can open the `YourProjectNameModuleExtensionConfigurator` class inside the `Domain.Shared` project of your solution and change the `ConfigureExtraProperties` method as shown below to add a new property to the `Poll` entity of the [CMS Kit Pro module](https://docs.abp.io/en/commercial/latest/modules/cms-kit/index): |
|||
|
|||
```csharp |
|||
public static void ConfigureExtraProperties() |
|||
{ |
|||
OneTimeRunner.Run(() => |
|||
{ |
|||
ObjectExtensionManager.Instance.Modules() |
|||
.ConfigureCmsKitPro(cmsKitPro => |
|||
{ |
|||
cmsKitPro.ConfigurePoll(poll => |
|||
{ |
|||
poll.AddOrUpdateProperty<string>( |
|||
"<property-name>", |
|||
property => |
|||
{ |
|||
//configuration for this property |
|||
} |
|||
) |
|||
}); |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
``` |
|||
|
|||
> See the [Module Entity Extensions documentation](https://docs.abp.io/en/abp/latest/Module-Entity-Extensions) to learn more. |
|||
|
|||
### LeptonX Account Layout |
|||
|
|||
In this version, Account Layout has been re-designed for LeptonX Theme. You can see the new account layout in the following figure: |
|||
|
|||
 |
|||
|
|||
> To use this new account layout, ensure that your LeptonX Theme package versions are v2.3+. |
|||
|
|||
## Community News |
|||
|
|||
### ABP Community Talks 2023.4: Angular 16 and ABP v7.3 |
|||
|
|||
 |
|||
|
|||
In this episode, the core ABP team talked about what's new with ABP v7.3 and Angular 16. You can watch the event from [here](https://www.youtube.com/watch?v=lq6u4vQURcI). |
|||
|
|||
### ABP .NET Conference 2023 |
|||
|
|||
 |
|||
|
|||
We organized ABP .NET Conference 2023 on May 2023 and we are happy to share the success of the conference, which captivated overwhelmingly interested live viewers from all over the world. 13 great line up of speakers which includes .NET experts and Microsoft MVPs delivered captivating talks that resonated with the audiences. Each of the talks attracted a great amount of interest and a lot of questions, sparking curiosity in the attendees. |
|||
|
|||
Thanks to all speakers and attendees for joining our event. |
|||
|
|||
> We shared our takeaways in a blog post, which you can read at [https://blog.abp.io/abp/ABP-.NET-Conference-2023-Wrap-Up](https://blog.abp.io/abp/ABP-.NET-Conference-2023-Wrap-Up). |
|||
|
|||
### Volosoft Attendeed & Sponsored Devnot .NET Conference 2023 |
|||
|
|||
 |
|||
|
|||
We are thrilled to announce that the Volosoft Company proudly attended as one of the Gold Sponsors at the Devnot .NET Conference 2023! We are happy to join and be a sponsor of events and contribute to the software society, empowering developers and driving innovation with the .NET community. |
|||
|
|||
 |
|||
|
|||
Co-Founder of [Volosoft](https://volosoft.com/) and Lead Developer of the ABP Framework, [Halil Ibrahim Kalkan](https://twitter.com/hibrahimkalkan) gave a word about "Dealing with Concurrency and Multi Threading in .NET" at this event. |
|||
|
|||
> You can check [this blog post](https://volosoft.com/blog/Reflecting-on-Devnot-Dotnet-Conference-2023) if you want to learn more about the Devnot .NET Conference 2023. |
|||
|
|||
### New ABP Community Posts |
|||
|
|||
There are exciting articles contributed by the ABP community as always. I will highlight some of them here: |
|||
|
|||
* [Authority Delegation in ABP Commercial](https://community.abp.io/posts/authority-delegation-in-abp-commercial-3wtljpp0) by [Liang Shiwei](https://github.com/realLiangshiwei) |
|||
* [What's new in Angular 16? New Features and Updates](https://community.abp.io/posts/whats-new-in-angular-16-new-features-and-updates-s1izi9br) by [Masum Ulu](https://twitter.com/masumulu) |
|||
* [Kubernetes Integrated Microservice Development with ABP Studio](https://community.abp.io/videos/kubernetes-integrated-microservice-development-with-abp-studio-oix9zkp8) by [Halil Ibrahim Kalkan](https://twitter.com/hibrahimkalkan) |
|||
|
|||
Thanks to the ABP Community for all the content they have published. You can also [post your ABP-related (text or video) content](https://community.abp.io/articles/submit) to the ABP Community. |
|||
|
|||
### New ABP Blog Posts |
|||
|
|||
There are also some exciting blog posts written by the ABP team. You can see the following list for some of those articles: |
|||
|
|||
* [ABP .NET Conference 2023 Wrap Up](https://blog.abp.io/abp/ABP-.NET-Conference-2023-Wrap-Up) by [Bige Beşikçi](https://twitter.com/bigedediki) |
|||
* [Meet Volosoft at the Devnot .NET Conference 2023!](https://volosoft.com/blog/Meet-Volosoft-at-the-Devnot-.NET-Conference-2023) by [Roo Xu](https://github.com/Roo1227) |
|||
|
|||
## Conclusion |
|||
|
|||
This version comes with some new features and a lot of enhancements to the existing features. You can see the [Road Map](https://docs.abp.io/en/abp/7.3/Road-Map) documentation to learn about the release schedule and planned features for the next releases. Please try ABP v7.3 RC and provide feedback to help us release a more stable version. |
|||
|
|||
Thanks for being a part of this community! |
|||
|
After Width: | Height: | Size: 742 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 234 KiB |
|
After Width: | Height: | Size: 2.8 MiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 691 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 80 KiB |
@ -0,0 +1,8 @@ |
|||
# ABP Version 7.4 Migration Guide |
|||
|
|||
This document is a guide for upgrading ABP v7.3 solutions to ABP v7.4. There are a few changes in this version that may affect your applications, please read it carefully and apply the necessary changes to your application. |
|||
|
|||
## TemplateDefinition |
|||
|
|||
The `LocalizationResource(Type)` of `TemplateDefinition` class is changed to `LocalizationResourceName(string)`. |
|||
|
|||
@ -1,51 +0,0 @@ |
|||
using System; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.Extensions.Options; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Tracing; |
|||
|
|||
namespace Volo.Abp.AspNetCore.Tracing; |
|||
|
|||
[Dependency(ReplaceServices = true)] |
|||
public class AspNetCoreCorrelationIdProvider : ICorrelationIdProvider, ITransientDependency |
|||
{ |
|||
protected IHttpContextAccessor HttpContextAccessor { get; } |
|||
protected AbpCorrelationIdOptions Options { get; } |
|||
|
|||
public AspNetCoreCorrelationIdProvider( |
|||
IHttpContextAccessor httpContextAccessor, |
|||
IOptions<AbpCorrelationIdOptions> options) |
|||
{ |
|||
HttpContextAccessor = httpContextAccessor; |
|||
Options = options.Value; |
|||
} |
|||
|
|||
public virtual string Get() |
|||
{ |
|||
if (HttpContextAccessor.HttpContext?.Request?.Headers == null) |
|||
{ |
|||
return CreateNewCorrelationId(); |
|||
} |
|||
|
|||
string correlationId = HttpContextAccessor.HttpContext.Request.Headers[Options.HttpHeaderName]; |
|||
|
|||
if (correlationId.IsNullOrEmpty()) |
|||
{ |
|||
lock (HttpContextAccessor.HttpContext.Request.Headers) |
|||
{ |
|||
if (correlationId.IsNullOrEmpty()) |
|||
{ |
|||
correlationId = CreateNewCorrelationId(); |
|||
HttpContextAccessor.HttpContext.Request.Headers[Options.HttpHeaderName] = correlationId; |
|||
} |
|||
} |
|||
} |
|||
|
|||
return correlationId; |
|||
} |
|||
|
|||
protected virtual string CreateNewCorrelationId() |
|||
{ |
|||
return Guid.NewGuid().ToString("N"); |
|||
} |
|||
} |
|||
@ -1,17 +1,27 @@ |
|||
using System; |
|||
using System.Threading; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.Tracing; |
|||
|
|||
public class DefaultCorrelationIdProvider : ICorrelationIdProvider, ISingletonDependency |
|||
{ |
|||
public string Get() |
|||
private readonly AsyncLocal<string?> _currentCorrelationId = new AsyncLocal<string?>(); |
|||
|
|||
private string? CorrelationId => _currentCorrelationId.Value; |
|||
|
|||
public virtual string? Get() |
|||
{ |
|||
return CreateNewCorrelationId(); |
|||
return CorrelationId; |
|||
} |
|||
|
|||
protected virtual string CreateNewCorrelationId() |
|||
public virtual IDisposable Change(string? correlationId) |
|||
{ |
|||
return Guid.NewGuid().ToString("N"); |
|||
var parent = CorrelationId; |
|||
_currentCorrelationId.Value = correlationId; |
|||
return new DisposeAction(() => |
|||
{ |
|||
_currentCorrelationId.Value = parent; |
|||
}); |
|||
} |
|||
} |
|||
|
|||
@ -1,9 +1,10 @@ |
|||
using JetBrains.Annotations; |
|||
using System; |
|||
|
|||
namespace Volo.Abp.Tracing; |
|||
|
|||
public interface ICorrelationIdProvider |
|||
{ |
|||
[NotNull] |
|||
string Get(); |
|||
string? Get(); |
|||
|
|||
IDisposable Change(string? correlationId); |
|||
} |
|||
|
|||
@ -0,0 +1,12 @@ |
|||
using System; |
|||
using Volo.Abp.EventBus; |
|||
|
|||
namespace Volo.Abp.Data; |
|||
|
|||
[Serializable] |
|||
[EventName("abp.data.applied_database_migrations")] |
|||
public class AppliedDatabaseMigrationsEto |
|||
{ |
|||
public string DatabaseName { get; set; } |
|||
public Guid? TenantId { get; set; } |
|||
} |
|||
@ -0,0 +1,318 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Logging; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Domain.Entities.Events.Distributed; |
|||
using Volo.Abp.EventBus.Distributed; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Uow; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.Migrations; |
|||
|
|||
public abstract class DatabaseMigrationEventHandlerBase<TDbContext> : |
|||
IDistributedEventHandler<TenantCreatedEto>, |
|||
IDistributedEventHandler<TenantConnectionStringUpdatedEto>, |
|||
IDistributedEventHandler<ApplyDatabaseMigrationsEto>, |
|||
ITransientDependency |
|||
where TDbContext : DbContext, IEfCoreDbContext |
|||
{ |
|||
protected string DatabaseName { get; } |
|||
|
|||
protected const string TryCountPropertyName = "__TryCount"; |
|||
|
|||
protected int MaxEventTryCount { get; set; } = 3; |
|||
|
|||
/// <summary>
|
|||
/// As milliseconds.
|
|||
/// </summary>
|
|||
protected int MinValueToWaitOnFailure { get; set; } = 5000; |
|||
|
|||
/// <summary>
|
|||
/// As milliseconds.
|
|||
/// </summary>
|
|||
protected int MaxValueToWaitOnFailure { get; set; } = 15000; |
|||
|
|||
protected ICurrentTenant CurrentTenant { get; } |
|||
protected IUnitOfWorkManager UnitOfWorkManager { get; } |
|||
protected ITenantStore TenantStore { get; } |
|||
protected IDistributedEventBus DistributedEventBus { get; } |
|||
protected ILogger<DatabaseMigrationEventHandlerBase<TDbContext>> Logger { get; } |
|||
|
|||
protected DatabaseMigrationEventHandlerBase( |
|||
string databaseName, |
|||
ICurrentTenant currentTenant, |
|||
IUnitOfWorkManager unitOfWorkManager, |
|||
ITenantStore tenantStore, |
|||
IDistributedEventBus distributedEventBus, |
|||
ILoggerFactory loggerFactory) |
|||
{ |
|||
CurrentTenant = currentTenant; |
|||
UnitOfWorkManager = unitOfWorkManager; |
|||
TenantStore = tenantStore; |
|||
DatabaseName = databaseName; |
|||
DistributedEventBus = distributedEventBus; |
|||
|
|||
Logger = loggerFactory.CreateLogger<DatabaseMigrationEventHandlerBase<TDbContext>>(); |
|||
} |
|||
|
|||
public virtual async Task HandleEventAsync(ApplyDatabaseMigrationsEto eventData) |
|||
{ |
|||
if (eventData.DatabaseName != DatabaseName) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var schemaMigrated = false; |
|||
try |
|||
{ |
|||
schemaMigrated = await MigrateDatabaseSchemaAsync(eventData.TenantId); |
|||
await SeedAsync(eventData.TenantId); |
|||
|
|||
if (schemaMigrated) |
|||
{ |
|||
await DistributedEventBus.PublishAsync( |
|||
new AppliedDatabaseMigrationsEto |
|||
{ |
|||
DatabaseName = DatabaseName, |
|||
TenantId = eventData.TenantId |
|||
} |
|||
); |
|||
} |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
await HandleErrorOnApplyDatabaseMigrationAsync(eventData, ex); |
|||
} |
|||
|
|||
await AfterApplyDatabaseMigrations(eventData, schemaMigrated); |
|||
} |
|||
|
|||
protected virtual Task AfterApplyDatabaseMigrations(ApplyDatabaseMigrationsEto eventData, bool schemaMigrated) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
public virtual async Task HandleEventAsync(TenantCreatedEto eventData) |
|||
{ |
|||
var schemaMigrated = false; |
|||
try |
|||
{ |
|||
schemaMigrated = await MigrateDatabaseSchemaAsync(eventData.Id); |
|||
await SeedAsync(eventData.Id); |
|||
|
|||
if (schemaMigrated) |
|||
{ |
|||
await DistributedEventBus.PublishAsync( |
|||
new AppliedDatabaseMigrationsEto |
|||
{ |
|||
DatabaseName = DatabaseName, |
|||
TenantId = eventData.Id |
|||
} |
|||
); |
|||
} |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
await HandleErrorTenantCreatedAsync(eventData, ex); |
|||
} |
|||
|
|||
await AfterTenantCreated(eventData, schemaMigrated); |
|||
} |
|||
|
|||
protected virtual Task AfterTenantCreated(TenantCreatedEto eventData, bool schemaMigrated) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
public virtual async Task HandleEventAsync(TenantConnectionStringUpdatedEto eventData) |
|||
{ |
|||
if (eventData.ConnectionStringName != DatabaseName && |
|||
eventData.ConnectionStringName != Volo.Abp.Data.ConnectionStrings.DefaultConnectionStringName || |
|||
eventData.NewValue.IsNullOrWhiteSpace()) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var schemaMigrated = false; |
|||
try |
|||
{ |
|||
schemaMigrated = await MigrateDatabaseSchemaAsync(eventData.Id); |
|||
await SeedAsync(eventData.Id); |
|||
|
|||
if (schemaMigrated) |
|||
{ |
|||
await DistributedEventBus.PublishAsync( |
|||
new AppliedDatabaseMigrationsEto |
|||
{ |
|||
DatabaseName = DatabaseName, |
|||
TenantId = eventData.Id |
|||
} |
|||
); |
|||
} |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
await HandleErrorTenantConnectionStringUpdatedAsync(eventData, ex); |
|||
} |
|||
|
|||
await AfterTenantConnectionStringUpdated(eventData, schemaMigrated); |
|||
} |
|||
|
|||
protected virtual Task AfterTenantConnectionStringUpdated(TenantConnectionStringUpdatedEto eventData, |
|||
bool schemaMigrated) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
protected virtual Task SeedAsync(Guid? tenantId) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Apply pending EF Core schema migrations to the database.
|
|||
/// Returns true if any migration has applied.
|
|||
/// </summary>
|
|||
protected virtual async Task<bool> MigrateDatabaseSchemaAsync(Guid? tenantId) |
|||
{ |
|||
var result = false; |
|||
|
|||
using (CurrentTenant.Change(tenantId)) |
|||
{ |
|||
using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false)) |
|||
{ |
|||
async Task<bool> MigrateDatabaseSchemaWithDbContextAsync() |
|||
{ |
|||
var dbContext = await uow.ServiceProvider |
|||
.GetRequiredService<IDbContextProvider<TDbContext>>() |
|||
.GetDbContextAsync(); |
|||
|
|||
if ((await dbContext.Database.GetPendingMigrationsAsync()).Any()) |
|||
{ |
|||
await dbContext.Database.MigrateAsync(); |
|||
return true; |
|||
} |
|||
|
|||
return false; |
|||
} |
|||
|
|||
if (tenantId == null) |
|||
{ |
|||
//Migrating the host database
|
|||
Logger.LogInformation($"Migrating database of host. Database Name = {DatabaseName}"); |
|||
result = await MigrateDatabaseSchemaWithDbContextAsync(); |
|||
} |
|||
else |
|||
{ |
|||
var tenantConfiguration = await TenantStore.FindAsync(tenantId.Value); |
|||
if (!tenantConfiguration.ConnectionStrings.Default.IsNullOrWhiteSpace() || |
|||
!tenantConfiguration.ConnectionStrings.GetOrDefault(DatabaseName).IsNullOrWhiteSpace()) |
|||
{ |
|||
//Migrating the tenant database (only if tenant has a separate database)
|
|||
Logger.LogInformation( |
|||
$"Migrating separate database of tenant. Database Name = {DatabaseName}, TenantId = {tenantId}"); |
|||
result = await MigrateDatabaseSchemaWithDbContextAsync(); |
|||
} |
|||
} |
|||
|
|||
await uow.CompleteAsync(); |
|||
} |
|||
} |
|||
|
|||
return result; |
|||
} |
|||
|
|||
protected virtual async Task HandleErrorOnApplyDatabaseMigrationAsync( |
|||
ApplyDatabaseMigrationsEto eventData, |
|||
Exception exception) |
|||
{ |
|||
var tryCount = IncrementEventTryCount(eventData); |
|||
if (tryCount <= MaxEventTryCount) |
|||
{ |
|||
Logger.LogWarning( |
|||
$"Could not apply database migrations. Re-queueing the operation. TenantId = {eventData.TenantId}, Database Name = {eventData.DatabaseName}."); |
|||
Logger.LogException(exception, LogLevel.Warning); |
|||
|
|||
await Task.Delay(RandomHelper.GetRandom(MinValueToWaitOnFailure, MaxValueToWaitOnFailure)); |
|||
await DistributedEventBus.PublishAsync(eventData); |
|||
} |
|||
else |
|||
{ |
|||
Logger.LogError( |
|||
$"Could not apply database migrations. Canceling the operation. TenantId = {eventData.TenantId}, DatabaseName = {eventData.DatabaseName}."); |
|||
Logger.LogException(exception); |
|||
} |
|||
} |
|||
|
|||
protected virtual async Task HandleErrorTenantCreatedAsync( |
|||
TenantCreatedEto eventData, |
|||
Exception exception) |
|||
{ |
|||
var tryCount = IncrementEventTryCount(eventData); |
|||
if (tryCount <= MaxEventTryCount) |
|||
{ |
|||
Logger.LogWarning( |
|||
$"Could not perform tenant created event. Re-queueing the operation. TenantId = {eventData.Id}, TenantName = {eventData.Name}."); |
|||
Logger.LogException(exception, LogLevel.Warning); |
|||
|
|||
await Task.Delay(RandomHelper.GetRandom(5000, 15000)); |
|||
await DistributedEventBus.PublishAsync(eventData); |
|||
} |
|||
else |
|||
{ |
|||
Logger.LogError( |
|||
$"Could not perform tenant created event. Canceling the operation. TenantId = {eventData.Id}, TenantName = {eventData.Name}."); |
|||
Logger.LogException(exception); |
|||
} |
|||
} |
|||
|
|||
protected virtual async Task HandleErrorTenantConnectionStringUpdatedAsync( |
|||
TenantConnectionStringUpdatedEto eventData, |
|||
Exception exception) |
|||
{ |
|||
var tryCount = IncrementEventTryCount(eventData); |
|||
if (tryCount <= MaxEventTryCount) |
|||
{ |
|||
Logger.LogWarning( |
|||
$"Could not perform tenant connection string updated event. Re-queueing the operation. TenantId = {eventData.Id}, TenantName = {eventData.Name}."); |
|||
Logger.LogException(exception, LogLevel.Warning); |
|||
|
|||
await Task.Delay(RandomHelper.GetRandom(5000, 15000)); |
|||
await DistributedEventBus.PublishAsync(eventData); |
|||
} |
|||
else |
|||
{ |
|||
Logger.LogError( |
|||
$"Could not perform tenant connection string updated event. Canceling the operation. TenantId = {eventData.Id}, TenantName = {eventData.Name}."); |
|||
Logger.LogException(exception); |
|||
} |
|||
} |
|||
|
|||
private static int GetEventTryCount(EtoBase eventData) |
|||
{ |
|||
var tryCountAsString = eventData.Properties.GetOrDefault(TryCountPropertyName); |
|||
if (tryCountAsString.IsNullOrEmpty()) |
|||
{ |
|||
return 0; |
|||
} |
|||
|
|||
return int.Parse(tryCountAsString); |
|||
} |
|||
|
|||
private static void SetEventTryCount(EtoBase eventData, int count) |
|||
{ |
|||
eventData.Properties[TryCountPropertyName] = count.ToString(); |
|||
} |
|||
|
|||
private static int IncrementEventTryCount(EtoBase eventData) |
|||
{ |
|||
var count = GetEventTryCount(eventData) + 1; |
|||
SetEventTryCount(eventData, count); |
|||
return count; |
|||
} |
|||
} |
|||
@ -0,0 +1,145 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.EntityFrameworkCore; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Logging; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.DistributedLocking; |
|||
using Volo.Abp.EventBus.Distributed; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Uow; |
|||
|
|||
namespace Volo.Abp.EntityFrameworkCore.Migrations; |
|||
|
|||
public abstract class EfCoreRuntimeDatabaseMigratorBase<TDbContext> : ITransientDependency |
|||
where TDbContext : DbContext, IEfCoreDbContext |
|||
{ |
|||
protected int MinValueToWaitOnFailure { get; set; } = 5000; |
|||
protected int MaxValueToWaitOnFailure { get; set; } = 15000; |
|||
|
|||
protected string DatabaseName { get; } |
|||
|
|||
/// <summary>
|
|||
/// Enabling this might be inefficient if you have many tenants!
|
|||
/// If disabled (default), tenant databases will be seeded only
|
|||
/// if there is a schema migration applied to the host database.
|
|||
/// If enabled, tenant databases will be seeded always on every service startup.
|
|||
/// </summary>
|
|||
protected bool AlwaysSeedTenantDatabases { get; set; } = false; |
|||
|
|||
protected IUnitOfWorkManager UnitOfWorkManager { get; } |
|||
protected IServiceProvider ServiceProvider { get; } |
|||
protected ICurrentTenant CurrentTenant { get; } |
|||
protected IAbpDistributedLock DistributedLock { get; } |
|||
protected IDistributedEventBus DistributedEventBus { get; } |
|||
protected ILogger<EfCoreRuntimeDatabaseMigratorBase<TDbContext>> Logger { get; } |
|||
|
|||
protected EfCoreRuntimeDatabaseMigratorBase( |
|||
string databaseName, |
|||
IUnitOfWorkManager unitOfWorkManager, |
|||
IServiceProvider serviceProvider, |
|||
ICurrentTenant currentTenant, |
|||
IAbpDistributedLock abpDistributedLock, |
|||
IDistributedEventBus distributedEventBus, |
|||
ILoggerFactory loggerFactory) |
|||
{ |
|||
DatabaseName = databaseName; |
|||
UnitOfWorkManager = unitOfWorkManager; |
|||
ServiceProvider = serviceProvider; |
|||
CurrentTenant = currentTenant; |
|||
DistributedLock = abpDistributedLock; |
|||
DistributedEventBus = distributedEventBus; |
|||
Logger = loggerFactory.CreateLogger<EfCoreRuntimeDatabaseMigratorBase<TDbContext>>(); |
|||
} |
|||
|
|||
public virtual async Task CheckAndApplyDatabaseMigrationsAsync() |
|||
{ |
|||
await TryAsync(LockAndApplyDatabaseMigrationsAsync); |
|||
} |
|||
|
|||
protected virtual async Task LockAndApplyDatabaseMigrationsAsync() |
|||
{ |
|||
Logger.LogInformation($"Trying to acquire the distributed lock for database migration: {DatabaseName}."); |
|||
|
|||
var schemaMigrated = false; |
|||
|
|||
await using (var handle = await DistributedLock.TryAcquireAsync("DatabaseMigration_" + DatabaseName)) |
|||
{ |
|||
if (handle is null) |
|||
{ |
|||
Logger.LogInformation($"Distributed lock could not be acquired for database migration: {DatabaseName}. Operation cancelled."); |
|||
return; |
|||
} |
|||
|
|||
Logger.LogInformation($"Distributed lock is acquired for database migration: {DatabaseName}..."); |
|||
|
|||
using (CurrentTenant.Change(null)) |
|||
{ |
|||
// Create database tables if needed
|
|||
using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false)) |
|||
{ |
|||
var dbContext = await ServiceProvider |
|||
.GetRequiredService<IDbContextProvider<TDbContext>>() |
|||
.GetDbContextAsync(); |
|||
|
|||
var pendingMigrations = await dbContext |
|||
.Database |
|||
.GetPendingMigrationsAsync(); |
|||
|
|||
if (pendingMigrations.Any()) |
|||
{ |
|||
await dbContext.Database.MigrateAsync(); |
|||
schemaMigrated = true; |
|||
} |
|||
|
|||
await uow.CompleteAsync(); |
|||
} |
|||
} |
|||
|
|||
await SeedAsync(); |
|||
|
|||
if (schemaMigrated || AlwaysSeedTenantDatabases) |
|||
{ |
|||
await DistributedEventBus.PublishAsync( |
|||
new AppliedDatabaseMigrationsEto |
|||
{ |
|||
DatabaseName = DatabaseName, |
|||
TenantId = null |
|||
} |
|||
); |
|||
} |
|||
} |
|||
|
|||
Logger.LogInformation($"Distributed lock has been released for database migration: {DatabaseName}..."); |
|||
} |
|||
|
|||
protected virtual Task SeedAsync() |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
protected virtual async Task TryAsync(Func<Task> task, int maxTryCount = 3) |
|||
{ |
|||
try |
|||
{ |
|||
await task(); |
|||
} |
|||
catch (Exception ex) |
|||
{ |
|||
maxTryCount--; |
|||
|
|||
if (maxTryCount <= 0) |
|||
{ |
|||
throw; |
|||
} |
|||
|
|||
Logger.LogWarning($"{ex.GetType().Name} has been thrown. The operation will be tried {maxTryCount} times more. Exception:\n{ex.Message}. Stack Trace:\n{ex.StackTrace}"); |
|||
|
|||
await Task.Delay(RandomHelper.GetRandom(MinValueToWaitOnFailure, MaxValueToWaitOnFailure)); |
|||
|
|||
await TryAsync(task, maxTryCount); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,6 @@ |
|||
namespace Volo.Abp.EventBus; |
|||
|
|||
public static class EventBusConsts |
|||
{ |
|||
public const string CorrelationIdHeaderName = "X-Correlation-Id"; |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
namespace Volo.Abp.EventBus.Dapr; |
|||
|
|||
public class AbpDaprEventData |
|||
{ |
|||
public string PubSubName { get; set; } |
|||
|
|||
public string Topic { get; set; } |
|||
|
|||
public string MessageId { get; set; } |
|||
|
|||
public string JsonData { get; set; } |
|||
|
|||
public string CorrelationId { get; set; } |
|||
|
|||
public AbpDaprEventData(string pubSubName, string topic, string messageId, string jsonData, string correlationId) |
|||
{ |
|||
PubSubName = pubSubName; |
|||
Topic = topic; |
|||
MessageId = messageId; |
|||
JsonData = jsonData; |
|||
CorrelationId = correlationId; |
|||
} |
|||
} |
|||
@ -0,0 +1,14 @@ |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using JetBrains.Annotations; |
|||
|
|||
namespace Volo.Abp.TextTemplating; |
|||
|
|||
public interface IDynamicTemplateDefinitionStore |
|||
{ |
|||
Task<TemplateDefinition> GetAsync([NotNull] string name); |
|||
|
|||
Task<IReadOnlyList<TemplateDefinition>> GetAllAsync(); |
|||
|
|||
Task<TemplateDefinition> GetOrNullAsync(string name); |
|||
} |
|||
@ -0,0 +1,14 @@ |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using JetBrains.Annotations; |
|||
|
|||
namespace Volo.Abp.TextTemplating; |
|||
|
|||
public interface IStaticTemplateDefinitionStore |
|||
{ |
|||
Task<TemplateDefinition> GetAsync([NotNull] string name); |
|||
|
|||
Task<IReadOnlyList<TemplateDefinition>> GetAllAsync(); |
|||
|
|||
Task<TemplateDefinition> GetOrNullAsync(string name); |
|||
} |
|||
@ -1,16 +1,17 @@ |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using JetBrains.Annotations; |
|||
|
|||
namespace Volo.Abp.TextTemplating; |
|||
|
|||
public interface ITemplateDefinitionManager |
|||
{ |
|||
[NotNull] |
|||
TemplateDefinition Get([NotNull] string name); |
|||
[ItemNotNull] |
|||
Task<TemplateDefinition> GetAsync([NotNull] string name); |
|||
|
|||
[NotNull] |
|||
IReadOnlyList<TemplateDefinition> GetAll(); |
|||
[ItemNotNull] |
|||
Task<IReadOnlyList<TemplateDefinition>> GetAllAsync(); |
|||
|
|||
[CanBeNull] |
|||
TemplateDefinition GetOrNull(string name); |
|||
[ItemCanBeNull] |
|||
Task<TemplateDefinition> GetOrNullAsync(string name); |
|||
} |
|||
|
|||
@ -0,0 +1,29 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Collections.Immutable; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.TextTemplating; |
|||
|
|||
public class NullIDynamicTemplateDefinitionStore : IDynamicTemplateDefinitionStore, ISingletonDependency |
|||
{ |
|||
private readonly static Task<TemplateDefinition> CachedTemplateResult = Task.FromResult((TemplateDefinition)null); |
|||
|
|||
private readonly static Task<IReadOnlyList<TemplateDefinition>> CachedFeaturesResult = Task.FromResult((IReadOnlyList<TemplateDefinition>)Array.Empty<TemplateDefinition>().ToImmutableList()); |
|||
|
|||
public Task<TemplateDefinition> GetAsync(string name) |
|||
{ |
|||
return CachedTemplateResult; |
|||
} |
|||
|
|||
public Task<IReadOnlyList<TemplateDefinition>> GetAllAsync() |
|||
{ |
|||
return CachedFeaturesResult; |
|||
} |
|||
|
|||
public Task<TemplateDefinition> GetOrNullAsync(string name) |
|||
{ |
|||
return CachedTemplateResult; |
|||
} |
|||
} |
|||
@ -0,0 +1,83 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Collections.Immutable; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.TextTemplating; |
|||
|
|||
public class StaticTemplateDefinitionStore : IStaticTemplateDefinitionStore, ISingletonDependency |
|||
{ |
|||
protected Lazy<IDictionary<string, TemplateDefinition>> TemplateDefinitions { get; } |
|||
|
|||
protected AbpTextTemplatingOptions Options { get; } |
|||
|
|||
protected IServiceProvider ServiceProvider { get; } |
|||
|
|||
public StaticTemplateDefinitionStore(IOptions<AbpTextTemplatingOptions> options, IServiceProvider serviceProvider) |
|||
{ |
|||
ServiceProvider = serviceProvider; |
|||
Options = options.Value; |
|||
|
|||
TemplateDefinitions = new Lazy<IDictionary<string, TemplateDefinition>>(CreateTextTemplateDefinitions, true); |
|||
} |
|||
|
|||
public virtual Task<TemplateDefinition> GetAsync(string name) |
|||
{ |
|||
Check.NotNull(name, nameof(name)); |
|||
|
|||
var template = GetOrNullAsync(name); |
|||
|
|||
if (template == null) |
|||
{ |
|||
throw new AbpException("Undefined template: " + name); |
|||
} |
|||
|
|||
return template; |
|||
} |
|||
|
|||
public virtual Task<IReadOnlyList<TemplateDefinition>> GetAllAsync() |
|||
{ |
|||
return Task.FromResult<IReadOnlyList<TemplateDefinition>>(TemplateDefinitions.Value.Values.ToImmutableList()); |
|||
} |
|||
|
|||
public virtual Task<TemplateDefinition> GetOrNullAsync(string name) |
|||
{ |
|||
return Task.FromResult(TemplateDefinitions.Value.GetOrDefault(name)); |
|||
} |
|||
|
|||
protected virtual IDictionary<string, TemplateDefinition> CreateTextTemplateDefinitions() |
|||
{ |
|||
var templates = new Dictionary<string, TemplateDefinition>(); |
|||
|
|||
using (var scope = ServiceProvider.CreateScope()) |
|||
{ |
|||
var providers = Options |
|||
.DefinitionProviders |
|||
.Select(p => scope.ServiceProvider.GetRequiredService(p) as ITemplateDefinitionProvider) |
|||
.ToList(); |
|||
|
|||
var context = new TemplateDefinitionContext(templates); |
|||
|
|||
foreach (var provider in providers) |
|||
{ |
|||
provider.PreDefine(context); |
|||
} |
|||
|
|||
foreach (var provider in providers) |
|||
{ |
|||
provider.Define(context); |
|||
} |
|||
|
|||
foreach (var provider in providers) |
|||
{ |
|||
provider.PostDefine(context); |
|||
} |
|||
} |
|||
|
|||
return templates; |
|||
} |
|||
} |
|||
@ -1,85 +1,50 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Collections.Generic; |
|||
using System.Collections.Immutable; |
|||
using System.Linq; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.TextTemplating; |
|||
|
|||
public class TemplateDefinitionManager : ITemplateDefinitionManager, ISingletonDependency |
|||
{ |
|||
protected Lazy<IDictionary<string, TemplateDefinition>> TemplateDefinitions { get; } |
|||
protected readonly IStaticTemplateDefinitionStore StaticStore; |
|||
protected readonly IDynamicTemplateDefinitionStore DynamicStore; |
|||
|
|||
protected AbpTextTemplatingOptions Options { get; } |
|||
|
|||
protected IServiceProvider ServiceProvider { get; } |
|||
|
|||
public TemplateDefinitionManager( |
|||
IOptions<AbpTextTemplatingOptions> options, |
|||
IServiceProvider serviceProvider) |
|||
public TemplateDefinitionManager(IStaticTemplateDefinitionStore staticStore, IDynamicTemplateDefinitionStore dynamicStore) |
|||
{ |
|||
ServiceProvider = serviceProvider; |
|||
Options = options.Value; |
|||
|
|||
TemplateDefinitions = |
|||
new Lazy<IDictionary<string, TemplateDefinition>>(CreateTextTemplateDefinitions, true); |
|||
StaticStore = staticStore; |
|||
DynamicStore = dynamicStore; |
|||
} |
|||
|
|||
public virtual TemplateDefinition Get(string name) |
|||
public virtual async Task<TemplateDefinition> GetAsync(string name) |
|||
{ |
|||
Check.NotNull(name, nameof(name)); |
|||
|
|||
var template = GetOrNull(name); |
|||
|
|||
if (template == null) |
|||
var permission = await GetOrNullAsync(name); |
|||
if (permission == null) |
|||
{ |
|||
throw new AbpException("Undefined template: " + name); |
|||
throw new AbpException("Undefined Template: " + name); |
|||
} |
|||
|
|||
return template; |
|||
return permission; |
|||
} |
|||
|
|||
public virtual IReadOnlyList<TemplateDefinition> GetAll() |
|||
public virtual async Task<TemplateDefinition> GetOrNullAsync(string name) |
|||
{ |
|||
return TemplateDefinitions.Value.Values.ToImmutableList(); |
|||
} |
|||
Check.NotNull(name, nameof(name)); |
|||
|
|||
public virtual TemplateDefinition GetOrNull(string name) |
|||
{ |
|||
return TemplateDefinitions.Value.GetOrDefault(name); |
|||
return await StaticStore.GetOrNullAsync(name) ?? await DynamicStore.GetOrNullAsync(name); |
|||
} |
|||
|
|||
protected virtual IDictionary<string, TemplateDefinition> CreateTextTemplateDefinitions() |
|||
public virtual async Task<IReadOnlyList<TemplateDefinition>> GetAllAsync() |
|||
{ |
|||
var templates = new Dictionary<string, TemplateDefinition>(); |
|||
|
|||
using (var scope = ServiceProvider.CreateScope()) |
|||
{ |
|||
var providers = Options |
|||
.DefinitionProviders |
|||
.Select(p => scope.ServiceProvider.GetRequiredService(p) as ITemplateDefinitionProvider) |
|||
.ToList(); |
|||
|
|||
var context = new TemplateDefinitionContext(templates); |
|||
var staticTemplates = await StaticStore.GetAllAsync(); |
|||
var staticTemplateNames = staticTemplates |
|||
.Select(p => p.Name) |
|||
.ToImmutableHashSet(); |
|||
|
|||
foreach (var provider in providers) |
|||
{ |
|||
provider.PreDefine(context); |
|||
} |
|||
|
|||
foreach (var provider in providers) |
|||
{ |
|||
provider.Define(context); |
|||
} |
|||
|
|||
foreach (var provider in providers) |
|||
{ |
|||
provider.PostDefine(context); |
|||
} |
|||
} |
|||
var dynamicTemplates = await DynamicStore.GetAllAsync(); |
|||
|
|||
return templates; |
|||
/* We prefer static Templates over dynamics */ |
|||
return staticTemplates.Concat(dynamicTemplates.Where(d => !staticTemplateNames.Contains(d.Name))).ToImmutableList(); |
|||
} |
|||
} |
|||
|
|||
@ -0,0 +1,8 @@ |
|||
namespace Volo.Abp.TextTemplating.VirtualFiles; |
|||
|
|||
public class TemplateContentFileInfo |
|||
{ |
|||
public string FileName { get; set; } |
|||
|
|||
public string FileContent { get; set; } |
|||
} |
|||
@ -0,0 +1,56 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.VirtualFileSystem; |
|||
|
|||
namespace Volo.Abp.TextTemplating.VirtualFiles; |
|||
|
|||
public class TemplateContentFileProvider : ITransientDependency |
|||
{ |
|||
protected IVirtualFileProvider VirtualFileProvider { get; } |
|||
|
|||
public TemplateContentFileProvider(IVirtualFileProvider virtualFileProvider) |
|||
{ |
|||
VirtualFileProvider = virtualFileProvider; |
|||
} |
|||
|
|||
public async Task<List<TemplateContentFileInfo>> GetFilesAsync(TemplateDefinition templateDefinition) |
|||
{ |
|||
var files = new List<TemplateContentFileInfo>(); |
|||
|
|||
var virtualPath = templateDefinition.GetVirtualFilePathOrNull(); |
|||
if (virtualPath == null) |
|||
{ |
|||
return files; |
|||
} |
|||
|
|||
var fileInfo = VirtualFileProvider.GetFileInfo(virtualPath); |
|||
if (!fileInfo.Exists) |
|||
{ |
|||
var directoryContents = VirtualFileProvider.GetDirectoryContents(virtualPath); |
|||
if (!directoryContents.Exists) |
|||
{ |
|||
throw new AbpException("Could not find a file/folder at the location: " + virtualPath); |
|||
} |
|||
|
|||
fileInfo = new VirtualDirectoryFileInfo(virtualPath, virtualPath, DateTimeOffset.UtcNow); |
|||
} |
|||
|
|||
if (fileInfo.IsDirectory) |
|||
{ |
|||
//TODO: Configure file extensions.
|
|||
var folderReader = new VirtualFolderLocalizedTemplateContentReader(new[] { ".tpl", ".cshtml" }); |
|||
await folderReader.ReadContentsAsync(VirtualFileProvider, virtualPath); |
|||
files.AddRange(folderReader.GetFiles()); |
|||
} |
|||
else |
|||
{ |
|||
var singleFileReader = new FileInfoLocalizedTemplateContentReader(); |
|||
await singleFileReader.ReadContentsAsync(fileInfo); |
|||
files.Add(singleFileReader.GetFile()); |
|||
} |
|||
|
|||
return files; |
|||
} |
|||
} |
|||
@ -0,0 +1,17 @@ |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Volo.Abp.AspNetCore.Mvc; |
|||
using Volo.Abp.Tracing; |
|||
|
|||
namespace Volo.Abp.AspNetCore.CorrelationIdProvider; |
|||
|
|||
[Route("api/correlation")] |
|||
public class CorrelationIdProviderController : AbpController |
|||
{ |
|||
[HttpGet] |
|||
[Route("get")] |
|||
public string Get() |
|||
{ |
|||
return this.HttpContext.RequestServices.GetRequiredService<ICorrelationIdProvider>().Get(); |
|||
} |
|||
} |
|||
@ -0,0 +1,48 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using System.Net; |
|||
using System.Net.Http; |
|||
using System.Threading.Tasks; |
|||
using Shouldly; |
|||
using Volo.Abp.AspNetCore.Mvc; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.AspNetCore.CorrelationIdProvider; |
|||
|
|||
public class CorrelationIdProvider_Tests : AspNetCoreMvcTestBase |
|||
{ |
|||
[Fact] |
|||
public async Task Test() |
|||
{ |
|||
// Test AbpCorrelationIdMiddleware without X-Correlation-Id header
|
|||
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "/api/correlation/404")) |
|||
{ |
|||
var response = await Client.SendAsync(requestMessage); |
|||
response.StatusCode.ShouldBe(HttpStatusCode.NotFound); |
|||
|
|||
response.Headers.ShouldContain(x => x.Key == "X-Correlation-Id" && x.Value.First() != null); |
|||
} |
|||
|
|||
var correlationId = Guid.NewGuid().ToString("N"); |
|||
|
|||
// Test AbpCorrelationIdMiddleware
|
|||
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "/api/correlation/404")) |
|||
{ |
|||
requestMessage.Headers.Add("X-Correlation-Id", correlationId); |
|||
var response = await Client.SendAsync(requestMessage); |
|||
response.StatusCode.ShouldBe(HttpStatusCode.NotFound); |
|||
|
|||
response.Headers.ShouldContain(x => x.Key == "X-Correlation-Id" && x.Value.First() == correlationId); |
|||
} |
|||
|
|||
// Test AspNetCoreCorrelationIdProvider
|
|||
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "/api/correlation/get")) |
|||
{ |
|||
requestMessage.Headers.Add("X-Correlation-Id", correlationId); |
|||
var response = await Client.SendAsync(requestMessage); |
|||
response.StatusCode.ShouldBe(HttpStatusCode.OK); |
|||
|
|||
(await response.Content.ReadAsStringAsync()).ShouldBe(correlationId); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.Tracing; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.CorrelationIdProvider; |
|||
|
|||
public class CorrelationIdProvider_Tests |
|||
{ |
|||
[Fact] |
|||
public async Task Test() |
|||
{ |
|||
using (var application = await AbpApplicationFactory.CreateAsync<IndependentEmptyModule>()) |
|||
{ |
|||
await application.InitializeAsync(); |
|||
|
|||
var correlationIdProvider = application.ServiceProvider.GetRequiredService<ICorrelationIdProvider>(); |
|||
|
|||
correlationIdProvider.Get().ShouldBeNull(); |
|||
|
|||
var correlationId = Guid.NewGuid().ToString("N"); |
|||
using (correlationIdProvider.Change(correlationId)) |
|||
{ |
|||
correlationIdProvider.Get().ShouldBe(correlationId); |
|||
} |
|||
|
|||
correlationIdProvider.Get().ShouldBeNull(); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
using System.Threading.Tasks; |
|||
using Shouldly; |
|||
using Volo.Abp.TextTemplating.VirtualFiles; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.TextTemplating.Razor; |
|||
|
|||
public class RazorTemplateContentFileProvider_Tests : TemplateContentFileProvider_Tests<RazorTextTemplatingTestModule> |
|||
{ |
|||
[Fact] |
|||
public async Task GetRazorFilesAsync() |
|||
{ |
|||
var definition = await TemplateDefinitionManager.GetAsync(TestTemplates.WelcomeEmail); |
|||
var files = await TemplateContentFileProvider.GetFilesAsync(definition); |
|||
files.Count.ShouldBe(2); |
|||
files.ShouldContain(x => x.FileName == "en.cshtml" && x.FileContent.Contains("Welcome @Model.Name to the abp.io!")); |
|||
files.ShouldContain(x => x.FileName == "tr.cshtml" && x.FileContent.Contains("Merhaba @Model.Name, abp.io'ya hoşgeldiniz!")); |
|||
} |
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
using System.Threading.Tasks; |
|||
using Shouldly; |
|||
using Volo.Abp.TextTemplating.VirtualFiles; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.TextTemplating.Scriban.SampleTemplates; |
|||
|
|||
public class ScribanTemplateContentFileProvider_Tests : TemplateContentFileProvider_Tests<ScribanTextTemplatingTestModule> |
|||
{ |
|||
[Fact] |
|||
public async Task GetScribanFilesAsync() |
|||
{ |
|||
var definition = await TemplateDefinitionManager.GetAsync(TestTemplates.WelcomeEmail); |
|||
var files = await TemplateContentFileProvider.GetFilesAsync(definition); |
|||
files.Count.ShouldBe(2); |
|||
files.ShouldContain(x => x.FileName == "en.tpl" && x.FileContent.Contains("Welcome {{model.name}} to the abp.io!")); |
|||
files.ShouldContain(x => x.FileName == "tr.tpl" && x.FileContent.Contains("Merhaba {{model.name}}, abp.io'ya hoşgeldiniz!")); |
|||
} |
|||
} |
|||
@ -0,0 +1,29 @@ |
|||
using System.Threading.Tasks; |
|||
using Shouldly; |
|||
using Volo.Abp.Modularity; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.TextTemplating.VirtualFiles; |
|||
|
|||
public abstract class TemplateContentFileProvider_Tests<TStartupModule> : AbpTextTemplatingTestBase<TStartupModule> |
|||
where TStartupModule : IAbpModule |
|||
{ |
|||
protected readonly TemplateContentFileProvider TemplateContentFileProvider; |
|||
protected readonly ITemplateDefinitionManager TemplateDefinitionManager; |
|||
|
|||
protected TemplateContentFileProvider_Tests() |
|||
{ |
|||
TemplateContentFileProvider = GetRequiredService<TemplateContentFileProvider>(); |
|||
TemplateDefinitionManager = GetRequiredService<ITemplateDefinitionManager>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task GetFilesAsync() |
|||
{ |
|||
var definition = await TemplateDefinitionManager.GetAsync(TestTemplates.HybridTemplateScriban); |
|||
|
|||
var files = await TemplateContentFileProvider.GetFilesAsync(definition); |
|||
files.Count.ShouldBe(1); |
|||
files.ShouldContain(x => x.FileName == "TestScribanTemplate.tpl" && x.FileContent == "Hello {{model.name}}, {{L \"HowAreYou\" }}"); |
|||
} |
|||
} |
|||