1- using SenseNet . Diagnostics ;
2- using System ;
1+ using System ;
32using System . Collections . Generic ;
4- using System . Linq ;
5- using System . Text ;
6- using System . Threading . Tasks ;
73
8- namespace SenseNet . Diagnostics
4+ // ReSharper disable once CheckNamespace
5+ namespace SenseNet . Diagnostics ;
6+
7+ /// <summary>
8+ /// Ensures that an audit event is logged when the block is disposed.
9+ /// WARNING: writes event only if the code exit unexpectedly from the using block (Successful == false).
10+ /// The successful block must be performed with explicit audit writing.
11+ /// </summary>
12+ public class AuditBlock : IDisposable
913{
10- public class AuditBlock : IDisposable
11- {
12- private AuditEvent _auditEvent ;
13- private string _operationName ;
14- private IDictionary < string , object > _properties ;
15- private DateTime _startedAt ;
14+ private readonly AuditEvent _auditEvent ;
15+ private readonly string _operationName ;
16+ private readonly IDictionary < string , object > _properties ;
17+ private readonly DateTime _startedAt ;
1618
17- public bool Successful { get ; set ; }
19+ public bool Successful { get ; set ; }
1820
19- public AuditBlock ( AuditEvent auditEvent , string operationName , IDictionary < string , object > properties )
20- {
21- _auditEvent = auditEvent ;
22- _operationName = operationName ?? auditEvent . ToString ( ) ;
23- _properties = properties ?? new Dictionary < string , object > ( ) ;
24- _startedAt = DateTime . UtcNow ;
25- }
21+ public AuditBlock ( AuditEvent auditEvent , string operationName , IDictionary < string , object > properties )
22+ {
23+ _auditEvent = auditEvent ;
24+ _operationName = operationName ?? auditEvent . ToString ( ) ;
25+ _properties = properties ?? new Dictionary < string , object > ( ) ;
26+ _startedAt = DateTime . UtcNow ;
27+ }
2628
27- public void Dispose ( )
29+ public void Dispose ( )
30+ {
31+ if ( ! Successful )
2832 {
29- if ( ! Successful )
30- {
31- _properties . Add ( "Execution" , "UNSUCCESSFUL" ) ;
32- _properties . Add ( "OriginalEvent" , _auditEvent ) ;
33- _properties . Add ( "StartedAt" , _startedAt ) ;
33+ _properties . Add ( "Execution" , "UNSUCCESSFUL" ) ;
34+ _properties . Add ( "OriginalEvent" , _auditEvent ) ;
35+ _properties . Add ( "StartedAt" , _startedAt ) ;
3436
35- var result = new AuditEvent ( _auditEvent . AuditCategory , _auditEvent . EventId , "UNSUCCESSFUL " + _auditEvent . AuditCategory , _operationName ) ;
36- SnLog . WriteAudit ( result , _properties ) ;
37- }
37+ var result = new AuditEvent ( _auditEvent . AuditCategory , _auditEvent . EventId , "UNSUCCESSFUL " + _auditEvent . AuditCategory , _operationName ) ;
38+ SnLog . WriteAudit ( result , _properties ) ;
3839 }
3940 }
40- }
41+ }
0 commit comments