PostSharp OnException. How can i get arguments for complex parameters

755 Views Asked by At

I wrote a OnMethodBoundaryAspect attribute for Logging the methods exceptions.

I am in trouble with Complex method parameter.

The method signature is:

TestClass m_tf = new TestClass();
m_tf.DoWorkInternal(1, new Prova1() { ProvaP1=10, ProvaP2=11 });

I be able to trace the first parameter of type int, so i can get the parameter name and value.
But how can i get the values of the properties of the second parameters that is a complex object ?

Thanks in advance. Giuseppe.

RESOLVED.

Found solution.
The aspect method is like this, and write the target method parameters in json format:

    public override void OnException(MethodExecutionArgs args)
    {
        base.OnException(args);

        Dictionary<string, object> m_args = new Dictionary<string, object>();

        for (int i = 0; i < args.Arguments.Count(); i++)
        {
            string name = args.Method.GetParameters()[i].Name;
            object obj = args.Arguments.GetArgument(i);

            m_args.Add(name, obj);
        }

        var output = JsonConvert.SerializeObject(m_args);

        :
        :
    }
1

There are 1 best solutions below

1
On

While you can turn the parameter/argument array into a dictionary and JSON serialize it, another way would be just find it directly using the type.

Following code should do the trick for you.

public override void OnException(MethodExecutionArgs args)
{
    Prova1 prova1 = null;

    var parameters = args.Method.GetParameters();
    var arguments = args.Arguments
    for (int i = 0; i < arguments.Count(); i++)
    {
        var param = parameters[i];
        var arg = arguments[i];
        if (param.ParameterType == typeof(Prova1))
        {
            prova1 = arg;
        }
    }

    var output = prova1;

    // Do your magic

    base.OnException(args);
}

Also, keep in mind of two things.

  1. System.Linq functions should be able to clean out that function a lot.
  2. You are looping through the argument list every time there is an exception. However, the indices of your parameters never change. Thus, you should be able to calculate the index of the complex method parameter once (either in CompileTimeInitialize() or RuntimeInitialize()) and re-use that index.