2

We have legacy code and want to know when application call 'Execute' method.

Legacy code structure:

public class CmsJob
{
    public static string Execute()
    {
    }
}

Is it possible to use IInterceptor or PostSharp.dll to implement additional operation after or before execution static method?

Pavel
  • 1,015
  • 3
  • 13
  • 27
  • I don't think so. Static methods by their very nature are very hard to mock. Usually interceptors base on Polymorphism+Proxies. You cannot use any of those features with static. To do such a think would probably require to create fake dll with fake Execute method which links aganist your dll and executes your interceptor logic then calls Execute. Of course you would need to link your project with that fake dll. – user2184057 Oct 20 '16 at 14:41
  • Thanks @user2184057. You confirmed my assumptions – Pavel Oct 20 '16 at 15:23
  • Can you modify the source and recompile? Can you modify the binary? Is the assembly containing this method signed? – Jeroen Mostert Oct 20 '16 at 15:30
  • I can't do this because it was restricted by license – Pavel Oct 20 '16 at 17:32
  • This can always be done, but how easy it is depends on what you're able to do with the binary. If you're not allowed it to modify it in any way, and it's signed as well (so creating a new one isn't possible because existing code won't load with it), then it can still be done by using the profiling interfaces of the CLR and intercepting JIT compilation of this method, but that gets complicated quickly. If the library isn't signed, however, you can easily replace it with an interface-compatible copy of your own. – Jeroen Mostert Oct 20 '16 at 19:36
  • ...actually, I'm being silly because you only want to know when this method is *called*. That's easy, run it under a debugger and set a breakpoint. [You don't need the source for that](https://blogs.msdn.microsoft.com/tess/2008/04/28/setting-breakpoints-in-net-code-using-bpmd/). You can have the debugger perform an action and continue. This can slow down execution considerably, though. – Jeroen Mostert Oct 20 '16 at 19:41

1 Answers1

1

It is possible to intercept the static method with PostSharp, even if it's declared in an external assembly that you can't modify. You can implement your own OnMethodBoundaryAspect.

[PSerializable]
public class MyAspect : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        // Code to execute before the target method ...
    }
}

Then apply this aspect in your project on the assembly level and set these properties: AttributeTargetAssemblies, AttributeTargetTypes, AttributeTargetMembers.

[assembly:MyAspect(AttributeTargetAssemblies="ThirdPartyAssembly",
                   AttributeTargetTypes="SomeNamespace.CmsJob",
                   AttributeTargetMembers="Execute")]
AlexD
  • 5,011
  • 2
  • 23
  • 34