The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Valnuke (9) [Avatar] Offline
Hello, I would like to implement something to log the updates in my database (to check which user updated what)

Since I'm quite a newbie programmer, I thought that you coul give me some good advice or point evident mistake in my code.

(I've also taken parts of code around on the internet(so thanks to these guys) but most of the examples were more complicated and written in c#)

I found 2 major issues on the internet:
1. none of the code I've seen around was dealing with the problem of avoiding logging if the item was not correctly updated... thing that I tried to solve by first adding the log information in a separate list
2. most of them were dealing with definied types of objects (customer, product) while what I want is a method that can deal with all of them


Partial Class myDataContext

Sub SubmitLogChanges()
'List of AuditLog objects, taken from the AuditLogs table in the database,
'a table with information about
'Username, date, table_name, modified item type, oldvalue, newvalue and ID

Dim AuditLogList As New List(Of AuditLog)

'For each update ready to be submitted
For Each item In GetChangeSet.Updates

'Get the table, object type, primary key
Dim myUpdatedTable = GetTable(item.GetType)
Dim pkeyfield = Mapping.GetTable(item.GetType).RowType.DataMembers.Where(Function(x) x.IsPrimaryKey)

Dim mmi = myUpdatedTable.GetModifiedMembers(item)
For Each mi In mmi

Dim newAuditRecord As New AuditLog
With newAuditRecord
'Get information about the logged user, date and values
.Username = myUserID
.Date = Now
.DbTable = mi.Member.Name
.Type = mi.Member.ReflectedType.Name ' same as item.GetType.Name
.OldValue = mi.OriginalValue
.NewValue = mi.CurrentValue
End With

'This is the only way I found (for now) to identify the object, looking for its
'primary key value....
Dim properties() = mi.Member.ReflectedType.GetProperties
If pkeyfield.Count = 1 Then
For Each pr In properties
If pr.Name = pkeyfield.FirstOrDefault.Name Then
With newAuditRecord
.ID = pr.GetValue(item, Nothing)
End With
End If
'If there are more than 1 PK, for example a combined PK....
If pkeyfield.Count > 1 Then
'to do, suggestion appreciated
End If
End If

'This add the Log object to a list

'Modify Database

'insert audit values, if no errors showed up
'Save also the changes in the AuditLogs Table

Catch ex As Exception
End Try
End Sub
End class

If I get to have this correctly working, I'll work on a delete-logger method in the future