Arti Arti -4 years ago 47
C# Question

User activity log to log old and new value using MVC

I have task to log user activity of the user for the project. So the requirement is to log all the changes to the database ie. any updates to the database has to be logged.

Example:


User1(who is assumed to be admin) tries to update firstname, lastname
of user2 then I should be logging messages like: User1 updated
firstname of user2 from "oldValue" to "newValue"


I am using MVC with entityframework and log4net for logging user activity.

Since I am using model to populate my view I can get the old model and new model. But how can I compare the model and find the differences to log it?

I first thought I can override Equal method of the class but he equal method returns a bool value which will only give me true or false.

But I would like to know old and new values. Any help would be appreciated.

Answer Source

I managed to get it solved by looping through each properties inside a class and get values for the property from both the objects and compare.

Here is the code:

Type types = typeof(ModelName);

//Loop through each properties inside class and get values for the property from both the objects and compare
foreach (System.Reflection.PropertyInfo property in types.GetProperties())
{
    string newValue = string.Empty;
    string oldValue = string.Empty;
    if (types.GetProperty(property.Name).GetValue(modelnew, null) != null)
        newValue = types.GetProperty(property.Name).GetValue(modelnew, null).ToString();
    if (types.GetProperty(property.Name).GetValue(modelOld, null) != null)
        oldValue = types.GetProperty(property.Name).GetValue(modelOld, null).ToString();

    if (newValue.Trim() != oldValue.Trim()) //if both values are not same
    {
        if (!string.IsNullOrEmpty(newValue.Trim()) && !string.IsNullOrEmpty(oldValue.Trim()))//if both values are not null
        {
            //log the update ie. value is updated from oldValue to newValue
        }
        else if (!string.IsNullOrEmpty(oldValue.Trim()))//else if only oldvalue is not null
        {
            //log - oldvalue has been deleted for property.name
        }
        else if (!string.IsNullOrEmpty(newValue.Trim()))
        {
            //log- newValue has been added for property.name
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download