Change method from dll C# - c#

I'm using avalondock 2.0 dll in my solution and I need to change IOverlayWindowHost.GetDropAreas method from DockingManager.cs at another project.
But, I don't want to do this at the source file. The method is not virtual and I can't just override it like this
class CustomDockingManager : DockingManager
{
override IEnumerable<IDropArea> GetDropAreas(LayoutFloatingWindowControl draggingWindow)
{
//some changes
}
}

Although not recommended in general, you can use the C# ability to reimplement explicitly just a single method of an interface, like this
class CustomDockingManager : DockingManager, IOverlayWindowHost
{
IEnumerable<IDropArea> IOverlayWindowHost.GetDropAreas(LayoutFloatingWindowControl draggingWindow)
{
// ...
}
}
Note that this way you cannot use the base implementation, you have to write the method from scratch.

You would need to do IL weaving to change a non-virtual method. You've many options here.
Mono.Cecil. Check this other Q&A that might give you some direction on how to solve your issue: C# Intercept/change/redirect a method
PostSharp. If you just want to add some code before and after some method execution, PostSharp makes it easier than emitting intermediate language by hand. You would do it using an OnMethodBoundaryAspect attribute. See this article to get in touch with method aspects: http://www.postsharp.net/blog/post/Day-4-OnMethodBoundaryAspect

Related

Intercept Method Invocation or Property Change with Reflection

I'm trying to create a generic class that will fire an event whenever a method is called or a property is accessed or changed. It may also fire events in response to other changes or actions being taken, but for now, that'll be it.
In order to do so, I'd like to intercept every method call and every property access/change, but I have no way of knowing exactly which methods I'm handling. There's no given interface that defines every generic type T I'll be working with, so I have to use reflection. Here's how I envision it (Trigger<T> is the class, and generic would be of type T):
public Trigger()
{
this.generic = default(T);
foreach (MethodInfo m in generic.GetType().GetMethods())
{
// This is pseudocode, since I can't just set MethodInfo to a new method
m = delegate()
{
m.Invoke(this.generic, null);
if (MethodCalled != null)
MethodCalled(this, eventArgs /*imagine these are valid EventArgs*/);
};
}
}
I realize that I've grossly oversimplified the problem. First off, I'd have to deal with parameters. Second, you can't just override a method programmatically like that. And third, I haven't even started on properties yet. Plus, I'd have to be changing these things for only the object, not the entire type, so I'm not sure how that works either.
I've done my research, and all I find is confusing content. I realize that I'm somehow supposed to be using AOP, but I've never done anything other than OOP and procedural programming, so I'm rather lost in this dense jungle of knowledge. It sounds like I'll need to use PostSharp or Unity, but I still have no clue how after looking at all this, and this, and these two, and also this (all separate links, per word).
Is there any simpler way to do this? And can I even do it without using interfaces or predefined classes?
It's generics that make my problem particularly complicated. If I could just have a class inherit from T, and then use a proxy to capture its method calls and property accesses/changes, then things would maybe be a tad simpler, though I still lack the fundamental understanding of AOP to do that. Any help you can provide would be much appreciated. If possible, please write your answer at a beginner level (though I know my OOP fairly strongly, like I said, I don't know the first thing about AOP).
Without resorting to a full-on AOP framework that uses post-bulid IL weaving, you can use Castle's DynamicProxy and create an interceptor. You can find plenty of tutorials online:
Simple AOP
Short tutorial on CodeProject
This extensive one.
For your interceptor to work, you will need to make sure your generic class's methods and properties are virtual. This allows the DynamicProxy's runtime weaving code to generate a proxy that wraps your class.
You can do it like that using NConcern, a new open source AOP Framework on which I actively work.
public class Trigger<T> : Aspect
{
static public event EventArgs MethodCalled;
static private Trigger<T> m_Singleton = new Trigger<T>();
//Auto weaving aspect
static Trigger()
{
Aspect.Weave<Trigger<T>>(method => method.ReflectedType == typeof(T));
}
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//define an advice to trigger only when method execution not failed
yield return Advice.Basic.After.Returning(() =>
{
if (MethodCalled != null)
{
MethodCalled(this, null);
}
});
}
}
public class A
{
public void Test()
{
}
}
int main(string[] args)
{
Trigger<A>.MethodCalled += ...
new A().Test();
}
You can find a similar Example code source here : Example of observation pattern implemented with NConcern
NConcern AOP Framework is a light framework working at runtime. It work with code injection avoiding factory/proxy by inheritance. It allow you to add aspect to a class by injecting code you can create using simple delegate, ILGenerator or expression tree (linq) before/after or around a method. It can handle sealed class, sealed method, virtual method or explicit/implicit interface implementation.
Into my example, I create a class derived from Aspect (abstract class).
When a class derived from Aspect, it have to implement Advise method by returning an instance of Advice (Before/After/After.Returning/After.Throwing or Around). Each can be created with Delegate or Expression to define what you need to do on method interception.
public class MyAspect : IAspect
{
//this method is called initially (not on interception) to rewrite method body.
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//this block of code means that method will be rewrite to execute a write method name to console before original code only for public methods
if (method.IsPublic)
{
yield return Advice.Basic.Before(() => Console.WriteLine(method.Name));
}
}
}
Usage
//attach myaspect to A class. All methods of A will be passed to Advise method to process methods rewriting.
Aspect.Weave<MyAspect>(method => method.ReflectedType == typeof(A));
//detach myaspect from A class. All methods will be rewrite to give back original code.
Aspect.Release<MyAspect>(method => method.ReflectedType == typeof(A));

Implement method decorators in C#

In python is possible to implement function decorators to extend the behavior of functions and methods.
In particular I'm migrating a device lib from python to C#. The communication with device can generate errors which should reraised with custom exception.
In python I would write like this:
#device_error_wrapper("Device A", "Error while setting output voltage.")
def set_voltage(self, voltage):
"""
Safely set the output voltage of device.
"""
self.__handle.write(":source:voltage:level {0}".format(voltage))
This method call would expand to
try:
self.__handle.write(":source:voltage:level {0}".format(voltage))
except Error:
raise DeviceError("Error while setting output voltage.", "DeviceA")
With this pattern you can easily wrap and extend methods without having to write every try-except clause in every method.
Is it to possible to implement a similar pattern using C#?
If the implementation of the decorator (device_error_wrapper) is needed, please tell.
As others have pointed out, tools like PostSharp allow you to weave in the cross cutting logic during (actually, after) compilation.
The alternative is to do it in runtime. Some IoC tools allow you to define the interceptors which are then added to proxy classes to your implementation. This sounds much more complex then it really is, so I will show an example based on Castle DynamicProxy.
First you define your class which needs to be wrapped.
[Interceptor(typeof(SecurityInterceptor))]
public class OrderManagementService : IOrderManagementService
{
[RequiredPermission(Permissions.CanCreateOrder)]
public virtual Guid CreateOrder(string orderCode)
{
Order order = new Order(orderCode);
order.Save(order); // ActiveRecord-like implementation
return order.Id;
}
}
RequiredPermission serves as a decorator here. The class itself is adorned with Interceptor attribute specifying the handler for the interface method calls. This can also be put into configuration, so it is hidden from the class.
The interceptor implementation contains the decorator logic
class SecurityInterceptor : IMethodInterceptor
{
public object Intercept(IMethodInvocation invocation, params object[] args)
{
MethodInfo method = invocation.Method;
if (method.IsDefined(typeof(RequiredPermission), true) // method has RequiredPermission attribute
&& GetRequiredPermission(method) != Context.Caller.Permission) {
throw new SecurityException("No permission!");
}
return invocation.Proceed(args);
}
private Permission GetRequiredPermission(MethodInfo method)
{
RequiredPermission attribute = (RequiredPermission)method.GetCustomAttributes(typeof(RequiredPermission), false)[0];
return attribute.Permission;
}
}
There are some drawbacks, however:
with DynamicProxy you can only wrap interfaces and virtual methods.
you need to instantiate the object via IoC container and not directly (which is not a problem if you already use IoC container)
You can achieve something similar using Aspect Oriented Programming. I've only used PostSharp in the past but it's not free for commercial use though.
There are other AOP solutions out there and you can certainly achieve something similar using Mono.Cecil, but it would require more work.
Reza Ahmadi wrote a nice little introduction article called Aspect Oriented Programming Using C# and PostSharp. It can give you a clear enough idea of what to expect and how it works.
There's no easy way to implement such decorators in C# - custom Attributes are by default only descriptive. There are however projects that extend C# compiler or runtime so that you can actually use this. I think the best one is PostSharp. With it you can define such method decorator ("aspect" in general) and the method gets wrapped during compilation like you need.
I've also seen this implemented by actually wrapping your classes by decorator classes, but that's a lot of work and I don't think it can be done in a really general way. Wikipedia shows this in Decorator Pattern article
As others have mentioned you are looking for AOP. PostSharp is a good post compile solution, but Castle DynamicProxy is a runtime AOP solution.

Is there a way to apply an attribute to a method that executes first?

Without using a library like PostSharp, is there a way to set up a custom attribute that I can have logic in that when attached to a method, will execute PRIOR to entering that method?
No; attributed are not intended to inject code. Tools like postsharp get around that with smoke and mirrors, but without that: no. Another option might be a decorator pattern,
perhaps dynamically implementing an interface (not trivial by any means). However, adding a utility method-call to the top of the method(s) is much simpler, and presumably fine since if you have access to add attributes you have access to add a method-call.
Or put another way: tools like postsharp exist precicely because this doesn't exist out-of-the-box.
// poor man's aspect oriented programming
public void Foo() {
SomeUtility.DoSomething();
// real code
}
In some cases, subclassing may be useful, especially if the subclass is done at runtime (meta-programming):
class YouWriteThisAtRuntimeWithTypeBuilder : YourType {
public override void Foo() {
SomeUtility.DoSomething();
base.Foo();
}
}

Is there a convenient way to map all interface methods onto a subobject?

Suppose I need to inherit from two classes in C#. This is not allowed, so I can do the following: inherit from one of the classes and include the other class as a member variable, inherit from its interfaces and reimplement all methods of those interfaces by redirecting them onto that member variable:
interface SecondBaseInterface {
void FirstMethod();
void SecondMethod();
};
class MyClass : FirstBaseClass, SecondBaseInterface {
public void FirstMethod()
{
secondBase.FirstMethod();
}
public void SecondMethod()
{
secondBase.SecondMethod();
}
SecondBaseClass secondBase = new SecondBaseClass();
};
now this works, but if there's a lot of methods in SecondBaseInterface it will require lot of typing of code that in fact does nothing useful and I'll have to maintain that code in case SecondBaseInterface changes.
Is there some C# feature that would tell the compiler "for all methods of SecondBaseInterface please call corresponding methods of this member variable" or some other convenient way to do such massive redirection?
There is no simple language feature that springs to mind, here are a few ideas:
Use .NET4.0 DynamicObject, where you can add properties / members on the fly.
Use Aspect Oriented Priogramming, or IL Weaving to add a mixin. See PostSharp for example.
Use some form of code generation, e.g. ReSharper.
I'd like to have that opportunity too, but I don't think it exists. Don't be afraid of doing this, though, if you really need a class that can act as both of its superclasses: it's the well-known delegation pattern (as you probably know).
I think almost every seasoned C# developer has probably wished for this at some stage - especially those who are former Delphi developers. It's called "implementation by delegation", and it was available in Delphi.
In fact the man responsible for this Delphi feature, Steve Teixeira, now works at MSFT. Here's a blog entry where he talks about it.
Unfortunately C# can't do this as the the CLI doesn't support implementation by delegation.
I know the pain.
So much that I've started my own project to solve this: NRoles.
This brings a form of trait (pdf) to C#.
Your code would look like this:
class FirstRole : Role {
public void FirstMethod() { ... }
public void SecondMethod() { ... }
}
class SecondRole : Role {
...
}
class MyClass : Does<FirstRole>, Does<SecondRole> {
}
You can also implement interfaces through the roles, and they'll be carried over to the composing class.

Dynamically building method/property bodies

So I've got this boilerplate code that I want to apply to a bunch of properties of certain classes, that is essentially identical for each one. Rather than have to type this same code out again and again for all of these properties, I was wondering if there was any way I could dynamically build these property methods either post-compile or at runtime, by assigning a C# attribute to the property that includes the slight difference for each method (a string) and then finding these properties by reflection.
I'm aware of PostSharp, but I'm looking for something free or open source.
For example, instead of having to do this:
public string Name {
get { return _member.GetValue( "othername" ); }
set { _member.SetValue( "othername", value ); }
}
...for each property I have, I just want to say this:
[MapTo( "othername" )]
public string Name { get; set; }
Any thoughts?
You can use Mono.Cecil for dynamic code injection.
You can make these properties as virtual and generate class that overrides these properties and compile new class to assembly where overridden properties will be defined. Then you should create instance of dynamic generated class and used it as defined class.
You can do something similar using the Unity interception extension.
OK, so it probably merits its own answer. I am aware of the following AOP Frameworks for which you won't have to pay:
Castle Dynamic Proxy
Introducing LinFu, Code
Looks like you are looking for an AOP (Aspect Oriented Programming) like PostSharp.
It allows you to programatically inject code (just like you mentioned) and is very flexible.
Check out CInject on Codeplex which is an open-source alternative to code injection

Categories

Resources