Audit the Current User or Host Identity (XPO)
- 2 minutes to read
If you build a business application that is intended for use by multiple users at the same time, you need to get information on who made a particular change. For this purpose, the CurrentUserName property of the application’s Security System is passed to the Audit Trail system. If you do not use the XAF Security System, handle the QueryCurrentUserName event to specify the user name for audit records. In an XAF Windows Forms application, you can get the user name from the WindowsIdentity object.
- Create the
AuditTrailUserNameHandlerclass that handles theQueryCurrentUserNameevent.
File: MySolution.Win\AuditTrailUserNameHandler.cs
using System.Security.Principal;
namespace MySolution.Win;
public class AuditTrailUserNameHandler {
public AuditTrailUserNameHandler(IAuditTrailService auditTrailService) {
auditTrailService.QueryCurrentUserName += OnQueryCurrentUserName;
}
private void OnQueryCurrentUserName(object sender, QueryCurrentUserNameEventArgs e) {
e.CurrentUserName = WindowsIdentity.GetCurrent().Name;
}
}
- Register the event handler in the DI container.
File: MySolution.Win\ApplicationBuilder.cs
using Microsoft.Extensions.DependencyInjection;
namespace MySolution.Win;
public class ApplicationBuilder : IDesignTimeApplicationFactory {
public static WinApplication BuildApplication() {
var builder = WinApplication.CreateBuilder();
builder.Services.AddSingleton<AuditTrailUserNameHandler>();
//...
}
//...
}
- Ensure that the event handler resolves at the application’s start.
File: MySolution.Win\ApplicationBuilder.cs
using Microsoft.Extensions.DependencyInjection;
namespace MySolution.Win;
public class ApplicationBuilder : IDesignTimeApplicationFactory {
public static WinApplication BuildApplication() {
var builder = WinApplication.CreateBuilder();
// ...
builder.AddBuildStep(application => {
var serviceProvider = ((WinApplication)application).ServiceProvider;
// Resolving the handler ensures the event is attached
serviceProvider.GetRequiredService<AuditTrailUserNameHandler>();
// ...
})
}
}