1
\$\begingroup\$

I am using ADO.NET in my project and I want to have a simple AuditLog. I have below Codes for that but I wounder to know is there a way to Optimize Update Method.

Note : In Update Section I don not want to log all properties , I want to detect All properties that have changes , for this I try to get Last Record was Inserted in database.

 public enum AuditLogType
{
    Insert=1,Update=2,Delete=3
}

    public class Auditable
{

    public static void Insert(object model)
    {
        var result = ToJson(model);


        Insert(result, AuditLogType.Insert);
    }

    public static void Update(object model)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        var primaryProperty = GetPrimaryProperty(model);
        var modelType = model.GetType();
        var OldObject = Activator.CreateInstance(modelType);
        bool doNotCompare = false;

        var sql = $"select top 1 [message] from AuditTable where [ActionType]={(int)AuditLogType.Update} order by id desc ";
        using (var connection = new SqlConnection("Data Source=AF-SHD-WS269;Initial Catalog=AuditLog;user id=sa;password=1"))
        {
            var result = connection.Query<AuditTableDto>(sql).SingleOrDefault();
            if (result != null)
                OldObject = JsonConvert.DeserializeObject(result.Message, modelType);
            else
                doNotCompare = true;
        }
        if (doNotCompare)
        {
            Insert(ToJson(model), AuditLogType.Update);
        }

        foreach (var item in modelType.GetProperties())
        {
            if (item.IsDefined(typeof(IgnoreAudit))) continue;

            var propName = item.Name;
            var newValue = item.GetValue(model);
            var oldValue = item.GetValue(OldObject);
            if (!Object.Equals(newValue, oldValue))
            {
                var val = JsonConvert.SerializeObject(item.GetValue(model));
                dic.Add(propName, val);
            }
        }

        var jsonResult = JsonConvert.SerializeObject(dic);

       Insert(jsonResult);

    }

    private static PropertyInfo GetPrimaryProperty(Object model)
    {
        return model.GetType().GetProperties().SingleOrDefault(attr => attr.CustomAttributes.Any(c => c.AttributeType == typeof(Key)));
    }

    private static string ToJson(object model)
    {
        JsonSerializerSettings _jsonWriter = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,

        };

        var type = model.GetType();
        Dictionary<string, string> dic = new Dictionary<string, string>();

        foreach (PropertyInfo item in type.GetProperties())
        {
            if (item.IsDefined(typeof(IgnoreAudit))) continue;

            var propName = item.Name;

            var propValue = item.GetValue(model);
            if (propValue == null) continue;
            ;

            propValue = JsonConvert.SerializeObject(propValue, Formatting.Indented, _jsonWriter);


            dic.Add(propName, propValue.ToString());
        }


        return JsonConvert.SerializeObject(dic);

    }

    public static void Insert(string message, AuditLogType type)
    {
        var sql = "insert into AuditTable (Message,ActionType) values(@message,@type)";
// insert in db
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ We do not put tags in title if this is not necessary and here it isn't. \$\endgroup\$
    – t3chb0t
    Oct 16 '17 at 7:44
  • \$\begingroup\$ Ok , I did not know it . \$\endgroup\$ Oct 16 '17 at 7:45
  • \$\begingroup\$ Just to make sure... this is your real code, it isn't shortened or otherwise changed or simplified for the question? \$\endgroup\$
    – t3chb0t
    Oct 16 '17 at 8:01
  • \$\begingroup\$ @t3chb0t no it is completely my code and it works fine \$\endgroup\$ Oct 16 '17 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.