C#: How to create an attribute on a method triggering an event when it is invoked?

57

Solution 1

The only way I know how to do this is with PostSharp. It post-processes your IL and can do things like what you asked for.

Solution 2

This concept is used in MVC web applications.

The .NET Framework 4.x provides several attributes which trigger actions, e.g.: ExceptionFilterAttribute (handling exceptions), AuthorizeAttribute (handling authorization). Both are defined in System.Web.Http.Filters.

You could for instance define your own authorization attribute as follows:

public class myAuthorizationAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        // do any stuff here
        // it will be invoked when the decorated method is called
        if (CheckAuthorization(actionContext)) 
           return true; // authorized
        else
           return false; // not authorized
    }

}

Then, in your controller class you decorate the methods which are supposed to use your authorization as follows:

[myAuthorization]
public HttpResponseMessage Post(string id)
{
    // ... your code goes here
    response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status
    return response;
}

Whenever the Post method is invoked, it will call the IsAuthorized method inside the myAuthorization Attribute before the code inside the Post method is executed.

If you return false in the IsAuthorized method, you signal that authorization is not granted and the execution of the method Post aborts.


To understand how this works, let's look into a different example: The ExceptionFilter, which allows filtering exceptions by using attributes, the usage is similar as shown above for the AuthorizeAttribute (you can find a more detailed description about its usage here).

To use it, derive the DivideByZeroExceptionFilter class from the ExceptionFilterAttribute as shown here, and override the method OnException:

public class DivideByZeroExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Exception is DivideByZeroException)
        {
            actionExecutedContext.Response = new HttpResponseMessage() { 
                Content = new StringContent("A DIV error occured within the application.",
                                System.Text.Encoding.UTF8, "text/plain"), 
                StatusCode = System.Net.HttpStatusCode.InternalServerError
                };
        }
    }
}

Then use the following demo code to trigger it:

[DivideByZeroExceptionFilter]
public void Delete(int id)
{
    // Just for demonstration purpose, it
    // causes the DivideByZeroExceptionFilter attribute to be triggered:
    throw new DivideByZeroException(); 

    // (normally, you would have some code here that might throw 
    // this exception if something goes wrong, and you want to make
    // sure it aborts properly in this case)
}

Now that we know how it is used, we're mainly interested in the implementation. The following code is from the .NET Framework. It uses the interface IExceptionFilter internally as a contract:

namespace System.Web.Http.Filters
{
    public interface IExceptionFilter : IFilter
    {
        // Executes an asynchronous exception filter.
        // Returns: An asynchronous exception filter.
        Task ExecuteExceptionFilterAsync(
                    HttpActionExecutedContext actionExecutedContext, 
                    CancellationToken cancellationToken);
    }
}

The ExceptionFilterAttribute itself is defined as follows:

namespace System.Web.Http.Filters
{
    // Represents the attributes for the exception filter.
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, 
            Inherited = true, AllowMultiple = true)]
    public abstract class ExceptionFilterAttribute : FilterAttribute, 
            IExceptionFilter, IFilter
    {
        // Raises the exception event.
        // actionExecutedContext: The context for the action.
        public virtual void OnException(
            HttpActionExecutedContext actionExecutedContext)
        {
        }
        // Asynchronously executes the exception filter.
        // Returns: The result of the execution.
        Task IExceptionFilter.ExecuteExceptionFilterAsync(
            HttpActionExecutedContext actionExecutedContext, 
            CancellationToken cancellationToken)
        {
            if (actionExecutedContext == null)
            {
                throw Error.ArgumentNull("actionExecutedContext");
            }
            this.OnException(actionExecutedContext);
            return TaskHelpers.Completed();
        }
    }
}

Inside ExecuteExceptionFilterAsync, the method OnException is called. Because you have overridden it as shown earlier, the error can now be handled by your own code.


There is also a commercial product available as mentioned in OwenP's answer, PostSharp, which allows you to do that easily. Here is an example how you can do that with PostSharp. Note that there is an Express edition available which you can use for free even for commercial projects.

PostSharp Example (see the link above for full description):

public class CustomerService
{
    [RetryOnException(MaxRetries = 5)]
    public void Save(Customer customer)
    {
        // Database or web-service call.
    }
}

Here the attribute specifies that the Save method is called up to 5 times if an exception occurs. The following code defines this custom attribute:

[PSerializable]
public class RetryOnExceptionAttribute : MethodInterceptionAspect
{
    public RetryOnExceptionAttribute()
    {
        this.MaxRetries = 3;
    }

    public int MaxRetries { get; set; }

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        int retriesCounter = 0;

        while (true)
        {
            try
            {
                args.Proceed();
                return;
            }
            catch (Exception e)
            {
                retriesCounter++;
                if (retriesCounter > this.MaxRetries) throw;

                Console.WriteLine(
                  "Exception during attempt {0} of calling method {1}.{2}: {3}",
                  retriesCounter, args.Method.DeclaringType, args.Method.Name, e.Message);
            }
        }
    }
}

Solution 3

You need some sort of Aspect oriented framework. PostSharp will do it, as will Windsor.

Basically, they subclass your object and override this method...

then it becomes:

//proxy
public override void DoSomeStuff()
{
     if(MethodHasTriggerAttribute)
        Trigger();

     _innerClass.DoSomeStuff();
}

of course all this is hidden to you. All you have to do is ask Windsor for the type, and it will do the proxying for you. The attribute becomes a (custom) facility I think in Windsor.

Solution 4

You can use ContextBoundObject and IMessageSink. See http://msdn.microsoft.com/nb-no/magazine/cc301356(en-us).aspx

Be warned that this approach has a severe performance impact compared with a direct method call.

Share:
57
BackPacker777
Author by

BackPacker777

Updated on April 08, 2020

Comments

  • BackPacker777
    BackPacker777 about 4 years

    My coding style is apparently synchronous. If I have the following code:

    #!/usr/bin/env node
    
    /*
     * AUTHOR  : 
     * CREATED :
     * VERSION :
     * PURPOSE :
     */
    
    'use strict';
    
    var $COLUMNS = 3;
    var $people = [];
    
    function main() {
        readFile('data.csv');
        printFile();
        writeFile();        
    }
    
    function readFile($filePath) {
        var $IN = require('ya-csv');
        var $reader = $IN.createCsvFileReader($filePath, {
            separator: ','
        });
        $reader.on('data', function($item) {
            $people.push($item);
        }).on('end', function() {
            console.dir($people);
        });
    }
    
    function printFile() {
        for (var $i = 0; $i < $people.length; $i++) {
            for (var $j = 0; $j < $COLUMNS; $j++) {
                process.stdout.write($people[$i][$j] + ' ');
            }
            process.stdout.write('\n');
        }
    }
    
    function writeFile() {
        var $OUT = require('ya-csv');
        var $writer = $OUT.createCsvFileWriter('dataX.csv', {
            quote: ''
        });
        $people.forEach(function($item) {
            $writer.writeRecord($item);
        });
    }
    
    main();
    

    Is it possible to use the values in $people globally and use dispatching with main() like I am?

  • Judah Gabriel Himango
    Judah Gabriel Himango over 15 years
    I voted up this answer because it's my thought as well: you're gonna need some tool to run after the build to analyze your IL, look for methods with your attribute, and inject some event logic.
  • cfeduke
    cfeduke over 15 years
    I just found out about PostSharp and went hunting for this question to post it as an answer.
  • Matt
    Matt over 5 years
    The link seems to be broken. It refers to: MSDN Magazine Issues and Downloads, listing all issues of this magazine. Because the answer does not provide any further information, it doesn't help without a working link in place.
  • Deepak Sharma
    Deepak Sharma over 3 years
    just in same if someone is looking for example, can check the git github.com/stdeepak22/CSharp_Method_Interceptor