Reputation: 697
I have to add auditing to a system that I didn't code, and which wasn't programmed with any thought to auditing.
Then I came across Audit.Net, and what an awesome framework!
I'm using the Audit.Mvc extension as well.
Anyways, I want to add a Target object in the HomeController to the AuditEvent object. I have this:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{...
var auditScope = this.GetCurrentAuditScope();
...
}
How do I add the leaveRequest as the Target to auditScope's AuditEvent?
Upvotes: 3
Views: 995
Reputation: 13114
On the current version, the Target object can only be assigned at AuditScope
creation, which you don't control when using Audit.Mvc
extension.
Of course you can do it manually like this:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{
SetTargetObject(leaveRequest);
// ... I guess here the leaveRequest object is modified
leaveRequest.SomeProp = "NewValue";
UpdateTargetObject(leaveRequest);
}
private void SetTargetObject(object value)
{
var scope = this.GetCurrentAuditScope();
scope.Event.Target = new AuditTarget
{
SerializedOld = scope.DataProvider.Serialize(value),
Type = value.GetType().Name
};
}
private void UpdateTargetObject(object value)
{
var scope = this.GetCurrentAuditScope();
scope.Event.Target.SerializedNew = scope.DataProvider.Serialize(value);
}
I will provide a way to re-assign the Target Getter in the next version of the library (really soon), so this kind of use case can be simplified.
But if you only need one version of the leaveRequest
object, you can just use a Custom Field:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{
this.GetCurrentAuditScope().SetCustomField("LeaveRequest", leaveRequest);
// ...
}
Starting on version 14.2.1, the library exposes a SetTargetGetter(Func<object>)
method on the AuditScope
to update the target getter (a function that returns the target object to audit).
So the first example now can be simplified as:
[Audit]
public ActionResult CreateLeavePrerequest(LeaveRequest leaveRequest)
{
this.GetCurrentAuditScope().SetTargetGetter(() => leaveRequest);
// ...
leaveRequest.SomeProp = "NewValue";
}
Upvotes: 1