3

When this method is executed in the Controller:

[Route("deleteIncCloseOut")]
[HttpDelete]
[AuditApi]
public bool deleteIncidentCloseOut(int ID)
{
  try
  {
    using (ESSDataContext ctx = new ESSDataContext())
    {
      ctx.DeleteIncidentCloseOut(ID);
      this.GetCurrentAuditScope().SetCustomField("Dynamic", new { IncidentCloseOutID = ID });
      return true;
    }
  }
  catch (Exception ex)
  {
    log.Error($"{ex.StackTrace}");
    return false;
    throw ex;
  }
}

There is an exception with the stored procedure DeleteIncidentCloseOut(ID), and so the CustomField of the AuditEvent is not being set. However, the DataProvider's InsertEvent is still being executed.

My problem is that in my InsertEvent I have to populate two tables. One table has a brief description of the audit event, and the other contains the properties and values of the object that is set as the CustomField of the AuditEvent object. In this case, I create a dynamic object with the ID as the property. So, I get an entry in my first table that the IncidentCloseOut has been deleted (but actually it hasn't, since an exception was thrown), but I do not get the ID of the supposedly deleted event in the second table (since there was no CustomField set). So I am getting false auditing information. Preferably, the stored procedure wouldn't throw an exception, but I would like the auditing to be correct, even if an exception is thrown.

How can I rectify/improve this situation?

Igavshne
  • 699
  • 7
  • 33

1 Answers1

0

Just set the custom field before calling the stored procedure that throws the exception:

public bool deleteIncidentCloseOut(int ID)
{
  try
  {
    using (ESSDataContext ctx = new ESSDataContext())
    {
      this.GetCurrentAuditScope().SetCustomField("Dynamic", new { IncidentCloseOutID = ID });
      ctx.DeleteIncidentCloseOut(ID);
      return true;
    }
  }
  catch (Exception ex)
  {
    ...
  }
}
thepirat000
  • 12,362
  • 4
  • 46
  • 72
  • I thought about doing this. However, then I have false auditing information if the stored procedure throws an exception. So I added an if-statement in my DataProvider that checks whether the CustomField is set or not, and if not, it adds a description to the EventType, such as " FAULTY". When this gets inserted to the first table in the DB, it is immediately clear that something went wrong with the code where the auditing took place, and it explains why there isn't a record in the second table. – Igavshne Aug 14 '19 at 09:42
  • I also saw that there is the option to discard the audit event. I could add that to the catch clause and then there won't be any auditing if an exception is thrown. https://github.com/thepirat000/Audit.NET#discard-option – Igavshne Aug 21 '19 at 19:19