Compare commits

...

25 Commits

Author SHA1 Message Date
ffe6339aa3 docs(readme): document Windows Service deployment workflow 2026-11-17 15:00:37 +01:00
43fbd7be95 chore(deployment): add Windows Service publish and install scripts 2026-11-17 15:00:33 +01:00
0003e4207f feat(api): persist data protection keys for Windows Service 2026-11-17 15:00:24 +01:00
f7039431f2 Update publish settings for versioning and file retention
Updated the `<PublishDir>` property to use `$(AssemblyVersion)`
instead of `$(Version)` for better versioning management.
Changed `<DeleteExistingFiles>` from `true` to `false` to
retain existing files during the publishing process.
2026-11-17 11:35:57 +01:00
7b0e3a1107 Update .gitignore and add WindowsService publish profile
Updated .gitignore to exclude `*.pubxml` and `*.publishproj` files, preventing sensitive information from being committed.

Added `WindowsServiceNet8.pubxml`, a new publish profile for deploying a Windows Service application. The profile specifies `FileSystem` as the publish method, targets `net8.0`, and includes configurations for output directory, runtime identifier, and environment settings.
2026-11-17 11:28:11 +01:00
a1ffe67318 Add Windows Service support and integrate Serilog logging
Added support for running the application as a Windows Service:
- Introduced `Microsoft.Extensions.Hosting.WindowsServices` package.
- Configured conditional Windows Service hosting in `Program.cs`.
- Added `Hosting:UseWindowsService` and `Hosting:Urls` settings in `appsettings.json`.

Integrated Serilog for enhanced logging capabilities:
- Added Serilog-related NuGet packages for configuration and sinks.
- Configured Serilog in `Program.cs` to read from configuration and enrich logs.

Updated `appsettings.json` to include Serilog logging levels and overrides.
2026-11-17 11:20:55 +01:00
c53bd9ceaf Add IIS publish profile for .NET 8.0 deployment
Added or modified `IISProfileNet8.pubxml` to define publishing settings for a .NET application targeting the `net8.0` framework. Key configurations include:

- `WebPublishMethod` set to `Package` for deployment packaging.
- `LastUsedBuildConfiguration` set to `Release`.
- `LaunchSiteAfterPublish` enabled.
- `DesktopBuildPackageLocation` specifies output path with version placeholder.
- `PackageAsSingleFile` enabled for single-file packaging.
- `DeployIisAppPath` set to `EnvelopeGenerator`.
- `TargetFramework` set to `net8.0`.
- `SelfContained` enabled with `RuntimeIdentifier` set to `win-x64`.
- `EnvironmentName` set to `Production`.
2026-11-16 16:55:25 +01:00
ef39263f82 Refactor ConsumerInitWorker to use IHostedService
Refactored the `ConsumerInitWorker` class to implement the
`IHostedService` interface, replacing `BackgroundService`.
Replaced `ExecuteAsync` with `StartAsync` and `StopAsync`
methods. Added a log statement for successful initialization
of `SendingEmailConsumerPool`.

Updated `DigitalData.MessagingService.API.csproj` to increment
version numbers:
- `Version`: 2.2.0-beta -> 2.2.1-beta
- `FileVersion`: 2.2.0.0 -> 2.2.1.0
- `AssemblyVersion`: 2.2.0.0 -> 2.2.1.0

These changes introduce minor improvements and bug fixes
without breaking changes.
2026-11-16 16:51:46 +01:00
a1165121d1 Make AddMessagingServiceHttpClient an extension method
Updated the AddMessagingServiceHttpClient method in the
DependencyInjection class to use the `this` keyword for the
IServiceCollection parameter. This change makes the method an
extension method, allowing it to be called directly on an
IServiceCollection instance. This improves usability and aligns
with common dependency injection extension patterns.
2026-11-05 10:11:39 +01:00
05d16bb32c Refactor and enhance MessagingService client tests
Updated `ToSender` to an extension method for improved usability.
Bumped project version to 3.0.0, reflecting major changes.
Added `MessagingServiceApiBaseAddress` constant for maintainability.
Introduced new test for HTTP client dependency injection.
Refactored command creation into a reusable `CreateCommand` method.
Removed redundant code and improved test structure for clarity.
2026-11-05 10:04:41 +01:00
3e86d4cfe2 feat(client)!: unify client API around IMessagingServiceClient
MessagingServiceClient now implements IMessagingServiceClient and takes a PublishEmailViaSmtpCommand instead of the removed Email record. Add MessagingServiceHttpClient, which posts the same command to the API via IHttpClientFactory.

Replace DependencyInjectionExtensions with a single DependencyInjection entry point that registers exactly one client implementation and throws when a second one is added. It exposes AddMessagingServiceClient for RabbitMQ and AddMessagingServiceHttpClient for the HTTP API, both with an optional license key.

Bump the package to 2.0.0 because the SendAsync signatures and the removed Email type are breaking changes, add Microsoft.Extensions.Http, and update the integration test to exercise the new contract.
2026-11-05 09:45:11 +01:00
c0e0fa3ba1 feat(application): make license key optional
Consumers that use the HTTP client do not pass AutoMapper license data, so the key is now optional and only assigned when supplied. Existing callers keep working unchanged.
2026-11-05 09:45:03 +01:00
4a39e3f92b feat(application): add ToSender helper for email accounts
Adds GetEmailAccountQueryExtensions.ToSender to build a sender query from an email address, and documents its use on PublishEmailViaSmtpCommand.Sender.
2026-11-05 09:44:59 +01:00
f799cdf2c4 feat(application): add IMessagingServiceClient abstraction
The client package will expose two interchangeable implementations (in-process and HTTP), so the contract moves into the application layer where both can depend on it. SendAsync returns the queued message id.
2026-11-05 09:44:56 +01:00
50b92115bb Refactor SendAsync method in MessagingServiceClient
The `SendAsync` method in the `MessagingServiceClient` class has been refactored. It no longer uses the `async` keyword and instead directly returns the `Task` from `sender.Send`. This change simplifies the method by removing the `await` operation, while still maintaining asynchronous behavior through the returned `Task`.
2026-11-04 15:28:51 +01:00
a7d8b3412b Simplify email test verification
Updated the `SendAsync_WithDependencyInjectionAndRealBroker_PublishesExpectedMessage` test in `MessagingServiceClientTests.cs` to use manual mailbox verification. Added XML documentation to explain the change due to potential shared queue consumption by other services. Simplified the test by removing detailed assertions and replacing them with a placeholder assertion to verify manually.
2026-11-04 15:26:59 +01:00
85d1e844b3 Update project version to 2.2.0-beta
Updated the version numbers in the DigitalData.MessagingService.API.csproj file to reflect a new beta release. The `<Version>` has been changed from `2.1.0-beta` to `2.2.0-beta`, and both `<FileVersion>` and `<AssemblyVersion>` have been updated from `2.1.0.0` to `2.2.0.0`. This version increment suggests the introduction of new features, improvements, or bug fixes, and prepares the project for testing or preview before a stable release.
2026-11-04 15:10:01 +01:00
888f01ea95 Add integration tests for MessagingServiceClient
Introduce `MessagingServiceClientTests` to test email sending
via RabbitMQ with dependency injection. Implement methods to
load configuration, manage RabbitMQ messages, and ensure
proper resource disposal. Include an in-memory email account
repository for testing purposes.
2026-11-04 15:09:51 +01:00
034d81f7f6 feat(client): add MessagingServiceClient and dependency injection extensions
Introduce the Email contract and MessagingServiceClient that send mail through the Application layer via MediatR, and add AddMessagingServiceClient overloads for delegate- and IConfiguration-based setup. Remove the empty client DI placeholders.
2026-11-04 14:53:17 +01:00
eed9a0e915 refactor(application)!: accept license key directly in AddMessagingServiceApplication
Remove MessagingServiceApplicationConfiguration and pass the LuckyPennySoft license key as a string. Program.cs now reads the value from configuration and fails fast with a clear error when it is missing.

BREAKING CHANGE: AddMessagingServiceApplication now takes a license key string.
2026-11-04 14:53:09 +01:00
ad2a5240d2 refactor(publisher)!: simplify AddMessagingServicePublisher registration
Replace the MessagingServicePublisherConfiguration builder with plain overloads that accept either a configuration delegate or IConfiguration. Update EmailSender and the publisher integration test to the new API, and mark the static EmailSender obsolete ahead of the new client.

BREAKING CHANGE: AddMessagingServicePublisher no longer accepts a builder configuration delegate.
2026-11-04 14:53:01 +01:00
51d8931dbe refactor(rabbitmq)!: rename RabbitMqConfiguration to RabbitMqConnectionConfiguration
Rename the RabbitMQ options type to make its purpose explicit and update all consumers in the RabbitMQ, Infrastructure, Publisher, Client and test projects. Inline the connection factory registration in the DI extensions instead of the private AddDefaultServices helper.

BREAKING CHANGE: RabbitMqConfiguration is now RabbitMqConnectionConfiguration.
2026-11-04 14:52:52 +01:00
35094529bb Refactor: Remove IServiceCollection dependency
Removed the IServiceCollection dependency and related code from MessagingServiceApplicationConfiguration.cs. This includes the private property `Services`, the boolean field `_luckyPennySoftLicenseKeyAdded`, and the constructor that initialized `Services`. The `EnsureConfigured` method remains, but its functionality may be impacted by these changes.
2026-11-04 11:37:57 +01:00
8cfa803cd3 Refactor DI and update namespace structure
Removed `AddMessagingServiceApplication` method from `DependencyInjection` class, simplifying service configuration. Updated namespaces from `DigitalData.MessagingService.Infrastructure` to `DigitalData.MessagingService.Infrastructure.DependencyInjection` for better organization. Adjusted `Program.cs` to use a lambda for setting `LuckyPennySoftLicenseKey`. Updated `using` directives in `EmailSyncWorker.cs` and `Program.cs` to reflect these changes.
2026-11-02 15:23:32 +01:00
82be3c5a4f Refactor configuration handling
Refactored `MessagingServiceApplicationConfiguration` to simplify the tracking of the LuckyPennySoft license key configuration by replacing the `_configured` tuple with a boolean. Removed email account configuration methods from this class.

Updated `MessagingServiceInfrastructureConfiguration` to introduce a new `_configured` tuple for tracking `RabbitMqConnectionFactory` and `EmailAccounts` configurations. Added methods for configuring email accounts and updated the `EnsureRabbitMqConnectionFactoryAdded` method to include email account checks.

Changed the namespace of `EmailAccountsOptions.cs` to `DigitalData.MessagingService.Infrastructure.Options`.

Modified `Program.cs` to include email account configuration in the infrastructure setup.

Added new files `DependencyInjectionExtensions.cs` and `MessagingServiceConfiguration.cs` as placeholders for future extensions, wrapped in `#if NET` directives.

Removed an `<ItemGroup>` from `DigitalData.MessagingService.Infrastructure.csproj` and updated `DigitalData.MessagingService.Client.csproj` for XML compliance.
2026-11-02 15:23:21 +01:00
38 changed files with 845 additions and 244 deletions

1
.gitignore vendored
View File

@@ -184,7 +184,6 @@ publish/
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to

135
README.md
View File

@@ -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
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 |
|-------|---------|
| `0` | None — send-only account, skipped by sync worker |
| `0` | None <EFBFBD> send-only account, skipped by sync worker |
| `1` | IMAP with username/password |
| `2` | POP3 with username/password |
| `3` | IMAP with OAuth2 |
@@ -92,7 +207,7 @@ automatically for all subsequent operations.
#### 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:
```
@@ -101,7 +216,7 @@ The application provides a built-in OAuth2 flow
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"**,
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.
@@ -122,7 +237,7 @@ The application provides a built-in OAuth2 flow
### 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
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.
> ?? `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,
> 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.
@@ -200,7 +315,7 @@ Each account is configured under `EmailAccounts.Accounts` in `appsettings.Secret
| 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 |
| `2` | POP3 with username/password |
| `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.
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 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
@@ -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.
> ?? `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,
> or `common`. Short names like `yourorg` are not valid and will cause `AADSTS900023`.

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

View File

@@ -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

View File

@@ -1,6 +1,5 @@
#if NET
using FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
@@ -11,25 +10,22 @@ namespace DigitalData.MessagingService.Application.DependencyInjection;
/// </summary>
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 configuration = new MessagingServiceApplicationConfiguration(services);
configure(configuration);
configuration.EnsureConfigured();
// MediatR - Register all handlers
services.AddMediatR(config =>
{
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
config.LicenseKey = luckyPennySoftLicenseKey;
config.RegisterServicesFromAssembly(assembly);
});
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
services.AddAutoMapper(config =>
{
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
if (luckyPennySoftLicenseKey is not null)
config.LicenseKey = luckyPennySoftLicenseKey;
config.AddMaps(assembly);
});
@@ -38,14 +34,5 @@ public static class DependencyInjection
return services;
}
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, IConfiguration configuration)
{
return services.AddMessagingServiceApplication(cfg =>
{
cfg.SetLuckyPennySoftLicenseKey(configuration);
cfg.ConfigureEmailAccounts(configuration);
});
}
}
#endif

View File

@@ -1,78 +0,0 @@
#if NET
using DigitalData.MessagingService.Application.Common.Options;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Application.DependencyInjection;
public partial class MessagingServiceApplicationConfiguration
{
private IServiceCollection Services { get; }
private (bool LuckyPennySoftLicenseKey, bool EmailAccounts) _configured = (LuckyPennySoftLicenseKey: false, EmailAccounts: false);
internal MessagingServiceApplicationConfiguration(IServiceCollection services)
{
Services = services;
}
internal void EnsureConfigured()
{
if (!_configured.LuckyPennySoftLicenseKey)
{
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
}
if (!_configured.EmailAccounts)
{
throw new InvalidOperationException("EmailAccountsOptions is not configured. Please call ConfigureEmailAccountsOptions() or ConfigureEmailAccounts(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;
_configured.LuckyPennySoftLicenseKey = true;
return this;
}
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(IConfiguration configuration, string key = "LuckyPennySoftLicenseKey")
{
return SetLuckyPennySoftLicenseKey(configuration.GetValue<string>(key) ?? string.Empty);
}
#endregion LuckyPennySoftLicenseKey
#region EmailAccountsOptions
/// <summary>
/// Ignores whether EmailAccountsOptions is configured or not. Use this method if you just want to publish messages to the messaging service; not to send
/// emails. If you want to consume the messaging service to send emails, you must configure EmailAccountsOptions using ConfigureEmailAccountsOptions() or
/// ConfigureEmailAccounts(IConfiguration).
/// </summary>
/// <returns></returns>
public MessagingServiceApplicationConfiguration PublishOnly()
{
_configured.EmailAccounts = true;
return this;
}
public MessagingServiceApplicationConfiguration ConfigureEmailAccountsOptions(Action<EmailAccountsOptions> configureOptions)
{
Services.Configure(configureOptions);
_configured.EmailAccounts = true;
return this;
}
public MessagingServiceApplicationConfiguration ConfigureEmailAccounts(IConfiguration configuration, string sectionName = EmailAccountsOptions.SectionName)
{
Services.Configure<EmailAccountsOptions>(configuration.GetSection(sectionName));
_configured.EmailAccounts = true;
return this;
}
#endregion EmailAccountsOptions
}
#endif

View File

@@ -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

View File

@@ -17,6 +17,10 @@ namespace DigitalData.MessagingService.Application.EmailSending.Commands;
/// </summary>
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; }
/// <summary>

View File

@@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DigitalData.MessagingService.Infrastructure;
namespace DigitalData.MessagingService.Infrastructure.DependencyInjection;
/// <summary>
/// Dependency injection configuration for Infrastructure layer

View File

@@ -0,0 +1,60 @@
using DigitalData.MessagingService.Infrastructure.Options;
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Infrastructure.DependencyInjection;
public class MessagingServiceInfrastructureConfiguration
{
internal IServiceCollection Services { get; }
private (bool RabbitMqConnectionFactory, bool EmailAccounts) _configured = (false, false);
internal MessagingServiceInfrastructureConfiguration(IServiceCollection services)
{
Services = services;
}
public void EnsureRabbitMqConnectionFactoryAdded()
{
if (!_configured.RabbitMqConnectionFactory)
{
throw new InvalidOperationException("RabbitMQ connection factory has not been added. Please call AddRabbitMqConnectionFactory() before using this configuration.");
}
if(!_configured.EmailAccounts)
{
throw new InvalidOperationException("Email accounts options have not been configured. Please call ConfigureEmailAccountsOptions() or ConfigureEmailAccounts() before using this configuration.");
}
}
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConnectionConfiguration> configure)
{
Services.AddRabbitMqConnectionFactory(configure);
_configured.RabbitMqConnectionFactory = true;
return this;
}
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConnectionConfiguration.SectionName)
{
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
_configured.RabbitMqConnectionFactory = true;
return this;
}
#region EmailAccountsOptions
public MessagingServiceInfrastructureConfiguration ConfigureEmailAccountsOptions(Action<EmailAccountsOptions> configureOptions)
{
Services.Configure(configureOptions);
_configured.EmailAccounts = true;
return this;
}
public MessagingServiceInfrastructureConfiguration ConfigureEmailAccounts(IConfiguration configuration, string sectionName = EmailAccountsOptions.SectionName)
{
Services.Configure<EmailAccountsOptions>(configuration.GetSection(sectionName));
_configured.EmailAccounts = true;
return this;
}
#endregion EmailAccountsOptions
}

View File

@@ -38,8 +38,4 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Folder Include="Messaging\" />
</ItemGroup>
</Project>

View File

@@ -1,40 +0,0 @@
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Infrastructure;
public class MessagingServiceInfrastructureConfiguration
{
internal IServiceCollection Services { get; }
private bool _rabbitMqConnectionFactoryAdded = false;
internal MessagingServiceInfrastructureConfiguration(IServiceCollection services)
{
Services = services;
}
public void EnsureRabbitMqConnectionFactoryAdded()
{
if (!_rabbitMqConnectionFactoryAdded)
{
throw new InvalidOperationException("RabbitMQ connection factory has not been added. Please call AddRabbitMqConnectionFactory() before using this configuration.");
}
}
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
{
Services.AddRabbitMqConnectionFactory(configure);
_rabbitMqConnectionFactoryAdded = true;
return this;
}
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
{
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
_rabbitMqConnectionFactoryAdded = true;
return this;
}
}

View File

@@ -1,10 +1,7 @@
#if NET
using DigitalData.MessagingService.Application.Common.Dto;
using DigitalData.MessagingService.Application.Common.Dto.EmailAccounts;
using DigitalData.MessagingService.Application.EmailAccounts.Commands;
using DigitalData.MessagingService.Domain.Entities;
namespace DigitalData.MessagingService.Application.Common.Options;
namespace DigitalData.MessagingService.Infrastructure.Options;
/// <summary>
/// Wrapper options class that holds a list of <see cref="Dto.EmailAccount"/> entries

View File

@@ -17,7 +17,7 @@ public sealed class SendingEmailConsumerPool : IAsyncDisposable
private readonly int _concurrency;
public SendingEmailConsumerPool(
IOptions<RabbitMqConfiguration> config,
IOptions<RabbitMqConnectionConfiguration> config,
IEmailService emailService,
IServiceScopeFactory scopeFactory,
RabbitMqConnectionFactory cnnFactory,

View File

@@ -14,18 +14,19 @@ namespace DigitalData.MessagingService.Infrastructure.Services.Background;
public class ConsumerInitWorker(
SendingEmailConsumerPool ConsumerPool,
ILogger<ConsumerInitWorker> Logger,
IOptions<RabbitMqConfiguration> RabbitMqOptions,
ConsumerInitHealthCheck HealthCheck) : BackgroundService
IOptions<RabbitMqConnectionConfiguration> RabbitMqOptions,
ConsumerInitHealthCheck HealthCheck) : IHostedService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
public async Task StartAsync(CancellationToken cancellationToken)
{
try
{
await ConsumerPool.InitAsync();
Logger.LogInformation("SendingEmailConsumerPool initialized successfully.");
}
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.
Logger.LogError(ex, "Failed to initialize SendingEmailConsumerPool. Outgoing email consumers are not running.");
@@ -34,7 +35,7 @@ public class ConsumerInitWorker(
if (!RabbitMqOptions.Value.ContinueOnInitFailure)
throw;
}
await Task.Delay(Timeout.Infinite, stoppingToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

View File

@@ -1,8 +1,8 @@
using DigitalData.MessagingService.Application.Common.Interfaces;
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
using DigitalData.MessagingService.Application.Common.Options;
using DigitalData.MessagingService.Domain.Entities;
using DigitalData.MessagingService.Domain.Enums;
using DigitalData.MessagingService.Infrastructure.Options;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

View File

@@ -7,15 +7,20 @@ namespace DigitalData.MessagingService.Publisher;
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) ---
services.AddSingleton<ISendingEmailPublisher, SendingEmailPublisher>();
return services;
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, IConfiguration configuration, string rabbitMqConnectionSectionName = RabbitMqConnectionConfiguration.SectionName)
{
services.AddRabbitMqConnectionFactory(configuration.GetSection(rabbitMqConnectionSectionName));
return services.AddMessagingServicePublisher();
}
}

View File

@@ -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;
}
}

View File

@@ -16,12 +16,12 @@ namespace DigitalData.MessagingService.Publisher;
/// </summary>
public sealed class SendingEmailPublisher : ISendingEmailPublisher, IAsyncDisposable
{
private readonly RabbitMqConfiguration _config;
private readonly RabbitMqConnectionConfiguration _config;
private readonly ILogger<SendingEmailPublisher> _logger;
private readonly RabbitMqConnectionFactory _cnnFactory;
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;
_logger = logger;

View File

@@ -9,36 +9,26 @@ namespace DigitalData.MessagingService.RabbitMQ
/// </summary>
public static class DependencyInjection
{
private static IServiceCollection AddDefaultServices(this IServiceCollection services)
{
services.AddSingleton<RabbitMqConnectionFactory>();
return services;
}
/// <summary>
/// Adds Infrastructure layer services to the DI container
/// </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 ---
services.Configure(configure);
return services;
return services.AddSingleton<RabbitMqConnectionFactory>();
}
/// <summary>
/// Adds Infrastructure layer services to the DI container
/// </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 ---
services.Configure<RabbitMqConfiguration>(configuration.GetSection(sectionName));
services.Configure<RabbitMqConnectionConfiguration>(configuration.GetSection(sectionName));
return services;
return services.AddSingleton<RabbitMqConnectionFactory>();
}
}
}

View File

@@ -3,7 +3,7 @@ namespace DigitalData.MessagingService.RabbitMQ
/// <summary>
/// Configuration for RabbitMQ connection
/// </summary>
public class RabbitMqConfiguration
public class RabbitMqConnectionConfiguration
{
/// <summary>
/// Configuration section name in appsettings.json

View File

@@ -12,7 +12,7 @@ namespace DigitalData.MessagingService.RabbitMQ
{
private readonly CancellationTokenSource _consumerCts = new CancellationTokenSource();
private readonly RabbitMqConfiguration _config;
private readonly RabbitMqConnectionConfiguration _config;
private readonly ILogger<RabbitMqConnectionFactory>
#if nullable
@@ -41,7 +41,7 @@ namespace DigitalData.MessagingService.RabbitMQ
return new AsyncEventingBasicConsumer(channel);
}
public RabbitMqConnectionFactory(IOptions<RabbitMqConfiguration> config)
public RabbitMqConnectionFactory(IOptions<RabbitMqConnectionConfiguration> config)
{
_config = config.Value;
_lazyConnectionProvider = new Lazy<Task<IConnection>>(async () =>

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -10,14 +10,16 @@
<Authors>Digital Data GmbH</Authors>
<Company>Digital Data GmbH</Company>
<Product>DigitalData.MessagingService.API</Product>
<Version>2.1.0-beta</Version>
<FileVersion>2.1.0.0</FileVersion>
<AssemblyVersion>2.1.0.0</AssemblyVersion>
<Version>2.2.1-beta</Version>
<FileVersion>2.2.1.0</FileVersion>
<AssemblyVersion>2.2.1.0</AssemblyVersion>
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<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.Settings.Configuration" Version="10.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />

View File

@@ -1,8 +1,9 @@
using DigitalData.MessagingService.API.Middleware;
using DigitalData.MessagingService.Application.DependencyInjection;
using DigitalData.MessagingService.Infrastructure;
using DigitalData.MessagingService.Infrastructure.DependencyInjection;
using DigitalData.MessagingService.Infrastructure.Services.Background;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Serilog;
@@ -48,6 +49,26 @@ try
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
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
@@ -65,10 +86,14 @@ try
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
// Register Application layer (MediatR, AutoMapper, FluentValidation)
builder.Services.AddMessagingServiceApplication(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.)
builder.Services.AddInfrastructure(cfg => cfg.AddRabbitMqConnectionFactory(builder.Configuration));
builder.Services.AddInfrastructure(cfg => cfg
.AddRabbitMqConnectionFactory(builder.Configuration)
.ConfigureEmailAccounts(builder.Configuration));
// Health checks — each check corresponds to a singleton registered in the Infrastructure layer
builder.Services.AddHealthChecks()

View File

@@ -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&amp;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>

View File

@@ -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>

View File

@@ -1,4 +1,11 @@
{
"Hosting": {
"UseWindowsService": true,
"Urls": "http://0.0.0.0:1415"
},
"DataProtection": {
"PersistKeysToFileSystem": true
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",

View File

@@ -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

View File

@@ -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

View File

@@ -11,9 +11,9 @@
<PackageIcon>icon.png</PackageIcon>
<RepositoryUrl>http://git.dd:3000/AppStd/Rec.git</RepositoryUrl>
<PackageTags>digital data messaging service api client</PackageTags>
<Version>1.0.5</Version>
<AssemblyVersion>1.0.5.0</AssemblyVersion>
<FileVersion>1.0.5.0</FileVersion>
<Version>3.0.1</Version>
<AssemblyVersion>3.0.1.0</AssemblyVersion>
<FileVersion>3.0.1.0</FileVersion>
<Description></Description>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
@@ -27,6 +27,7 @@
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.10" />
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.10" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
@@ -61,7 +62,7 @@
<Target Name="EmbedProjectReferences" DependsOnTargets="ResolveReferences">
<ItemGroup>
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget','ProjectReference'))" />
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths-&gt;WithMetadataValue('ReferenceSourceTarget','ProjectReference'))" />
</ItemGroup>
</Target>

View File

@@ -13,14 +13,17 @@ namespace DigitalData.MessagingService.Client;
/// <remarks>
/// This class manages its own internal <see cref="IServiceProvider"/> using a
/// <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>
#if NET
[Obsolete("Use MessagingServiceClient with dependency injection instead.")]
#endif
public static class EmailSender
{
/// <summary>
/// Internal event used to accumulate service registrations before the
/// <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.
/// </summary>
private static event Action<IServiceCollection> ConfigureServices = delegate { };
@@ -43,7 +46,7 @@ public static class EmailSender
/// and the internal <see cref="IServiceProvider"/> has been initialized.
/// </summary>
/// <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"/>.
/// </value>
public static bool IsConnected => LazyProvider.IsValueCreated;
@@ -53,7 +56,7 @@ public static class EmailSender
/// the internal dependency injection container.
/// </summary>
/// <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.
/// </param>
/// <param name="onReconnect">
@@ -64,12 +67,12 @@ public static class EmailSender
/// Thrown when the service is already connected and
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
/// </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)
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
}
@@ -111,7 +114,7 @@ public static class EmailSender
/// </summary>
/// <param name="email">The outgoing email data to enqueue.</param>
/// <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>
/// <remarks>
/// This method maps <see cref="EmailContext"/> to <see cref="SendingEmailEvent"/>,

View File

@@ -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

View File

@@ -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

View File

@@ -1,7 +1,7 @@
namespace DigitalData.MessagingService.Client;
/// <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.
/// </summary>
public enum OnReconnect

View File

@@ -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();
}
}

View File

@@ -24,7 +24,7 @@ public sealed class SendingEmailPublisherTests : IAsyncDisposable
{
var services = new ServiceCollection();
services.AddLogging();
services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(RabbitMqTestConfig.Apply));
services.AddMessagingServicePublisher(RabbitMqTestConfig.Apply);
_serviceProvider = services.BuildServiceProvider();
_publisher = _serviceProvider.GetRequiredService<ISendingEmailPublisher>();

View File

@@ -21,7 +21,7 @@ internal static class RabbitMqTestConfig
public const string DlqExchangeName = "emailprofiler.emails.dlq";
public const string DlqRoutingKey = "email.outbox.dlq";
public static void Apply(RabbitMqConfiguration cfg)
public static void Apply(RabbitMqConnectionConfiguration cfg)
{
cfg.HostName = HostName;
cfg.Port = Port;

View File

@@ -11,12 +11,12 @@ public sealed class EmailSenderUrlParsingTests
{
/// <summary>
/// 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>
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 cfg = new RabbitMqConfiguration();
var cfg = new RabbitMqConnectionConfiguration();
cfg.HostName = uri.Host;
cfg.Port = uri.IsDefaultPort ? 5672 : uri.Port;
@@ -95,7 +95,7 @@ public sealed class EmailSenderUrlParsingTests
[Fact]
public void ParseUrl_WithRootPath_DoesNotOverrideVirtualHost()
{
var defaultVHost = new RabbitMqConfiguration().VirtualHost;
var defaultVHost = new RabbitMqConnectionConfiguration().VirtualHost;
var cfg = ParseUrl("amqp://broker:5672/", "user", "pass");
Assert.Equal(defaultVHost, cfg.VirtualHost);
@@ -104,7 +104,7 @@ public sealed class EmailSenderUrlParsingTests
[Fact]
public void ParseUrl_WithoutPath_DoesNotOverrideVirtualHost()
{
var defaultVHost = new RabbitMqConfiguration().VirtualHost;
var defaultVHost = new RabbitMqConnectionConfiguration().VirtualHost;
var cfg = ParseUrl("amqp://broker:5672", "user", "pass");
Assert.Equal(defaultVHost, cfg.VirtualHost);