lundi 14 novembre 2016

Mongo DB audit change tracker using Reflection and Recursion on C# objects

I am introducing this question in Code Golf format. Is there anything that does this?

Given:

  • All objects will be of simple types (int, string, bool, byte, etc.) or
  • A class may inherit from a type called BaseType
  • Any other object types are to be ignored.
  • There may be array's or lists
  • The array's or lists may contain other objects or arrays

Example:
A C# object is foo.bar[2].zim.zam = 4; You may assume that foo, bar, zim are of type BaseType or BaseType[] and zam is a number.

Another example, array of arrays:foo[3].bar[2].zim[5].zam = 4; all of type BaseType[] except for zam.

Problem: Mongo Databases store "paths" to objects as a dot notation. The previous examples, in Mongo notation are:
foo.bar[2].zim.zam = 4; = foo.bar.2.zim.zam = 4;
foo[3].bar[2].zim[5].zam = 4; = foo.3.bar.2.zim.5.zam = 4;

But! We don't want all the properties. We want to compare two objects of type BaseType and return a list of :
1) Dot notation string path foo.bar.2.zim.zam
2) Old value 4
3) New value 5

The function call looks like this:

        public List<AuditField> AuditChanges(
           BaseType Old,
           BaseType New)

AuditField looks like this:

class AuditField {
  string path;
  string oldValue;
  string newValue;
}

Simple example:
var a = { foo= { bar= 6 }, zim = 2, zam = null};
var b = { foo= { bar= 4 }, zim = 2, zam = 1};

result as JSON:
AuditChanges(a, b) = [ { path: "foo.bar", oldValue = 6, newValue = 4}, { path: "zam", oldValue = null, newValue = 1}, ]

zim did not change so it's not in the list.

NOTE:
There are some catches:
1) List elements may be added or deleted.
2) List's may be null or of zero count.
3) List elements may be re-arranged!
4) Items of BaseType may be nulled (deleted)
5) Lists containing lists are tricky

You will have to use reflection and recursion. a and b will always be the same type.





Aucun commentaire:

Enregistrer un commentaire