Compare commits
23 Commits
8cfa803cd3
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| ffe6339aa3 | |||
| 43fbd7be95 | |||
| 0003e4207f | |||
| f7039431f2 | |||
| 7b0e3a1107 | |||
| a1ffe67318 | |||
| c53bd9ceaf | |||
| ef39263f82 | |||
| a1165121d1 | |||
| 05d16bb32c | |||
| 3e86d4cfe2 | |||
| c0e0fa3ba1 | |||
| 4a39e3f92b | |||
| f799cdf2c4 | |||
| 50b92115bb | |||
| a7d8b3412b | |||
| 85d1e844b3 | |||
| 888f01ea95 | |||
| 034d81f7f6 | |||
| eed9a0e915 | |||
| ad2a5240d2 | |||
| 51d8931dbe | |||
| 35094529bb |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -184,7 +184,6 @@ publish/
|
|||||||
*.azurePubxml
|
*.azurePubxml
|
||||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||||
# but database connection strings (with potential passwords) will be unencrypted
|
# but database connection strings (with potential passwords) will be unencrypted
|
||||||
*.pubxml
|
|
||||||
*.publishproj
|
*.publishproj
|
||||||
|
|
||||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||||
|
|||||||
135
README.md
135
README.md
@@ -4,6 +4,121 @@ A .NET 8 messaging service for sending and receiving emails via SMTP, IMAP, POP3
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Deployment als Windows-Dienst (empfohlen)
|
||||||
|
|
||||||
|
Der Betrieb als **Windows-Dienst** ist dem IIS-Hosting ausdrücklich vorzuziehen, da:
|
||||||
|
|
||||||
|
- Der RabbitMQ-Consumer dauerhaft läuft – unabhängig von eingehenden HTTP-Anfragen
|
||||||
|
- Kein IIS-Idle-Timeout, der den App-Pool beendet
|
||||||
|
- Automatischer Neustart bei Absturz (konfigurierbar)
|
||||||
|
- Verwaltung über die Windows-Dienstverwaltung (`services.msc`) oder PowerShell
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Voraussetzungen
|
||||||
|
|
||||||
|
- Windows Server (2016 oder neuer)
|
||||||
|
- .NET 8 Runtime **nicht erforderlich** – das Paket ist self-contained
|
||||||
|
- Administratorrechte auf dem Zielserver
|
||||||
|
- Port **1415** muss in der Firewall freigegeben sein
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Schritt 1: Publish
|
||||||
|
|
||||||
|
Auf dem Entwicklungsrechner im Repository-Verzeichnis:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\publish-windows-service.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
Die Ausgabe liegt anschließend unter:
|
||||||
|
```
|
||||||
|
M:\App&Service\0 DD - Funktionsmodule\MessagingService\PreRelease\WindowsService\net8\
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Schritt 2: Dateien auf den Server kopieren
|
||||||
|
|
||||||
|
Den gesamten Publish-Ordner auf den Server kopieren, z. B. nach:
|
||||||
|
```
|
||||||
|
D:\ProgramFiles\Digital Data\SERVICES\DigitalData.MessagingService\
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Wichtig:** Die Datei `appsettings.Secrets.json` wird **nicht** mit dem Publish-Paket ausgeliefert (sie ist nicht im Git-Repository). Diese Datei muss separat auf den Server kopiert werden. Sie enthält RabbitMQ-Zugangsdaten, E-Mail-Konten und weitere sensible Einstellungen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Schritt 3: Dienst installieren
|
||||||
|
|
||||||
|
Die Datei `install-windows-service.bat` liegt im Publish-Verzeichnis. Als Administrator ausführen:
|
||||||
|
|
||||||
|
```
|
||||||
|
install-windows-service.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
Das Skript führt folgende Schritte automatisch aus:
|
||||||
|
1. Vorhandenen Dienst stoppen und löschen (falls vorhanden)
|
||||||
|
2. Neuen Windows-Dienst erstellen
|
||||||
|
3. Automatischen Neustart bei Absturz konfigurieren
|
||||||
|
4. Firewall-Regel für Port 1415 hinzufügen
|
||||||
|
5. Dienst starten
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Schritt 4: Überprüfung
|
||||||
|
|
||||||
|
Nach der Installation die API im Browser aufrufen:
|
||||||
|
```
|
||||||
|
http://SERVER-IP:1415/swagger
|
||||||
|
http://SERVER-IP:1415/health
|
||||||
|
http://SERVER-IP:1415/serilog-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
Dienststatus prüfen:
|
||||||
|
```powershell
|
||||||
|
sc.exe query "DD-MessagingService"
|
||||||
|
# oder
|
||||||
|
Get-Service "DD-MessagingService"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Update (neue Version einspielen)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 1. Dienst stoppen
|
||||||
|
sc.exe stop "DD-MessagingService"
|
||||||
|
|
||||||
|
# 2. Neue Dateien ins Verzeichnis kopieren (appsettings.Secrets.json NICHT überschreiben)
|
||||||
|
|
||||||
|
# 3. Dienst starten
|
||||||
|
sc.exe start "DD-MessagingService"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Dienst entfernen
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
sc.exe stop "DD-MessagingService"
|
||||||
|
sc.exe delete "DD-MessagingService"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Konfiguration
|
||||||
|
|
||||||
|
| Einstellung | Datei | Beschreibung |
|
||||||
|
|---|---|---|
|
||||||
|
| `Hosting:UseWindowsService` | `appsettings.json` | `true` = Windows-Dienst-Modus aktiv |
|
||||||
|
| `Hosting:Urls` | `appsettings.json` | Bind-Adresse und Port, z. B. `http://0.0.0.0:1415` |
|
||||||
|
| `DataProtection:PersistKeysToFileSystem` | `appsettings.json` | `true` = Schlüssel werden im Verzeichnis `dp-keys/` gespeichert, unabhängig vom Windows-Benutzer |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
## Email Account Configuration
|
## Email Account Configuration
|
||||||
|
|
||||||
Each account is configured under `EmailAccounts.Accounts` in `appsettings.Secrets.json`.
|
Each account is configured under `EmailAccounts.Accounts` in `appsettings.Secrets.json`.
|
||||||
@@ -39,7 +154,7 @@ Each account is configured under `EmailAccounts.Accounts` in `appsettings.Secret
|
|||||||
|
|
||||||
| Value | Meaning |
|
| Value | Meaning |
|
||||||
|-------|---------|
|
|-------|---------|
|
||||||
| `0` | None — send-only account, skipped by sync worker |
|
| `0` | None <EFBFBD> send-only account, skipped by sync worker |
|
||||||
| `1` | IMAP with username/password |
|
| `1` | IMAP with username/password |
|
||||||
| `2` | POP3 with username/password |
|
| `2` | POP3 with username/password |
|
||||||
| `3` | IMAP with OAuth2 |
|
| `3` | IMAP with OAuth2 |
|
||||||
@@ -92,7 +207,7 @@ automatically for all subsequent operations.
|
|||||||
|
|
||||||
#### Obtaining the refresh token via the built-in authorization endpoint
|
#### Obtaining the refresh token via the built-in authorization endpoint
|
||||||
|
|
||||||
The application provides a built-in OAuth2 flow — no external tools needed.
|
The application provides a built-in OAuth2 flow <EFBFBD> no external tools needed.
|
||||||
|
|
||||||
1. Open a browser and navigate to:
|
1. Open a browser and navigate to:
|
||||||
```
|
```
|
||||||
@@ -101,7 +216,7 @@ The application provides a built-in OAuth2 flow
|
|||||||
Example: `https://localhost:7261/api/oauth2/google/authorize/3`
|
Example: `https://localhost:7261/api/oauth2/google/authorize/3`
|
||||||
|
|
||||||
2. You will be redirected to Google's consent screen. If you see **"Google hasn't verified this app"**,
|
2. You will be redirected to Google's consent screen. If you see **"Google hasn't verified this app"**,
|
||||||
click **Continue** — this is expected while the app is in Testing mode.
|
click **Continue** <EFBFBD> this is expected while the app is in Testing mode.
|
||||||
|
|
||||||
3. Sign in with the Gmail account and grant access.
|
3. Sign in with the Gmail account and grant access.
|
||||||
|
|
||||||
@@ -122,7 +237,7 @@ The application provides a built-in OAuth2 flow
|
|||||||
|
|
||||||
### Microsoft 365 / Exchange Online (Azure AD)
|
### Microsoft 365 / Exchange Online (Azure AD)
|
||||||
|
|
||||||
Microsoft uses **application-level OAuth2** (client credentials flow — no user interaction required).
|
Microsoft uses **application-level OAuth2** (client credentials flow <EFBFBD> no user interaction required).
|
||||||
Tokens are acquired automatically using the client ID, secret and tenant ID. No authorization endpoint
|
Tokens are acquired automatically using the client ID, secret and tenant ID. No authorization endpoint
|
||||||
needs to be visited.
|
needs to be visited.
|
||||||
|
|
||||||
@@ -154,12 +269,12 @@ needs to be visited.
|
|||||||
5. Set `OAuth2TenantId` to the full domain (e.g. `yourorg.onmicrosoft.com`) or tenant GUID.
|
5. Set `OAuth2TenantId` to the full domain (e.g. `yourorg.onmicrosoft.com`) or tenant GUID.
|
||||||
|
|
||||||
> ?? `OAuth2ClientSecret` must be the **Value** shown at secret creation time, not the Secret ID (GUID).
|
> ?? `OAuth2ClientSecret` must be the **Value** shown at secret creation time, not the Secret ID (GUID).
|
||||||
> The value is only visible once — if lost, create a new secret.
|
> The value is only visible once <EFBFBD> if lost, create a new secret.
|
||||||
|
|
||||||
> ?? `OAuth2TenantId` must be a full domain (`yourorg.onmicrosoft.com`), a tenant GUID,
|
> ?? `OAuth2TenantId` must be a full domain (`yourorg.onmicrosoft.com`), a tenant GUID,
|
||||||
> or `common`. Short names like `yourorg` are not valid and will cause `AADSTS900023`.
|
> or `common`. Short names like `yourorg` are not valid and will cause `AADSTS900023`.
|
||||||
|
|
||||||
> No browser-based authorization is required for Microsoft — the application acquires tokens
|
> No browser-based authorization is required for Microsoft <EFBFBD> the application acquires tokens
|
||||||
> automatically on first use and caches them in memory until 5 minutes before expiry.
|
> automatically on first use and caches them in memory until 5 minutes before expiry.
|
||||||
|
|
||||||
|
|
||||||
@@ -200,7 +315,7 @@ Each account is configured under `EmailAccounts.Accounts` in `appsettings.Secret
|
|||||||
|
|
||||||
| Value | Meaning |
|
| Value | Meaning |
|
||||||
|-------|---------|
|
|-------|---------|
|
||||||
| `0` | None — send-only account, skipped by sync worker |
|
| `0` | None <EFBFBD> send-only account, skipped by sync worker |
|
||||||
| `1` | IMAP with username/password |
|
| `1` | IMAP with username/password |
|
||||||
| `2` | POP3 with username/password |
|
| `2` | POP3 with username/password |
|
||||||
| `3` | IMAP with OAuth2 |
|
| `3` | IMAP with OAuth2 |
|
||||||
@@ -235,7 +350,7 @@ Google uses **user-delegated OAuth2** (not client credentials). A one-time autho
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Setup — obtaining the refresh token (one-time)
|
#### Setup <EFBFBD> obtaining the refresh token (one-time)
|
||||||
|
|
||||||
1. Go to [console.cloud.google.com](https://console.cloud.google.com) and create or select a project.
|
1. Go to [console.cloud.google.com](https://console.cloud.google.com) and create or select a project.
|
||||||
2. Enable the **Gmail API** under *APIs & Services ? Library*.
|
2. Enable the **Gmail API** under *APIs & Services ? Library*.
|
||||||
@@ -264,7 +379,7 @@ Google uses **user-delegated OAuth2** (not client credentials). A one-time autho
|
|||||||
|
|
||||||
### Microsoft 365 / Exchange Online (Azure AD)
|
### Microsoft 365 / Exchange Online (Azure AD)
|
||||||
|
|
||||||
Microsoft uses **application-level OAuth2** (client credentials flow — no user interaction required).
|
Microsoft uses **application-level OAuth2** (client credentials flow <EFBFBD> no user interaction required).
|
||||||
|
|
||||||
#### Required fields
|
#### Required fields
|
||||||
|
|
||||||
@@ -294,7 +409,7 @@ Microsoft uses **application-level OAuth2** (client credentials flow
|
|||||||
5. Set `OAuth2TenantId` to the full domain (e.g. `yourorg.onmicrosoft.com`) or tenant GUID.
|
5. Set `OAuth2TenantId` to the full domain (e.g. `yourorg.onmicrosoft.com`) or tenant GUID.
|
||||||
|
|
||||||
> ?? `OAuth2ClientSecret` must be the **Value** shown at secret creation time, not the Secret ID (GUID).
|
> ?? `OAuth2ClientSecret` must be the **Value** shown at secret creation time, not the Secret ID (GUID).
|
||||||
> The value is only visible once — if lost, create a new secret.
|
> The value is only visible once <EFBFBD> if lost, create a new secret.
|
||||||
|
|
||||||
> ?? `OAuth2TenantId` must be a full domain (`yourorg.onmicrosoft.com`), a tenant GUID,
|
> ?? `OAuth2TenantId` must be a full domain (`yourorg.onmicrosoft.com`), a tenant GUID,
|
||||||
> or `common`. Short names like `yourorg` are not valid and will cause `AADSTS900023`.
|
> or `common`. Short names like `yourorg` are not valid and will cause `AADSTS900023`.
|
||||||
|
|||||||
23
publish-windows-service.ps1
Normal file
23
publish-windows-service.ps1
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
# publish-windows-service.ps1
|
||||||
|
# Kullanim: .\publish-windows-service.ps1
|
||||||
|
# Cikti: E:\Publish\MessagingService\WindowsService\
|
||||||
|
|
||||||
|
$project = "$PSScriptRoot\src\presentation\DigitalData.MessagingService.API\DigitalData.MessagingService.API.csproj"
|
||||||
|
$output = "M:\App&Service\0 DD - Funktionsmodule\MessagingService\PreRelease\WindowsService\net8"
|
||||||
|
|
||||||
|
Write-Host "Publishing to $output ..." -ForegroundColor Cyan
|
||||||
|
|
||||||
|
dotnet publish $project `
|
||||||
|
--configuration Release `
|
||||||
|
--runtime win-x64 `
|
||||||
|
--self-contained true `
|
||||||
|
--output $output `
|
||||||
|
-p:EnvironmentName=Production `
|
||||||
|
-p:PublishSingleFile=false
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -eq 0) {
|
||||||
|
Write-Host "Done. Files at: $output" -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host "Publish FAILED." -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public interface IMessagingServiceClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<Guid> SendAsync(PublishEmailViaSmtpCommand command, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
#if NET
|
#if NET
|
||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
|
||||||
@@ -11,25 +10,22 @@ namespace DigitalData.MessagingService.Application.DependencyInjection;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, Action<MessagingServiceApplicationConfiguration> configure)
|
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, string? luckyPennySoftLicenseKey = null)
|
||||||
{
|
{
|
||||||
var assembly = Assembly.GetExecutingAssembly();
|
var assembly = Assembly.GetExecutingAssembly();
|
||||||
|
|
||||||
var configuration = new MessagingServiceApplicationConfiguration(services);
|
|
||||||
configure(configuration);
|
|
||||||
configuration.EnsureConfigured();
|
|
||||||
|
|
||||||
// MediatR - Register all handlers
|
// MediatR - Register all handlers
|
||||||
services.AddMediatR(config =>
|
services.AddMediatR(config =>
|
||||||
{
|
{
|
||||||
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
|
config.LicenseKey = luckyPennySoftLicenseKey;
|
||||||
config.RegisterServicesFromAssembly(assembly);
|
config.RegisterServicesFromAssembly(assembly);
|
||||||
});
|
});
|
||||||
|
|
||||||
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
|
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
|
||||||
services.AddAutoMapper(config =>
|
services.AddAutoMapper(config =>
|
||||||
{
|
{
|
||||||
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
|
if (luckyPennySoftLicenseKey is not null)
|
||||||
|
config.LicenseKey = luckyPennySoftLicenseKey;
|
||||||
config.AddMaps(assembly);
|
config.AddMaps(assembly);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
#if NET
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Application.DependencyInjection;
|
|
||||||
|
|
||||||
public partial class MessagingServiceApplicationConfiguration
|
|
||||||
{
|
|
||||||
private IServiceCollection Services { get; }
|
|
||||||
|
|
||||||
private bool _luckyPennySoftLicenseKeyAdded = false;
|
|
||||||
|
|
||||||
internal MessagingServiceApplicationConfiguration(IServiceCollection services)
|
|
||||||
{
|
|
||||||
Services = services;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal void EnsureConfigured()
|
|
||||||
{
|
|
||||||
if (!_luckyPennySoftLicenseKeyAdded)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#region LuckyPennySoftLicenseKey
|
|
||||||
internal string? LuckyPennySoftLicenseKey { get; set; } = null;
|
|
||||||
|
|
||||||
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(string licenseKey)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(licenseKey))
|
|
||||||
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
|
|
||||||
|
|
||||||
LuckyPennySoftLicenseKey = licenseKey;
|
|
||||||
_luckyPennySoftLicenseKeyAdded = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(IConfiguration configuration, string key = "LuckyPennySoftLicenseKey")
|
|
||||||
{
|
|
||||||
return SetLuckyPennySoftLicenseKey(configuration.GetValue<string>(key) ?? string.Empty);
|
|
||||||
}
|
|
||||||
#endregion LuckyPennySoftLicenseKey
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
|
||||||
|
public static class GetEmailAccountQueryExtensions
|
||||||
|
{
|
||||||
|
public static GetEmailAccountQuery ToSender(this string emailAddress)
|
||||||
|
{
|
||||||
|
return new GetEmailAccountQuery
|
||||||
|
{
|
||||||
|
Username = emailAddress
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -17,6 +17,10 @@ namespace DigitalData.MessagingService.Application.EmailSending.Commands;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public record PublishEmailViaSmtpCommand : IRequest<Guid>
|
public record PublishEmailViaSmtpCommand : IRequest<Guid>
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Specifies the sender's email account to resolve, identified by either its Id or Username.
|
||||||
|
/// Use <see cref="GetEmailAccountQueryExtensions.ToSender(string)"/> to create a query from an email address.
|
||||||
|
/// </summary>
|
||||||
public required GetEmailAccountQuery Sender { get; init; }
|
public required GetEmailAccountQuery Sender { get; init; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -28,14 +28,14 @@ public class MessagingServiceInfrastructureConfiguration
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
|
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConnectionConfiguration> configure)
|
||||||
{
|
{
|
||||||
Services.AddRabbitMqConnectionFactory(configure);
|
Services.AddRabbitMqConnectionFactory(configure);
|
||||||
_configured.RabbitMqConnectionFactory = true;
|
_configured.RabbitMqConnectionFactory = true;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
|
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
{
|
{
|
||||||
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
|
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
|
||||||
_configured.RabbitMqConnectionFactory = true;
|
_configured.RabbitMqConnectionFactory = true;
|
||||||
@@ -57,5 +57,4 @@ public class MessagingServiceInfrastructureConfiguration
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
#endregion EmailAccountsOptions
|
#endregion EmailAccountsOptions
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ public sealed class SendingEmailConsumerPool : IAsyncDisposable
|
|||||||
private readonly int _concurrency;
|
private readonly int _concurrency;
|
||||||
|
|
||||||
public SendingEmailConsumerPool(
|
public SendingEmailConsumerPool(
|
||||||
IOptions<RabbitMqConfiguration> config,
|
IOptions<RabbitMqConnectionConfiguration> config,
|
||||||
IEmailService emailService,
|
IEmailService emailService,
|
||||||
IServiceScopeFactory scopeFactory,
|
IServiceScopeFactory scopeFactory,
|
||||||
RabbitMqConnectionFactory cnnFactory,
|
RabbitMqConnectionFactory cnnFactory,
|
||||||
|
|||||||
@@ -14,18 +14,19 @@ namespace DigitalData.MessagingService.Infrastructure.Services.Background;
|
|||||||
public class ConsumerInitWorker(
|
public class ConsumerInitWorker(
|
||||||
SendingEmailConsumerPool ConsumerPool,
|
SendingEmailConsumerPool ConsumerPool,
|
||||||
ILogger<ConsumerInitWorker> Logger,
|
ILogger<ConsumerInitWorker> Logger,
|
||||||
IOptions<RabbitMqConfiguration> RabbitMqOptions,
|
IOptions<RabbitMqConnectionConfiguration> RabbitMqOptions,
|
||||||
ConsumerInitHealthCheck HealthCheck) : BackgroundService
|
ConsumerInitHealthCheck HealthCheck) : IHostedService
|
||||||
{
|
{
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await ConsumerPool.InitAsync();
|
await ConsumerPool.InitAsync();
|
||||||
|
Logger.LogInformation("SendingEmailConsumerPool initialized successfully.");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
// Log and mark the health check as unhealthy — callers will receive HTTP 503.
|
// Log and mark the health check as unhealthy <EFBFBD> callers will receive HTTP 503.
|
||||||
// The API remains operational; only outgoing email delivery via the consumer pool is affected.
|
// The API remains operational; only outgoing email delivery via the consumer pool is affected.
|
||||||
Logger.LogError(ex, "Failed to initialize SendingEmailConsumerPool. Outgoing email consumers are not running.");
|
Logger.LogError(ex, "Failed to initialize SendingEmailConsumerPool. Outgoing email consumers are not running.");
|
||||||
|
|
||||||
@@ -34,7 +35,7 @@ public class ConsumerInitWorker(
|
|||||||
if (!RabbitMqOptions.Value.ContinueOnInitFailure)
|
if (!RabbitMqOptions.Value.ContinueOnInitFailure)
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
|
|
||||||
await Task.Delay(Timeout.Infinite, stoppingToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||||
}
|
}
|
||||||
@@ -7,15 +7,20 @@ namespace DigitalData.MessagingService.Publisher;
|
|||||||
|
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, Action<MessagingServicePublisherConfiguration>? configure = null)
|
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
var configuration = new MessagingServicePublisherConfiguration(services);
|
return services.AddSingleton<ISendingEmailPublisher, SendingEmailPublisher>();
|
||||||
|
}
|
||||||
|
|
||||||
configure?.Invoke(configuration);
|
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, Action<RabbitMqConnectionConfiguration> configureRabbitMqConnection)
|
||||||
|
{
|
||||||
|
services.AddRabbitMqConnectionFactory(configureRabbitMqConnection);
|
||||||
|
return services.AddMessagingServicePublisher();
|
||||||
|
}
|
||||||
|
|
||||||
// --- Email Queue (RabbitMQ) ---
|
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, IConfiguration configuration, string rabbitMqConnectionSectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
services.AddSingleton<ISendingEmailPublisher, SendingEmailPublisher>();
|
{
|
||||||
|
services.AddRabbitMqConnectionFactory(configuration.GetSection(rabbitMqConnectionSectionName));
|
||||||
return services;
|
return services.AddMessagingServicePublisher();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
using DigitalData.MessagingService.RabbitMQ;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Publisher;
|
|
||||||
|
|
||||||
public class MessagingServicePublisherConfiguration
|
|
||||||
{
|
|
||||||
internal IServiceCollection Services { get; }
|
|
||||||
|
|
||||||
internal MessagingServicePublisherConfiguration(IServiceCollection services)
|
|
||||||
{
|
|
||||||
Services = services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServicePublisherConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
|
|
||||||
{
|
|
||||||
Services.AddRabbitMqConnectionFactory(configure);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServicePublisherConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
|
|
||||||
{
|
|
||||||
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,12 +16,12 @@ namespace DigitalData.MessagingService.Publisher;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class SendingEmailPublisher : ISendingEmailPublisher, IAsyncDisposable
|
public sealed class SendingEmailPublisher : ISendingEmailPublisher, IAsyncDisposable
|
||||||
{
|
{
|
||||||
private readonly RabbitMqConfiguration _config;
|
private readonly RabbitMqConnectionConfiguration _config;
|
||||||
private readonly ILogger<SendingEmailPublisher> _logger;
|
private readonly ILogger<SendingEmailPublisher> _logger;
|
||||||
private readonly RabbitMqConnectionFactory _cnnFactory;
|
private readonly RabbitMqConnectionFactory _cnnFactory;
|
||||||
private readonly Lazy<Task<IChannel>> _lazyChannel;
|
private readonly Lazy<Task<IChannel>> _lazyChannel;
|
||||||
|
|
||||||
public SendingEmailPublisher(IOptions<RabbitMqConfiguration> config, ILogger<SendingEmailPublisher> logger, RabbitMqConnectionFactory cnnFactory)
|
public SendingEmailPublisher(IOptions<RabbitMqConnectionConfiguration> config, ILogger<SendingEmailPublisher> logger, RabbitMqConnectionFactory cnnFactory)
|
||||||
{
|
{
|
||||||
_config = config.Value;
|
_config = config.Value;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|||||||
@@ -9,36 +9,26 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
private static IServiceCollection AddDefaultServices(this IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddSingleton<RabbitMqConnectionFactory>();
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Adds Infrastructure layer services to the DI container
|
/// Adds Infrastructure layer services to the DI container
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, Action<RabbitMqConfiguration> configure)
|
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, Action<RabbitMqConnectionConfiguration> configure)
|
||||||
{
|
{
|
||||||
services.AddDefaultServices();
|
|
||||||
|
|
||||||
// --- RabbitMQ Configuration ---
|
// --- RabbitMQ Configuration ---
|
||||||
services.Configure(configure);
|
services.Configure(configure);
|
||||||
|
|
||||||
return services;
|
return services.AddSingleton<RabbitMqConnectionFactory>();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Adds Infrastructure layer services to the DI container
|
/// Adds Infrastructure layer services to the DI container
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
|
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, IConfiguration configuration, string sectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
{
|
{
|
||||||
services.AddDefaultServices();
|
|
||||||
|
|
||||||
// --- RabbitMQ Configuration ---
|
// --- RabbitMQ Configuration ---
|
||||||
services.Configure<RabbitMqConfiguration>(configuration.GetSection(sectionName));
|
services.Configure<RabbitMqConnectionConfiguration>(configuration.GetSection(sectionName));
|
||||||
|
|
||||||
return services;
|
return services.AddSingleton<RabbitMqConnectionFactory>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Configuration for RabbitMQ connection
|
/// Configuration for RabbitMQ connection
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class RabbitMqConfiguration
|
public class RabbitMqConnectionConfiguration
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Configuration section name in appsettings.json
|
/// Configuration section name in appsettings.json
|
||||||
@@ -12,7 +12,7 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
{
|
{
|
||||||
private readonly CancellationTokenSource _consumerCts = new CancellationTokenSource();
|
private readonly CancellationTokenSource _consumerCts = new CancellationTokenSource();
|
||||||
|
|
||||||
private readonly RabbitMqConfiguration _config;
|
private readonly RabbitMqConnectionConfiguration _config;
|
||||||
|
|
||||||
private readonly ILogger<RabbitMqConnectionFactory>
|
private readonly ILogger<RabbitMqConnectionFactory>
|
||||||
#if nullable
|
#if nullable
|
||||||
@@ -41,7 +41,7 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
return new AsyncEventingBasicConsumer(channel);
|
return new AsyncEventingBasicConsumer(channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
public RabbitMqConnectionFactory(IOptions<RabbitMqConfiguration> config)
|
public RabbitMqConnectionFactory(IOptions<RabbitMqConnectionConfiguration> config)
|
||||||
{
|
{
|
||||||
_config = config.Value;
|
_config = config.Value;
|
||||||
_lazyConnectionProvider = new Lazy<Task<IConnection>>(async () =>
|
_lazyConnectionProvider = new Lazy<Task<IConnection>>(async () =>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFrameworks>net8.0</TargetFrameworks>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||||
@@ -10,14 +10,16 @@
|
|||||||
<Authors>Digital Data GmbH</Authors>
|
<Authors>Digital Data GmbH</Authors>
|
||||||
<Company>Digital Data GmbH</Company>
|
<Company>Digital Data GmbH</Company>
|
||||||
<Product>DigitalData.MessagingService.API</Product>
|
<Product>DigitalData.MessagingService.API</Product>
|
||||||
<Version>2.1.0-beta</Version>
|
<Version>2.2.1-beta</Version>
|
||||||
<FileVersion>2.1.0.0</FileVersion>
|
<FileVersion>2.2.1.0</FileVersion>
|
||||||
<AssemblyVersion>2.1.0.0</AssemblyVersion>
|
<AssemblyVersion>2.2.1.0</AssemblyVersion>
|
||||||
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
|
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
|
||||||
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
|
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.DataProtection.Extensions" Version="8.0.11" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.1" />
|
||||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||||
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
|
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
|
||||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using DigitalData.MessagingService.Application.DependencyInjection;
|
|||||||
using DigitalData.MessagingService.Infrastructure.DependencyInjection;
|
using DigitalData.MessagingService.Infrastructure.DependencyInjection;
|
||||||
using DigitalData.MessagingService.Infrastructure.Services.Background;
|
using DigitalData.MessagingService.Infrastructure.Services.Background;
|
||||||
using HealthChecks.UI.Client;
|
using HealthChecks.UI.Client;
|
||||||
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
@@ -48,6 +49,26 @@ try
|
|||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
// Windows Service hosting — controlled via appsettings "Hosting:UseWindowsService"
|
||||||
|
var useWindowsService = builder.Configuration.GetValue<bool>("Hosting:UseWindowsService");
|
||||||
|
if (useWindowsService)
|
||||||
|
{
|
||||||
|
builder.Host.UseWindowsService();
|
||||||
|
var urls = builder.Configuration.GetValue<string>("Hosting:Urls");
|
||||||
|
if (!string.IsNullOrWhiteSpace(urls))
|
||||||
|
builder.WebHost.UseUrls(urls);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Data Protection — persist keys to file system so Windows Service (LOCAL SYSTEM) can read them
|
||||||
|
// across restarts. Controlled via appsettings "DataProtection:PersistKeysToFileSystem".
|
||||||
|
if (builder.Configuration.GetValue<bool>("DataProtection:PersistKeysToFileSystem"))
|
||||||
|
{
|
||||||
|
var keysDir = Path.Combine(AppContext.BaseDirectory, "dp-keys");
|
||||||
|
builder.Services.AddDataProtection()
|
||||||
|
.PersistKeysToFileSystem(new DirectoryInfo(keysDir))
|
||||||
|
.ProtectKeysWithDpapi(protectToLocalMachine: true);
|
||||||
|
}
|
||||||
|
|
||||||
// Use Serilog for logging
|
// Use Serilog for logging
|
||||||
builder.Host.UseSerilog((context, services, configuration) => configuration
|
builder.Host.UseSerilog((context, services, configuration) => configuration
|
||||||
.ReadFrom.Configuration(context.Configuration)
|
.ReadFrom.Configuration(context.Configuration)
|
||||||
@@ -65,7 +86,9 @@ try
|
|||||||
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
|
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
|
||||||
|
|
||||||
// Register Application layer (MediatR, AutoMapper, FluentValidation)
|
// Register Application layer (MediatR, AutoMapper, FluentValidation)
|
||||||
builder.Services.AddMessagingServiceApplication(cfg => cfg.SetLuckyPennySoftLicenseKey(builder.Configuration));
|
var LuckyPennySoftLicenseKey = builder.Configuration.GetValue<string>("LuckyPennySoftLicenseKey")
|
||||||
|
?? throw new InvalidOperationException("The required configuration value 'LuckyPennySoftLicenseKey' is missing. Please ensure it is properly configured.");
|
||||||
|
builder.Services.AddMessagingServiceApplication(LuckyPennySoftLicenseKey);
|
||||||
|
|
||||||
// Register Infrastructure layer (RabbitMQ, Repositories, etc.)
|
// Register Infrastructure layer (RabbitMQ, Repositories, etc.)
|
||||||
builder.Services.AddInfrastructure(cfg => cfg
|
builder.Services.AddInfrastructure(cfg => cfg
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!--
|
||||||
|
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||||
|
-->
|
||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<WebPublishMethod>Package</WebPublishMethod>
|
||||||
|
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
|
||||||
|
<LastUsedPlatform>Any CPU</LastUsedPlatform>
|
||||||
|
<SiteUrlToLaunchAfterPublish />
|
||||||
|
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
|
||||||
|
<ExcludeApp_Data>false</ExcludeApp_Data>
|
||||||
|
<ProjectGuid>5e0e17c0-ff5a-4246-bf87-1add85376a27</ProjectGuid>
|
||||||
|
<DesktopBuildPackageLocation>M:\App&Service\0 DD - Funktionsmodule\MessagingService\PreRelease\API\net8\$(Version)\DigitalData.MessagingService.API.zip</DesktopBuildPackageLocation>
|
||||||
|
<PackageAsSingleFile>true</PackageAsSingleFile>
|
||||||
|
<DeployIisAppPath>EnvelopeGenerator</DeployIisAppPath>
|
||||||
|
<_TargetId>IISWebDeployPackage</_TargetId>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<SelfContained>true</SelfContained>
|
||||||
|
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||||
|
<EnvironmentName>Production</EnvironmentName>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!--
|
||||||
|
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||||
|
Windows Service publish profile — outputs files to a folder for sc.exe deployment.
|
||||||
|
Usage: dotnet publish /p:PublishProfile=WindowsServiceNet8 /p:Version=2.2.1-beta
|
||||||
|
-->
|
||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||||
|
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
|
||||||
|
<LastUsedPlatform>Any CPU</LastUsedPlatform>
|
||||||
|
<PublishDir>E:\Publish\MessagingService\WindowsService\</PublishDir>
|
||||||
|
<DeleteExistingFiles>false</DeleteExistingFiles>
|
||||||
|
<ProjectGuid>5e0e17c0-ff5a-4246-bf87-1add85376a27</ProjectGuid>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<SelfContained>true</SelfContained>
|
||||||
|
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||||
|
<EnvironmentName>Production</EnvironmentName>
|
||||||
|
<PublishSingleFile>false</PublishSingleFile>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -1,4 +1,11 @@
|
|||||||
{
|
{
|
||||||
|
"Hosting": {
|
||||||
|
"UseWindowsService": true,
|
||||||
|
"Urls": "http://0.0.0.0:1415"
|
||||||
|
},
|
||||||
|
"DataProtection": {
|
||||||
|
"PersistKeysToFileSystem": true
|
||||||
|
},
|
||||||
"Serilog": {
|
"Serilog": {
|
||||||
"MinimumLevel": {
|
"MinimumLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
@echo off
|
||||||
|
:: DigitalData MessagingService - Windows Service Installer
|
||||||
|
:: Als Administrator ausfuehren / Run as Administrator
|
||||||
|
::
|
||||||
|
:: Verwendung / Usage:
|
||||||
|
:: install-windows-service.bat
|
||||||
|
::
|
||||||
|
:: Voraussetzung: Dieses Skript liegt im Publish-Verzeichnis neben der .exe
|
||||||
|
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set SERVICE_NAME=DD-MessagingService
|
||||||
|
set SERVICE_DISPLAY=DigitalData MessagingService
|
||||||
|
set SERVICE_DESC=DigitalData E-Mail Messaging Service - RabbitMQ Consumer + REST API
|
||||||
|
set SERVICE_EXE=%~dp0DigitalData.MessagingService.API.exe
|
||||||
|
set SERVICE_PORT=1415
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ============================================================
|
||||||
|
echo DigitalData MessagingService - Windows Service Installation
|
||||||
|
echo ============================================================
|
||||||
|
echo.
|
||||||
|
|
||||||
|
:: Adminrechte pruefen
|
||||||
|
net session >nul 2>&1
|
||||||
|
if %errorlevel% neq 0 (
|
||||||
|
echo [FEHLER] Bitte als Administrator ausfuehren.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
:: Pruefen ob .exe vorhanden
|
||||||
|
if not exist "%SERVICE_EXE%" (
|
||||||
|
echo [FEHLER] Datei nicht gefunden: %SERVICE_EXE%
|
||||||
|
echo Bitte sicherstellen, dass das Skript im Publish-Verzeichnis liegt.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
:: Vorhandenen Dienst stoppen und loeschen
|
||||||
|
sc query "%SERVICE_NAME%" >nul 2>&1
|
||||||
|
if %errorlevel% equ 0 (
|
||||||
|
echo [INFO] Vorhandener Dienst wird gestoppt und geloescht...
|
||||||
|
sc stop "%SERVICE_NAME%" >nul 2>&1
|
||||||
|
timeout /t 3 /nobreak >nul
|
||||||
|
sc delete "%SERVICE_NAME%"
|
||||||
|
timeout /t 2 /nobreak >nul
|
||||||
|
)
|
||||||
|
|
||||||
|
:: Dienst erstellen
|
||||||
|
echo [INFO] Dienst wird erstellt...
|
||||||
|
sc create "%SERVICE_NAME%" binPath= "\"%SERVICE_EXE%\"" DisplayName= "%SERVICE_DISPLAY%" start= auto
|
||||||
|
if %errorlevel% neq 0 (
|
||||||
|
echo [FEHLER] Dienst konnte nicht erstellt werden.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
:: Beschreibung setzen
|
||||||
|
sc description "%SERVICE_NAME%" "%SERVICE_DESC%"
|
||||||
|
|
||||||
|
:: Neustart-Verhalten konfigurieren (bei Absturz automatisch neu starten)
|
||||||
|
sc failure "%SERVICE_NAME%" reset= 86400 actions= restart/5000/restart/10000/restart/30000
|
||||||
|
|
||||||
|
:: Firewall-Regel hinzufuegen
|
||||||
|
echo [INFO] Firewall-Regel wird hinzugefuegt (Port %SERVICE_PORT%)...
|
||||||
|
netsh advfirewall firewall delete rule name="DD MessagingService %SERVICE_PORT%" >nul 2>&1
|
||||||
|
netsh advfirewall firewall add rule name="DD MessagingService %SERVICE_PORT%" dir=in action=allow protocol=TCP localport=%SERVICE_PORT%
|
||||||
|
|
||||||
|
:: Dienst starten
|
||||||
|
echo [INFO] Dienst wird gestartet...
|
||||||
|
sc start "%SERVICE_NAME%"
|
||||||
|
if %errorlevel% neq 0 (
|
||||||
|
echo [WARNUNG] Dienst konnte nicht sofort gestartet werden. Bitte manuell pruefen.
|
||||||
|
) else (
|
||||||
|
echo [OK] Dienst gestartet.
|
||||||
|
)
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ============================================================
|
||||||
|
echo Installation abgeschlossen.
|
||||||
|
echo API erreichbar unter: http://localhost:%SERVICE_PORT%/swagger
|
||||||
|
echo Logs: %~dp0logs\
|
||||||
|
echo ============================================================
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.DependencyInjection;
|
||||||
|
using DigitalData.MessagingService.Publisher;
|
||||||
|
using DigitalData.MessagingService.RabbitMQ;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public static class DependencyInjection
|
||||||
|
{
|
||||||
|
private static IServiceCollection EnsureMessagingServiceClientNotRegistered(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
if (services.Any(x => x.ServiceType == typeof(IMessagingServiceClient)))
|
||||||
|
throw new InvalidOperationException("IMessagingServiceClient is already registered. Register only one client implementation (MessagingServiceClient or MessagingServiceHttpClient).");
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IServiceCollection AddMessagingServiceClientDefault(this IServiceCollection services, string? luckyPennySoftLicenseKey = null)
|
||||||
|
{
|
||||||
|
services.EnsureMessagingServiceClientNotRegistered();
|
||||||
|
services.AddMessagingServiceApplication(luckyPennySoftLicenseKey);
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
#region DI Extensions
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="luckyPennySoftLicenseKey"></param>
|
||||||
|
/// <param name="configureRabbitMqConnection"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IServiceCollection AddMessagingServiceClient(this IServiceCollection services, Action<RabbitMqConnectionConfiguration> configureRabbitMqConnection, string? luckyPennySoftLicenseKey = null)
|
||||||
|
{
|
||||||
|
services.AddMessagingServiceClientDefault(luckyPennySoftLicenseKey);
|
||||||
|
services.AddMessagingServicePublisher(configureRabbitMqConnection);
|
||||||
|
services.AddTransient<IMessagingServiceClient, MessagingServiceClient>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="luckyPennySoftLicenseKey"></param>
|
||||||
|
/// <param name="configuration"></param>
|
||||||
|
/// <param name="rabbitMqConnectionSectionName"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IServiceCollection AddMessagingServiceClient(this IServiceCollection services, IConfiguration configuration, string? luckyPennySoftLicenseKey = null, string rabbitMqConnectionSectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
|
{
|
||||||
|
services.AddMessagingServiceClientDefault(luckyPennySoftLicenseKey);
|
||||||
|
services.AddMessagingServicePublisher(configuration, rabbitMqConnectionSectionName);
|
||||||
|
services.AddTransient<IMessagingServiceClient, MessagingServiceClient>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers <see cref="MessagingServiceHttpClient"/> as <see cref="IMessagingServiceClient"/>.
|
||||||
|
/// Configure <see cref="HttpClient.BaseAddress"/> for the named client <c>MessagingServiceHttpClient</c>.
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddMessagingServiceHttpClient(this IServiceCollection services, Action<HttpClient> configureHttpClient)
|
||||||
|
{
|
||||||
|
services.EnsureMessagingServiceClientNotRegistered();
|
||||||
|
services.AddHttpClient(nameof(MessagingServiceHttpClient), configureHttpClient);
|
||||||
|
services.AddTransient<IMessagingServiceClient, MessagingServiceHttpClient>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers <see cref="MessagingServiceHttpClient"/> as <see cref="IMessagingServiceClient"/>.
|
||||||
|
/// Configure <see cref="HttpClient.BaseAddress"/> for the named client <c>MessagingServiceHttpClient</c> using the provided base address.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="baseAddress"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IServiceCollection AddMessagingServiceHttpClient(this IServiceCollection services, string baseAddress)
|
||||||
|
{
|
||||||
|
// do not call EnsureMessagingServiceClientNotRegistered here because AddMessagingServiceHttpClient is already calling it in the overload above
|
||||||
|
return services.AddMessagingServiceHttpClient(client => client.BaseAddress = new Uri(baseAddress));
|
||||||
|
}
|
||||||
|
#endregion DI Extensions
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
#if NET
|
|
||||||
namespace DigitalData.MessagingService.Client.DependencyInjection;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
///
|
|
||||||
/// </summary>
|
|
||||||
public static class DependencyInjectionExtensions
|
|
||||||
{
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
#if NET
|
|
||||||
namespace DigitalData.MessagingService.Client.DependencyInjection;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
///
|
|
||||||
/// </summary>
|
|
||||||
public class MessagingServiceConfiguration
|
|
||||||
{
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -11,9 +11,9 @@
|
|||||||
<PackageIcon>icon.png</PackageIcon>
|
<PackageIcon>icon.png</PackageIcon>
|
||||||
<RepositoryUrl>http://git.dd:3000/AppStd/Rec.git</RepositoryUrl>
|
<RepositoryUrl>http://git.dd:3000/AppStd/Rec.git</RepositoryUrl>
|
||||||
<PackageTags>digital data messaging service api client</PackageTags>
|
<PackageTags>digital data messaging service api client</PackageTags>
|
||||||
<Version>1.0.5</Version>
|
<Version>3.0.1</Version>
|
||||||
<AssemblyVersion>1.0.5.0</AssemblyVersion>
|
<AssemblyVersion>3.0.1.0</AssemblyVersion>
|
||||||
<FileVersion>1.0.5.0</FileVersion>
|
<FileVersion>3.0.1.0</FileVersion>
|
||||||
<Description></Description>
|
<Description></Description>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
@@ -27,6 +27,7 @@
|
|||||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.10" />
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.10" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
|
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.10" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
|
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
|
||||||
|
|||||||
@@ -13,14 +13,17 @@ namespace DigitalData.MessagingService.Client;
|
|||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This class manages its own internal <see cref="IServiceProvider"/> using a
|
/// This class manages its own internal <see cref="IServiceProvider"/> using a
|
||||||
/// <see cref="Lazy{T}"/> pattern so the DI container is only built once,
|
/// <see cref="Lazy{T}"/> pattern so the DI container is only built once,
|
||||||
/// on the first call to <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/>.
|
/// on the first call to <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/>.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
|
#if NET
|
||||||
|
[Obsolete("Use MessagingServiceClient with dependency injection instead.")]
|
||||||
|
#endif
|
||||||
public static class EmailSender
|
public static class EmailSender
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Internal event used to accumulate service registrations before the
|
/// Internal event used to accumulate service registrations before the
|
||||||
/// <see cref="IServiceProvider"/> is built. Handlers are added by
|
/// <see cref="IServiceProvider"/> is built. Handlers are added by
|
||||||
/// <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> and invoked exactly once during
|
/// <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/> and invoked exactly once during
|
||||||
/// lazy initialization.
|
/// lazy initialization.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static event Action<IServiceCollection> ConfigureServices = delegate { };
|
private static event Action<IServiceCollection> ConfigureServices = delegate { };
|
||||||
@@ -43,7 +46,7 @@ public static class EmailSender
|
|||||||
/// and the internal <see cref="IServiceProvider"/> has been initialized.
|
/// and the internal <see cref="IServiceProvider"/> has been initialized.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// <see langword="true"/> if <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> has been called
|
/// <see langword="true"/> if <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/> has been called
|
||||||
/// and the provider is built; otherwise <see langword="false"/>.
|
/// and the provider is built; otherwise <see langword="false"/>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public static bool IsConnected => LazyProvider.IsValueCreated;
|
public static bool IsConnected => LazyProvider.IsValueCreated;
|
||||||
@@ -53,7 +56,7 @@ public static class EmailSender
|
|||||||
/// the internal dependency injection container.
|
/// the internal dependency injection container.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="configure">
|
/// <param name="configure">
|
||||||
/// A delegate used to configure the <see cref="RabbitMqConfiguration"/>,
|
/// A delegate used to configure the <see cref="RabbitMqConnectionConfiguration"/>,
|
||||||
/// such as host, port, credentials, and exchange settings.
|
/// such as host, port, credentials, and exchange settings.
|
||||||
/// </param>
|
/// </param>
|
||||||
/// <param name="onReconnect">
|
/// <param name="onReconnect">
|
||||||
@@ -64,12 +67,12 @@ public static class EmailSender
|
|||||||
/// Thrown when the service is already connected and
|
/// Thrown when the service is already connected and
|
||||||
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
|
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
|
||||||
/// </exception>
|
/// </exception>
|
||||||
public static void ConnectRabbitMq(Action<RabbitMqConfiguration> configure, OnReconnect onReconnect = OnReconnect.ThrowException)
|
public static void ConnectRabbitMq(Action<RabbitMqConnectionConfiguration> configure, OnReconnect onReconnect = OnReconnect.ThrowException)
|
||||||
{
|
{
|
||||||
if(IsConnected && onReconnect == OnReconnect.ThrowException)
|
if(IsConnected && onReconnect == OnReconnect.ThrowException)
|
||||||
throw new InvalidOperationException("Messaging service is already connected.");
|
throw new InvalidOperationException("Messaging service is already connected.");
|
||||||
|
|
||||||
ConfigureServices += services => services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(configure));
|
ConfigureServices += services => services.AddMessagingServicePublisher(configure);
|
||||||
_ = LazyProvider.Value; // Force initialization
|
_ = LazyProvider.Value; // Force initialization
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +114,7 @@ public static class EmailSender
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="email">The outgoing email data to enqueue.</param>
|
/// <param name="email">The outgoing email data to enqueue.</param>
|
||||||
/// <exception cref="InvalidOperationException">
|
/// <exception cref="InvalidOperationException">
|
||||||
/// Thrown when <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> has not been called prior to sending.
|
/// Thrown when <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/> has not been called prior to sending.
|
||||||
/// </exception>
|
/// </exception>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This method maps <see cref="EmailContext"/> to <see cref="SendingEmailEvent"/>,
|
/// This method maps <see cref="EmailContext"/> to <see cref="SendingEmailEvent"/>,
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
using MediatR;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public class MessagingServiceClient(ISender sender) : IMessagingServiceClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<Guid> SendAsync(PublishEmailViaSmtpCommand command, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return sender.Send(command, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public class MessagingServiceHttpClient(IHttpClientFactory httpClientFactory) : IMessagingServiceClient
|
||||||
|
{
|
||||||
|
private sealed record SendEmailAcceptedResponse(Guid Id);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
/// <exception cref="HttpRequestException"></exception>
|
||||||
|
public async Task<Guid> SendAsync(PublishEmailViaSmtpCommand command, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var httpClient = httpClientFactory.CreateClient(nameof(MessagingServiceHttpClient));
|
||||||
|
|
||||||
|
var senderUsernameField = $"{nameof(PublishEmailViaSmtpCommand.Sender)}.{nameof(GetEmailAccountQuery.Username)}";
|
||||||
|
|
||||||
|
using var form = new MultipartFormDataContent
|
||||||
|
{
|
||||||
|
{ new StringContent(command.Sender.Username ?? string.Empty), senderUsernameField },
|
||||||
|
{ new StringContent(command.Subject), nameof(PublishEmailViaSmtpCommand.Subject) },
|
||||||
|
{ new StringContent(command.Body), nameof(PublishEmailViaSmtpCommand.Body) },
|
||||||
|
{ new StringContent(command.IsHtml.ToString().ToLowerInvariant()), nameof(PublishEmailViaSmtpCommand.IsHtml) }
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var recipient in command.Recipients)
|
||||||
|
form.Add(new StringContent(recipient), nameof(PublishEmailViaSmtpCommand.Recipients));
|
||||||
|
|
||||||
|
using var response = await httpClient.PostAsync("api/Email/smtp", form, cancellationToken);
|
||||||
|
if (response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var payload = await response.Content.ReadFromJsonAsync<SendEmailAcceptedResponse>(cancellationToken: cancellationToken)
|
||||||
|
?? throw new HttpRequestException("MessagingService API response body is empty.");
|
||||||
|
|
||||||
|
return payload.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
var responseText = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
|
||||||
|
throw new HttpRequestException(
|
||||||
|
$"MessagingService API request failed with status {(int)response.StatusCode} ({response.StatusCode}). Body: {responseText}",
|
||||||
|
null,
|
||||||
|
response.StatusCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
namespace DigitalData.MessagingService.Client;
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Defines the behavior when <see cref="EmailSender.ConnectRabbitMq(Action{RabbitMQ.RabbitMqConfiguration}, OnReconnect)"/> is called
|
/// Defines the behavior when <see cref="EmailSender.ConnectRabbitMq(Action{RabbitMQ.RabbitMqConnectionConfiguration}, OnReconnect)"/> is called
|
||||||
/// while a connection has already been established.
|
/// while a connection has already been established.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public enum OnReconnect
|
public enum OnReconnect
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using DigitalData.MessagingService.Application.Common.Dto;
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
|
||||||
|
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
using DigitalData.MessagingService.Client;
|
||||||
|
using DigitalData.MessagingService.Domain.Entities;
|
||||||
|
using DigitalData.MessagingService.Publisher;
|
||||||
|
using DigitalData.MessagingService.RabbitMQ;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Tests.Integration;
|
||||||
|
|
||||||
|
public sealed class MessagingServiceClientTests : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private const string SenderAddress = "test-flow@digitaldata.works";
|
||||||
|
private const string RecipientAddress = "htek0100@gmail.com";
|
||||||
|
private const string MessagingServiceApiBaseAddress = "http://172.24.12.39:1414";
|
||||||
|
|
||||||
|
private readonly ServiceProvider _serviceProvider;
|
||||||
|
private readonly IMessagingServiceClient _client;
|
||||||
|
private readonly RabbitMqConnectionFactory _factory;
|
||||||
|
|
||||||
|
public MessagingServiceClientTests()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddLogging();
|
||||||
|
|
||||||
|
services.AddMessagingServiceClient(RabbitMqTestConfig.Apply, LoadLuckyPennySoftLicenseKey());
|
||||||
|
services.AddSingleton<IRepository<EmailAccount>>(
|
||||||
|
new InMemoryEmailAccountRepository(
|
||||||
|
[
|
||||||
|
new EmailAccount
|
||||||
|
{
|
||||||
|
Id = 1,
|
||||||
|
Username = SenderAddress,
|
||||||
|
Password = "ddemail108",
|
||||||
|
SmtpServer = "kundencenter.triplew.de",
|
||||||
|
SmtpPort = 465,
|
||||||
|
SmtpUseSsl = true,
|
||||||
|
UseOAuth2 = false
|
||||||
|
}
|
||||||
|
]));
|
||||||
|
|
||||||
|
_serviceProvider = services.BuildServiceProvider();
|
||||||
|
_client = _serviceProvider.GetRequiredService<IMessagingServiceClient>();
|
||||||
|
_factory = _serviceProvider.GetRequiredService<RabbitMqConnectionFactory>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends an email through <see cref="IMessagingServiceClient"/> using the real RabbitMQ setup.
|
||||||
|
/// This test intentionally uses manual mailbox verification because the shared queue can be
|
||||||
|
/// consumed by other services during test execution.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task SendAsync_WithDependencyInjectionAndRealBroker_PublishesExpectedMessage()
|
||||||
|
{
|
||||||
|
var subject = $"MessagingServiceClient Integration Test {Guid.NewGuid():N}";
|
||||||
|
|
||||||
|
var command = CreateCommand(subject);
|
||||||
|
|
||||||
|
await _client.SendAsync(command);
|
||||||
|
|
||||||
|
Assert.True(true, "Verify in mailbox.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SendAsync_WithHttpClientDependencyInjection_PublishesExpectedMessage()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddLogging();
|
||||||
|
services.AddMessagingServiceHttpClient(client => client.BaseAddress = new Uri(MessagingServiceApiBaseAddress));
|
||||||
|
|
||||||
|
await using var serviceProvider = services.BuildServiceProvider();
|
||||||
|
var client = serviceProvider.GetRequiredService<IMessagingServiceClient>();
|
||||||
|
|
||||||
|
var subject = $"MessagingServiceHttpClient Integration Test {Guid.NewGuid():N}";
|
||||||
|
var command = CreateCommand(subject);
|
||||||
|
|
||||||
|
await Record.ExceptionAsync(() => client.SendAsync(command));
|
||||||
|
|
||||||
|
Assert.True(true, "Verify in mailbox.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PublishEmailViaSmtpCommand CreateCommand(string subject)
|
||||||
|
{
|
||||||
|
return new PublishEmailViaSmtpCommand
|
||||||
|
{
|
||||||
|
Sender = SenderAddress.ToSender(),
|
||||||
|
Recipients = [RecipientAddress],
|
||||||
|
Subject = subject,
|
||||||
|
Body = "<p>Realistic test mail via MessagingServiceClient.</p>",
|
||||||
|
IsHtml = true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<SendingEmailEvent?> FindMessageBySubjectAsync(string subject, int maxMessages = 100)
|
||||||
|
{
|
||||||
|
var connection = await _factory.GetDefaultConnectionAsync();
|
||||||
|
await using var channel = await connection.CreateChannelAsync();
|
||||||
|
|
||||||
|
var inspectedTags = new List<ulong>();
|
||||||
|
|
||||||
|
for (var i = 0; i < maxMessages; i++)
|
||||||
|
{
|
||||||
|
var result = await channel.BasicGetAsync(RabbitMqTestConfig.QueueName, autoAck: false);
|
||||||
|
if (result is null)
|
||||||
|
break;
|
||||||
|
|
||||||
|
inspectedTags.Add(result.DeliveryTag);
|
||||||
|
|
||||||
|
var json = Encoding.UTF8.GetString(result.Body.ToArray());
|
||||||
|
var message = JsonSerializer.Deserialize<SendingEmailEvent>(json);
|
||||||
|
if (message?.Mail.Subject == subject)
|
||||||
|
{
|
||||||
|
foreach (var tag in inspectedTags)
|
||||||
|
await channel.BasicNackAsync(tag, multiple: false, requeue: true);
|
||||||
|
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var tag in inspectedTags)
|
||||||
|
await channel.BasicNackAsync(tag, multiple: false, requeue: true);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string LoadLuckyPennySoftLicenseKey()
|
||||||
|
{
|
||||||
|
var appsettingsPath = FindApiAppSettingsPath();
|
||||||
|
using var doc = JsonDocument.Parse(File.ReadAllText(appsettingsPath));
|
||||||
|
|
||||||
|
if (doc.RootElement.TryGetProperty("LuckyPennySoftLicenseKey", out var key) &&
|
||||||
|
key.ValueKind == JsonValueKind.String &&
|
||||||
|
!string.IsNullOrWhiteSpace(key.GetString()))
|
||||||
|
return key.GetString()!;
|
||||||
|
|
||||||
|
throw new InvalidOperationException($"LuckyPennySoftLicenseKey not found in '{appsettingsPath}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FindApiAppSettingsPath()
|
||||||
|
{
|
||||||
|
var current = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
|
|
||||||
|
while (current is not null)
|
||||||
|
{
|
||||||
|
var candidate = Path.Combine(current.FullName, "src", "presentation", "DigitalData.MessagingService.API", "appsettings.json");
|
||||||
|
if (File.Exists(candidate))
|
||||||
|
return candidate;
|
||||||
|
|
||||||
|
current = current.Parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new FileNotFoundException("Could not locate API appsettings.json from test output directory.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
await _factory.DisposeAsync();
|
||||||
|
await _serviceProvider.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class InMemoryEmailAccountRepository(IEnumerable<EmailAccount> accounts) : IRepository<EmailAccount>
|
||||||
|
{
|
||||||
|
private readonly List<EmailAccount> _accounts = accounts.ToList();
|
||||||
|
|
||||||
|
public Task<IEnumerable<EmailAccount>> FindAsync(Expression<Func<EmailAccount, bool>> predicate, int? skip = null, int? take = null, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var query = _accounts.AsQueryable().Where(predicate);
|
||||||
|
if (skip.HasValue)
|
||||||
|
query = query.Skip(skip.Value);
|
||||||
|
if (take.HasValue)
|
||||||
|
query = query.Take(take.Value);
|
||||||
|
|
||||||
|
return Task.FromResult<IEnumerable<EmailAccount>>(query.ToList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<EmailAccount> CreateAsync<TDto>(TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<IEnumerable<EmailAccount>> CreateRangeAsync<TDto>(IEnumerable<TDto> dtos, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<EmailAccount?> GetByIdAsync(int id, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<IEnumerable<EmailAccount>> GetAllAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<EmailAccount?> FindFirstAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<EmailAccount?> FindSingleAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<int> CountAsync(Expression<Func<EmailAccount, bool>>? predicate = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<bool> AnyAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<(EmailAccount Entity, bool Created)> UpsertAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<(EmailAccount Entity, bool Created)> UpsertSingleAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task UpdateSingleAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<int> UpdateAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task DeleteSingleAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<int> DeleteAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,7 +24,7 @@ public sealed class SendingEmailPublisherTests : IAsyncDisposable
|
|||||||
{
|
{
|
||||||
var services = new ServiceCollection();
|
var services = new ServiceCollection();
|
||||||
services.AddLogging();
|
services.AddLogging();
|
||||||
services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(RabbitMqTestConfig.Apply));
|
services.AddMessagingServicePublisher(RabbitMqTestConfig.Apply);
|
||||||
|
|
||||||
_serviceProvider = services.BuildServiceProvider();
|
_serviceProvider = services.BuildServiceProvider();
|
||||||
_publisher = _serviceProvider.GetRequiredService<ISendingEmailPublisher>();
|
_publisher = _serviceProvider.GetRequiredService<ISendingEmailPublisher>();
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ internal static class RabbitMqTestConfig
|
|||||||
public const string DlqExchangeName = "emailprofiler.emails.dlq";
|
public const string DlqExchangeName = "emailprofiler.emails.dlq";
|
||||||
public const string DlqRoutingKey = "email.outbox.dlq";
|
public const string DlqRoutingKey = "email.outbox.dlq";
|
||||||
|
|
||||||
public static void Apply(RabbitMqConfiguration cfg)
|
public static void Apply(RabbitMqConnectionConfiguration cfg)
|
||||||
{
|
{
|
||||||
cfg.HostName = HostName;
|
cfg.HostName = HostName;
|
||||||
cfg.Port = Port;
|
cfg.Port = Port;
|
||||||
|
|||||||
@@ -11,12 +11,12 @@ public sealed class EmailSenderUrlParsingTests
|
|||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Applies the same URL-parsing logic used by the URL overload to a fresh
|
/// Applies the same URL-parsing logic used by the URL overload to a fresh
|
||||||
/// <see cref="RabbitMqConfiguration"/> and returns it for assertion.
|
/// <see cref="RabbitMqConnectionConfiguration"/> and returns it for assertion.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static RabbitMqConfiguration ParseUrl(string url, string username, string password)
|
private static RabbitMqConnectionConfiguration ParseUrl(string url, string username, string password)
|
||||||
{
|
{
|
||||||
var uri = new Uri(url);
|
var uri = new Uri(url);
|
||||||
var cfg = new RabbitMqConfiguration();
|
var cfg = new RabbitMqConnectionConfiguration();
|
||||||
|
|
||||||
cfg.HostName = uri.Host;
|
cfg.HostName = uri.Host;
|
||||||
cfg.Port = uri.IsDefaultPort ? 5672 : uri.Port;
|
cfg.Port = uri.IsDefaultPort ? 5672 : uri.Port;
|
||||||
@@ -95,7 +95,7 @@ public sealed class EmailSenderUrlParsingTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseUrl_WithRootPath_DoesNotOverrideVirtualHost()
|
public void ParseUrl_WithRootPath_DoesNotOverrideVirtualHost()
|
||||||
{
|
{
|
||||||
var defaultVHost = new RabbitMqConfiguration().VirtualHost;
|
var defaultVHost = new RabbitMqConnectionConfiguration().VirtualHost;
|
||||||
var cfg = ParseUrl("amqp://broker:5672/", "user", "pass");
|
var cfg = ParseUrl("amqp://broker:5672/", "user", "pass");
|
||||||
|
|
||||||
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
||||||
@@ -104,7 +104,7 @@ public sealed class EmailSenderUrlParsingTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseUrl_WithoutPath_DoesNotOverrideVirtualHost()
|
public void ParseUrl_WithoutPath_DoesNotOverrideVirtualHost()
|
||||||
{
|
{
|
||||||
var defaultVHost = new RabbitMqConfiguration().VirtualHost;
|
var defaultVHost = new RabbitMqConnectionConfiguration().VirtualHost;
|
||||||
var cfg = ParseUrl("amqp://broker:5672", "user", "pass");
|
var cfg = ParseUrl("amqp://broker:5672", "user", "pass");
|
||||||
|
|
||||||
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
||||||
|
|||||||
Reference in New Issue
Block a user