I want to be notified whenever a specific method has been called. I was hoping I could accomplish this using Reflection, but my attempts haven't gotten me anywhere. How can I be notified?
I figured using MethodInfo was the way to go, but like I said, I found nothing there that could help me accomplish what I wanted to do.
I cannot change the method or decorate it with attributes or anything. If I could do something like that, I wouldn't need to do this, I could just change the method itself.
Have you considered AOP (aspect-oriented programming)? Something like PostSharp.
I believe the only way to do this is either rewrite the method body so that it notifies you when the method has been called or use CLR Profiling Api.
The first way can be accomplished by using AOP framework. You can use Postsharp (which was turned into a commercial product) to achieve it with OnMethodBoundaryAspect. Here is an example: Derive the class from OnMethodBoundaryAspect
Reflection is half the solution. You need to wrapperize the objects being observed in order to intercept the method calls. Usually thi is done via remoting proxy objects.
Enterprise Library has the Unity Interception block which does exactly what you want. Also you may want to look into Castle framework's DynamicProxy, which gives you extremely thorough control of this interception process.
Googling for Aspect Oriented Programming will give you more information.
you can use extension methods
so you can use different attributes and modify everything before or after the actual method
Related
I was wondering how to go about writing a custom attribute which can access both the input and output parameters of a function.
Below is an example of what I wish to achieve
[CustomAttribute("Creating Foo")]
public Foo CreateFoo(Foo newFoo)
{
//do logic
return newlyCreatedFoo;
}
From this, the CustomAttribute will create an entry in a DB with the "Creating Foo" tag, which is easy enough to do, but I want to be able to access both newFoo and newlyCreatedFoo as well. Is this possible?
Custom attributes can't do that in general: their purpose is to add metadata to a method to view during reflection.
That being said, there are some cases where attributes are leveraged to do that. For example, ASP.Net MVC uses custom attributes that implement IAuthorizationFilter to provide security for some web pages. This works because ASP is using reflection to launch the methods in the first place. Once it gets the method it checks to see if any attributes are IAuthorizationFilters, and does some extra work when they are. See this link for some more info.
Another way to think about this is to consider aspect-oriented programming. I think AOP frameworks for c# tend to make compile time decorations to methods based on attributes that implement a certain interface, but I have not used one.
My favorite way to deal with this is the good old Proxy pattern. Create a logging proxy.
I am afraid that this is not possible with custom attributes.
This could be achieved with post compilation processing. Tools like PostSharp would allow you to achieve this functionality.
Perhaps you should rephrase your question to "How can I intercept calls to specific methods and log the arguments"?
A custom attribute is just a decoration on a method. It does not intercept or in any way affect the execution of a method. It doesn't even know what member it is attached to.
If you want to intercept the calls you can use a dependency injection framework, or any other AOP framework for .NET to do just that. Some of them actually use attributes to mark their targets, but that isn't a requirement.
PostSharp is just one AOP framework for .NET.
Another option, is to use an IoC/Dependency Injection library like MEF to wrap your class in a proxy object that will intercept all calls and only log the values of the methods decorated with a special attribute.
I'd like to intercept and inject custom code when calling 3rd party code in C#. I am using an external library (AutoIt) for GUI automation. The AutoIt dll is provided without source code.
All actions done with this framework are performed from a single class (AutoItClass) providing access to all the methods. I'd like to be able to inject custom code when calling methods on this class, is this possible? For example:
Log some information from within the called method.
Perform any other action from within the method (wait for X seconds).
This would be possible very simply by inheriting from this class and overriding all its methods (which is a must since this is a COM object), but this is not the preferred way. Any comments will be helpful!
I wouldn't use inheritance - you can use composition here. Create your own class which has the same methods - or in fact only the ones you're interested in - and delegate through that. That way you can be sure you won't "miss" any methods accidentally, because anything you don't implement won't be callable through the rest of your codebase... so long as you make sure the rest of your code doesn't refer to the original library class, of course.
You can investigate PostSharp, which is a commercial product that can inject IL into compiled assemblies to perform aspect oriented programming. You can define different kind of behaviour that should happen before and after a method gets executed, for example, which seems to be what you want. This way, as PostSharp handles this in a post-compilation step, you don't need to create any inherited classes from the classes that you want to intercept.
Otherwise if you want a more "pure" solution I would follow Jon's advice about creating a new class that wraps the functionality of the one that you want to intercept. (see Decorator pattern) .
Is there a way that I can track and intercept calls to values in properties that are auto implemented?
I'd like to have code that looks a bit like this:
[Tracked]
public int SomeProperty { get; set; }
Ideally the attribute would be able to intercept changes to the property values. Is this possible?
What I don't want it to have a second piece of code spin over an object later and request the values, but rather the attribute should tack the value as it is being set.
No. The way you do this is by not using auto properties. The only possible solution there is, is to use something like Castle AOP to create automatic wrappers around your class and have that track the changes, but this is a lot of difficult work to implement.
You should be able to do this with an AOP framework, such as PostSharp (which I note is now commercial). There are a few more linked here, but some of the links are dead.
If you want a solution that works at runtime, then you'll want an aspect-oriented programming (AOP) framework; I've used CciSharp with some success. It's not as mature as PostSharp, but works on the same basic principle: it will modify your already-compiled code, producing another assembly.
If you are just wanting this for testing (or profiling), then there is another option: Microsoft Moles (which is also free). It works very differently; it uses a "detour" type of injection to change the program while it's running, intercepting the property getter and setter methods.
I'm primarily an Objective-C/Cocoa developer, but I'm trying to implement the Observer pattern in C#.NET, specifically mimicking the NSKeyValueObserving protocols and methodology.
I've gotten as far as mimicking NSKVO with manual support, as described in Apple's KVO Programming Guide (see http://tinyurl.com/nugolr). Since I'm writing the setValue:forKey: methods myself, I can implement auto KVO notification through there.
However, I'd like to somehow implement auto KVO on all properties by dynamically overriding them at runtime. For example, replacing Button.Title.set with:
set {
this.willChangeValueForKey("title");
title = value;
this.didChangeValueForKey("title");
}
So, this is my question:
How do I dynamically override a method or property at runtime in C#? I've gotten as far as getting and invoking methods and properties by name using Reflection.MethodInfo. Alternatively, can I observe the runtime and find out when a method is about to be/has been called?
Dynamic metaprogramming and aspect oriented programming are not yet strongly supported in C#. What you can do, is look at a free tool called PostSharp - it allows supports weaving aspects into your code around properties and method calls quite easily.
You can implement the INotifyPropertyChanged interface (without postsharp) and it can be used in certain contexts to notify observers that a value of a property has changed. However, it still requires that each property actually broadcast the change notification - which generally requires it to be specifically coded to support that. Injecting change notification to existing code (without actually changing the source) is not an easy thing to do in straight-up C#. PostSharp (other other AOP/dynamic proxy libraries) make this sort of thing dramatically easier.
I'm not sure if you need to go down this road or not. But if you want to implement overrides of a method (i.e. generating new code for the method?) then it is possible with Emit. I would explore any other suggestions first before diving into those deep waters.
You're looking for INotifyPropertyChanged. You can dynamically implement that using PostSharp, Castle DynamicProxy or probably any other proxying library.
This does not solves the problem of having to add the tracking code dynamically, but can be interesting to read: Trackable Properties with Weak Events
With this stuff you are able to track changes to specific properties and it makes easier to implement INotifyPropertyChanged (i.e. track changes to all properties).
After doing extensive research on this subject, it appears that I can't do exactly what I'd like to do with .NET in its current state.
PostSharp's method is done at compile time, meaning I can't dynamically insert my own implementations to methods.
Reflection.Emit allows me to do this dynamically, but it generates a new instance of the created subclass - I need to do this so it works with the original instance.
INotifyPropertyChanging and INotifyPropertyChanged would be perfect if any of the existing .NET classes actually used them.
... so, at the moment I'm a bit stuck. I've put a more detailed piece on what I'm doing and how I'm trying to achieve in a post on my blog. Here's hoping .NET 4.0's dynamic dispatch will help!
I'm trying to use Spring.NET's support for AOP to do dependency injection/inversion of control/aspect-oriented programming (sorry for the slew of buzzwords - maybe I'll post a separate question asking someone to clarify the difference :) ).
Specifically, I want to have intercept a recursive method call, so that every time that the method is invoked, the AOP advice/interceptor will be called.
Spring.Net doesn't appear to intercept anything other than the very first method call. I think that Spring.Net is maintaining exactly 1 chain of interceptors per instance, and not call any more interceptors until that first method invocation has finished.
Does anybody have any info about getting the interceptor (the advice) to be triggered for EVERY method invocation, including recursive calls?
I can provide code/example output, if that's helpful.
Thanks!
See http://forum.springframework.net/showthread.php?t=5331
If you are using proxy-based AOP then this will not work for recursive method calls. The first call against the target will be intercepted by the proxy and your advice will run. Then the method on the target will be invoked, and subsequent calls will stay within the target class, ignorant of the proxy. The only way to make this work is to actually modify your bytecode so that class itself contains the behavior.
I actually haven't worked with Spring.NET (only Spring with Java) so I'm unfortunately ignorant about what kinds of bytecode weaving options exist in the .NET universe.
I know this isn't Spring.NET per se, but have a look at PostSharp. It gives you compile time weaving that doesn't rely on dynamic proxies, and would handle the recursive method call. The configuration is slightly different though...