Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@
<ItemGroup>
<PackageVersion Include="AspNetCore.HealthChecks.SqlServer" Version="9.0.0" />
<PackageVersion Include="AspNetCore.HealthChecks.UI.Client" Version="9.0.0" />
<PackageVersion Include="HealthMonitoring.Client" Version="2026.9.4.53" />
<PackageVersion Include="HealthMonitoring.Client" Version="2026.10.1" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.13" />
<PackageVersion Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageVersion Include="NLog.Web.AspNetCore" Version="6.2.1" />
<PackageVersion Include="Shared" Version="2026.10.3" />
<PackageVersion Include="Shared.Logger" Version="2026.10.3" />
<PackageVersion Include="Shared.Results.Web" Version="2026.10.3" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.0" />
<PackageVersion Include="NLog.Web.AspNetCore" Version="6.2.2" />
<PackageVersion Include="Shared" Version="2026.10.4" />
<PackageVersion Include="Shared.Logger" Version="2026.10.4" />
<PackageVersion Include="Shared.Results.Web" Version="2026.10.4" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.13" />
<PackageVersion Include="Sentry.AspNetCore" Version="6.12.1" />
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="10.0.13" />
<PackageVersion Include="TransactionProcessing.ApiDefaults" Version="2026.10.4" />
</ItemGroup>
</Project>
12 changes: 11 additions & 1 deletion MobileConfiguration/DataTransferObjects/Configuration.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
namespace MobileConfiguration.DataTransferObjects;
using System.ComponentModel;

namespace MobileConfiguration.DataTransferObjects;

[Description("Configuration settings associated with a Transaction Mobile device.")]
public class Configuration
{
[Description("Client identifier used by the mobile device.")]
public string ClientId { get; set; }

[Description("Client secret used by the mobile device. Treat this value as sensitive.")]
public string ClientSecret { get; set; }

[Description("Identifier of the mobile device.")]
public string DeviceIdentifier { get; set; }

[Description("Whether the mobile device should install updates automatically.")]
public bool EnableAutoUpdates { get; set; }

[Description("Service URI values available to the mobile device.")]
public List<HostAddress> HostAddresses { get; set; }

[Description("Unique identifier for this configuration.")]
public string Id { get; set; }

[Description("Minimum severity level written by the mobile client. Enum values are numeric in JSON.")]
public LoggingLevel LogLevel { get; set; }
}
12 changes: 11 additions & 1 deletion MobileConfiguration/DataTransferObjects/ConfigurationResponse.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
namespace MobileConfiguration.DataTransferObjects;
using System.ComponentModel;

namespace MobileConfiguration.DataTransferObjects;

[Description("Configuration returned for a Transaction Mobile device. Includes the client secret.")]
public class ConfigurationResponse
{
[Description("Client identifier used by the mobile device.")]
public string ClientId { get; set; }
[Description("Client secret used by the mobile device. Treat this value as sensitive.")]
public string ClientSecret { get; set; }

[Description("Identifier of the mobile device.")]
public string DeviceIdentifier { get; set; }

[Description("Whether the mobile device should install updates automatically.")]
public bool EnableAutoUpdates { get; set; }

[Description("Service URI values available to the mobile device.")]
public List<HostAddress> HostAddresses { get; set; }

[Description("Unique identifier for this configuration.")]
public string Id { get; set; }

[Description("Minimum severity level written by the mobile client. Enum values are numeric in JSON.")]
public LoggingLevel LogLevel { get; set; }
}
7 changes: 6 additions & 1 deletion MobileConfiguration/DataTransferObjects/HostAddress.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
namespace MobileConfiguration.DataTransferObjects;
using System.ComponentModel;

namespace MobileConfiguration.DataTransferObjects;

[Description("A service type and the URI where the mobile client can reach it.")]
public class HostAddress
{
[Description("Service represented by this address. Enum values are numeric in JSON.")]
public ServiceType ServiceType { get; set; }

[Description("URI for the service endpoint.")]
public string Uri { get; set; }
}
8 changes: 7 additions & 1 deletion MobileConfiguration/DataTransferObjects/LogMessage.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
namespace MobileConfiguration.DataTransferObjects;
using System.ComponentModel;

namespace MobileConfiguration.DataTransferObjects;

[Description("A log event submitted by a mobile client.")]
public class LogMessage
{
[Description("Timestamp associated with the log event.")]
public DateTime EntryDateTime { get; set; }
[Description("Log severity label supplied by the client.")]
public String LogLevel { get; set; }
[Description("Text of the log event.")]
public String Message { get; set; }
}
1 change: 1 addition & 0 deletions MobileConfiguration/MobileConfiguration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" />
<PackageReference Include="Sentry.AspNetCore" />
<PackageReference Include="System.Security.Cryptography.Pkcs" />
<PackageReference Include="TransactionProcessing.ApiDefaults" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;

namespace MobileConfiguration.OpenApi;

/// <summary>
/// Adds representative request and response payloads to the generated OpenAPI document.
/// </summary>
internal sealed class MobileConfigurationExamplesOperationTransformer : IOpenApiOperationTransformer
{
private const string ConfigurationExample = """
{
"clientId": "mobile-client",
"clientSecret": "example-secret",
"deviceIdentifier": "device-123",
"enableAutoUpdates": true,
"hostAddresses": [
{ "serviceType": 2, "uri": "https://transactions.example.test" }
],
"id": "device-123",
"logLevel": 3
}
""";

private const string ConfigurationResponseExample = """
{
"clientId": "mobile-client",
"clientSecret": "example-secret",
"deviceIdentifier": "device-123",
"enableAutoUpdates": true,
"hostAddresses": [
{ "serviceType": 2, "uri": "https://transactions.example.test" }
],
"id": "device-123",
"logLevel": 3
}
""";

private const string CreateSuccessExample = """
{
"status": 0,
"isSuccess": true,
"isFailed": false,
"message": "Configuration created successfully.",
"errors": []
}
""";

private const string CreateFailureExample = """
{
"status": 6,
"isSuccess": false,
"isFailed": true,
"message": "Failed to create configuration: persistence failed.",
"errors": []
}
""";

private const string LogMessagesExample = """
[
{
"entryDateTime": "2026-10-21 09:30:00",
"logLevel": "Information",
"message": "Mobile client started"
}
]
""";

public Task TransformAsync(OpenApiOperation operation,
OpenApiOperationTransformerContext context,
CancellationToken cancellationToken)
{
string path = context.Description.RelativePath?.Trim('/') ?? string.Empty;
string? requestExample = (context.Description.HttpMethod, path) switch
{
("POST", "api/transactionmobile/configuration") => ConfigurationExample,
("PUT", "api/transactionmobile/configuration/{id}") => ConfigurationExample,
("POST", "api/transactionmobile/logging") => LogMessagesExample,
_ => null
};

if (requestExample is not null
&& operation.RequestBody is OpenApiRequestBody requestBody
&& requestBody.Content is not null
&& requestBody.Content.TryGetValue("application/json", out OpenApiMediaType? requestMediaType))
{
requestMediaType.Example = JsonNode.Parse(requestExample);
}

string? successResponseExample = (context.Description.HttpMethod, path) switch
{
("POST", "api/transactionmobile/configuration") => CreateSuccessExample,
("GET", "api/transactionmobile/configuration/{id}") => ConfigurationResponseExample,
_ => null
};

SetResponseExample(operation, "200", successResponseExample);

if (context.Description.HttpMethod == "POST" && path == "api/transactionmobile/configuration")
{
SetResponseExample(operation, "400", CreateFailureExample);
}

return Task.CompletedTask;
}

private static void SetResponseExample(OpenApiOperation operation, string statusCode, string? example)
{
if (example is not null
&& operation.Responses is not null
&& operation.Responses.TryGetValue(statusCode, out IOpenApiResponse? response)
&& response.Content is not null
&& response.Content.TryGetValue("application/json", out OpenApiMediaType? mediaType))
{
mediaType.Example = JsonNode.Parse(example);
}
}
}
69 changes: 58 additions & 11 deletions MobileConfiguration/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.EntityFrameworkCore;
using MobileConfiguration.Database;
using MobileConfiguration.DataTransferObjects;
using MobileConfiguration.Repository;
using NLog;
using NLog.Extensions.Logging;
Expand All @@ -17,6 +18,9 @@
using System.Reflection;
using System.Text.Json;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using SimpleResults;
using TransactionProcessing.ApiDefaults;
using MobileConfiguration.OpenApi;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

Expand Down Expand Up @@ -154,16 +158,23 @@

builder.Services.AddHealthMonitoringRegistration(configuration);

builder.Services.AddApiDefaults(options => {
options.Title = "Mobile Configuration";

Check warning on line 162 in MobileConfiguration/Program.cs

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

MobileConfiguration/Program.cs#L162

Define a constant instead of using this literal 'Mobile Configuration' 4 times.
options.Description = "API to maintain all aspects of mobile device configuration";
});
builder.Services.AddOpenApi(options =>
{
options.AddOperationTransformer(new MobileConfigurationExamplesOperationTransformer());
});

var app = builder.Build();

var serialiser = app.Services.GetRequiredService<IStringSerialiser>();
StringSerialiser.Initialise(serialiser);

app.UseMiddleware<TenantMiddleware>();

app.UseSwagger();
app.UseSwaggerUI();

app.UseApiDefaults();

// Configure the HTTP request pipeline.
app.UseAuthorization();
Expand All @@ -173,24 +184,60 @@


// Minimal API endpoints (handler pattern)
app.MapPost("/api/TransactionMobileConfiguration", MobileConfiguration.Handlers.TransactionMobileConfigurationHandler.PostConfiguration);
app.MapGet("/api/TransactionMobileConfiguration/{id}", MobileConfiguration.Handlers.TransactionMobileConfigurationHandler.GetConfiguration);
app.MapPut("/api/TransactionMobileConfiguration/{id}", MobileConfiguration.Handlers.TransactionMobileConfigurationHandler.PutConfiguration);

app.MapPost("/api/TransactionMobileLogging", MobileConfiguration.Handlers.TransactionMobileLoggingHandler.PostLogging);
String configBaseRoute = "/api/transactionmobile/configuration";

app.MapPost(configBaseRoute, MobileConfiguration.Handlers.TransactionMobileConfigurationHandler.PostConfiguration)
Comment thread
StuartFerguson marked this conversation as resolved.
Resolved
.WithName("CreateTransactionMobileConfiguration")
.WithTags("Mobile Configuration")
.WithSummary("Create a mobile configuration")
.WithDescription("Creates a Transaction Mobile configuration and returns the persistence result. A failed persistence operation is returned as 400 Bad Request.")
.Accepts<Configuration>("application/json")
.Produces<Result>(StatusCodes.Status200OK)
.Produces<Result>(StatusCodes.Status400BadRequest);
app.MapGet($"{configBaseRoute}/{{id}}", MobileConfiguration.Handlers.TransactionMobileConfigurationHandler.GetConfiguration)
.WithName("GetTransactionMobileConfiguration")
.WithTags("Mobile Configuration")
.WithSummary("Get a mobile configuration")
.WithDescription("Returns the Transaction Mobile configuration for the supplied identifier. The response contains the configured client secret.")
.Produces<ConfigurationResponse>(StatusCodes.Status200OK);
app.MapPut($"{configBaseRoute}/{{id}}", MobileConfiguration.Handlers.TransactionMobileConfigurationHandler.PutConfiguration)
.WithName("UpsertTransactionMobileConfiguration")
.WithTags("Mobile Configuration")
.WithSummary("Create or update a mobile configuration")
.WithDescription("Updates the Transaction Mobile configuration for the supplied identifier, or creates it if it does not exist. For an existing record, the path identifier selects the record.")
.Accepts<Configuration>("application/json")
.Produces(StatusCodes.Status200OK);

String loggingBaseRoute = "/api/transactionmobile/logging";

app.MapPost(loggingBaseRoute, MobileConfiguration.Handlers.TransactionMobileLoggingHandler.PostLogging)
.WithName("SubmitTransactionMobileLogs")
.WithTags("Mobile Logging")
.WithSummary("Submit mobile log messages")
.WithDescription("Writes the submitted log messages to the service logger. The messages are not stored in the configuration database.")
.Accepts<List<LogMessage>>("application/json")
.Produces(StatusCodes.Status200OK);

app.MapHealthChecks("health",
new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = Shared.HealthChecks.HealthCheckMiddleware.WriteResponse
});
})
.WithName("HealthCheck")
.WithTags("Health")
.WithSummary("Check service and dependency health")
.WithDescription("Returns health-check details for the service and its configured dependencies.");
app.MapHealthChecks("healthui",
new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
})
.WithName("HealthCheckUi")
.WithTags("Health")
.WithSummary("Get health details for the monitoring UI")
.WithDescription("Returns health-check data formatted for the health monitoring UI.");

InitializeDatabase(app).Wait(CancellationToken.None);

Expand Down Expand Up @@ -222,4 +269,4 @@
serializerOptions.WriteIndented = defaultOptions.WriteIndented;
serializerOptions.Converters.Add(new DateTimeSpaceConverter());
}
}
}
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# MobileConfiguration
# MobileConfiguration

Open Scalar at `/scalar` for the interactive, generated API reference. See [the API and DTO reference](docs/api.md) for endpoint routes, request and response shapes, enum values, and examples.
Loading
Loading