Introduction
Implementing Audit Trail using Binding Source is one of the methods of auditing user interactions with Windows Forms in .NET application.
Such a method can help development with any methodology using third parties.
See Implementing Audit Trail using Entity Framework.
Background
A developer who is involved in Windows Forms applications may get stuck deciding which method to use or how to audit the application. The simplest way is to audit the database using triggers. But in fact, this method has many sensitive views, one of them is that if you save the original changed record into audit table; you have to get the actual values of related table. i.e., if the Employee
table has a field of cityID
, that cityid
has value of 15
which is Cairo
, if another user updates the city table and sets city of Cairo into Alex, then the first user audit will show the changes from Paris into Alex not into Cairo.
The proposed method is to develop a way to save the current readable values to user at the time of changing.
Using BindingSource
control which is most used by any developer, you can audit the current working table prior to actual values represented to user's screen.
Using BindingComplete
event of binding source, you track user interaction with the screen, finally when saving changes, you can also save the instance of the audit object.
Using the Code
To use this method, you may:
- Create a new Windows form
- Add and define your
BindingSource
object in form - Add
BindingComplete
event to above bindingSource
object to track user changes as follows:
if (e.BindingCompleteContext == BindingCompleteContext.ControlUpdate &&
e.Binding.IsBinding)
{
if (! auditDictionary.ContainsKey(e.Binding.BindingMemberInfo.BindingField))
{
string OldValue = ReadDisplayValue(e.Binding.Control);
AuditTrial audit = new AuditTrial(e.Binding.BindingMemberInfo.BindingField, OldValue);
}
}
if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate &&
e.Binding.IsBinding)
{
if (auditDictionary.ContainsKey(e.Binding.BindingMemberInfo.BindingField))
auditDictionary[e.Binding.BindingMemberInfo.BindingField].NewValue =
ReadDisplayValue(e.Binding.Control);
}
The above method writes values into auditDictionary
automatically adding a field with its values.
Finally, you may save the object of auditDictionary
into database as Audit entry.
Points of Interest
If you are using such methods, I recommend setting this code into your base forms for your applications, as it is in generic form and can be applied into any data Provider.