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
34 changes: 34 additions & 0 deletions TestHosts/TestHosts/Common/CorrelationIdBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Collections.ObjectModel;
using System.Linq;
using CoreWCF;
using CoreWCF.Channels;
using CoreWCF.Description;
using CoreWCF.Dispatcher;

namespace TestHosts.Common;

public class CorrelationIdBehavior : IServiceBehavior
{
public void Validate(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase) {
// No validation needed for correlation ID behavior
}

public void AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters) {
// No binding parameters needed for correlation ID behavior
}

public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>())
{
foreach (EndpointDispatcher endpoint in dispatcher.Endpoints)
{
endpoint.DispatchRuntime.MessageInspectors.Add(new CorrelationIdMessageInspector());
}
}
}
}
33 changes: 33 additions & 0 deletions TestHosts/TestHosts/Common/CorrelationIdMessageInspector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using CoreWCF;
using CoreWCF.Channels;
using CoreWCF.Dispatcher;

namespace TestHosts.Common;

public class CorrelationIdMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out Object httpRequestMessageObject)
&& httpRequestMessageObject is HttpRequestMessageProperty httpRequest)
{
String correlationId = httpRequest.Headers["correlationId"];

if (!string.IsNullOrWhiteSpace(correlationId))
{
using (NLog.ScopeContext.PushProperty("CorrelationId", correlationId)) {
// Store it globally per operation (e.g., ThreadStatic, AsyncLocal, or Logging Context)
NLog.ScopeContext.PushProperty("CorrelationId", correlationId);
}
}
}

return null;
}

public void BeforeSendReply(ref Message reply, object correlationState)
{
// Optionally, you can add the correlation ID to the reply message headers
}
}
31 changes: 17 additions & 14 deletions TestHosts/TestHosts/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,10 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog.Extensions.Logging;
using TestHosts.Common;

namespace TestHosts
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Metrics;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;
using CoreWCF;
using CoreWCF.Configuration;
using CoreWCF.Description;
Expand All @@ -37,6 +27,18 @@
using Shared.General;
using Shared.Logger;
using Shared.Middleware;
using Shared.TennantContext;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Metrics;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;
using TestHosts.SoapServices;
using ILogger = Microsoft.Extensions.Logging.ILogger;

Expand Down Expand Up @@ -99,12 +101,13 @@
String pataPawaConnectionString = ConfigurationReader.GetConnectionString("PataPawaReadModel");
services.AddDbContext<PataPawaContext>(builder => builder.UseSqlServer(pataPawaConnectionString));
}

services.AddScoped<TenantContext>(x => new TenantContext());
services.AddSingleton<PataPawaPostPayService>();
services.AddMvc();

services.AddServiceModelServices().AddServiceModelMetadata();
services.AddSingleton<IServiceBehavior, UseRequestHeadersForMetadataAddressBehavior>();
services.AddSingleton<IServiceBehavior, CorrelationIdBehavior>();


bool logRequests = ConfigurationReader.GetValueOrDefault<Boolean>("MiddlewareLogging", "LogRequests", true);
Expand Down Expand Up @@ -137,7 +140,7 @@
ILogger logger = loggerFactory.CreateLogger("TestHosts");

Logger.Initialise(logger);
app.UseMiddleware<CorrelationIdMiddleware>();
app.UseMiddleware<TenantMiddleware>();
app.AddRequestLogging();
app.AddResponseLogging();
app.AddExceptionHandler();
Expand Down Expand Up @@ -174,7 +177,7 @@
app.UseServiceModel(builder => {
builder.AddService<PataPawaPostPayService>((serviceOptions) => {
serviceOptions.DebugBehavior.IncludeExceptionDetailInFaults = true;
})
})
// Add a BasicHttpBinding at a specific endpoint
.AddServiceEndpoint<PataPawaPostPayService, IPataPawaPostPayService>(new BasicHttpBinding(), "/PataPawaPostPayService/basichttp");
});
Expand Down Expand Up @@ -224,7 +227,7 @@
protected override async Task ExecuteAsync(CancellationToken stoppingToken){
while (stoppingToken.IsCancellationRequested == false){
// TODO: may introduce a date filter
using ResolvedDbContext<PataPawaContext>? resolvedContext = this.Resolver.Resolve("PataPawaReadModel");

Check warning on line 230 in TestHosts/TestHosts/Startup.cs

View workflow job for this annotation

GitHub Actions / Build and Test Pull Requests

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

var pendingTransactions = await resolvedContext.Context.Transactions.Where(t => t.IsPending).OrderBy(t => t.Date).ToListAsync(stoppingToken);

Expand Down
2 changes: 1 addition & 1 deletion TestHosts/TestHosts/TestHosts.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="9.0.5" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
<PackageReference Include="Shared" Version="2025.7.2" />
<PackageReference Include="Shared" Version="2025.7.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.2" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.5.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.5">
Expand Down
6 changes: 6 additions & 0 deletions TestHosts/TestHosts/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{
"Logging": {
"LogLevel": {
"Microsoft": "None", // Disable all Microsoft logs
"System": "None" // Disable all System logs
}
},
"ConnectionStrings": {
"TestBankReadModel": "server=localhost;user id=sa;password=Sc0tland;database=TestBankReadModel;Encrypt=false",
"PataPawaReadModel": "server=localhost;user id=sa;password=Sc0tland;database=PataPawaReadModel;Encrypt=false"
Expand Down
2 changes: 1 addition & 1 deletion TestHosts/TestHosts/nlog.development.config
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<target name="asyncFile" xsi:type="AsyncWrapper">
<target name="logfile" xsi:type="File"
fileName="/home/txnproc/trace/testhosts/testhosts_dev.log"
layout="$| ${date:format=dd/MM/yyyy HH\:mm\:ss.ffff} | ${level} |${mdlc:CorrelationId:fallback=NO-ID}| ${callsite:className=true} | ${message} | ${exception:format=type,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method:InnerExceptionSeparator= | }"
layout="${date:format=dd/MM/yyyy HH\:mm\:ss.ffff} | ${level} |${mdlc:CorrelationId:fallback=NO-ID}| ${callsite:className=true} | ${message} | ${exception:format=type,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method:InnerExceptionSeparator= | }"
archiveNumbering="Date"
archiveDateFormat="yyyyMMdd-HH"
archiveEvery="Hour"
Expand Down
Loading