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.
Related
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
we are trying to implement Logging in our application using AOP (and PostSharp by the way but this question relates to any AOP framework).
The problem we are facing is that the information we get is like:
Entering method XXX with parameters:
parameter content if it is a value type.
anything in the ToString() override if it is done.
classname if the ToString() is not overridden.
This information is not very useful as normally what we get is the 3rd case. We are creating also LOTS of non useful information.
If you have used AOP for logging in any product how did you manage this problem?
Thanks in advance.
A few approaches:
Put a common interface on types that you want to log. (ILoggable, for example). Implementing that interface will give your aspect the ability to log exactly what you want. The downside is that you have to implement/maintain ILoggable for every object that you might log.
Use reflection (which is what I did in this audit example on my blog. It uses an MVC ActionFilter, but the principle is the same). The trade-offs are spelled out in the blog post, but basically it's complexity of using reflection and performance concerns, depending on how much you are logging and how often.
Use serialization. Given an object, serialize it to Json or XML or whatever, and log that string. Depending on what you're doing with the logs, this could range from perfect to worthless, and depending on how the serialization works and how complex the objects are, this could be a performance issue too.
I work on a new kind of AOP Framework to respond on the missing features of existing AOP Framework. You can find my open source project here : NConcern .NET AOP Framework
One of the differences with others is to allow you to develop your advice with System.Linq.Expression to avoid boxing/unboxing, reflection and hash jump based on type. It is a little harder to develop using Expression for beginner but easy for an advanced developer.
Example a simple example of logging (into console) without rewrite your business, reflection and boxing.
a business : Calculator
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
your logging Aspect implemented by linq expression to describe how Advice must work.
public class Logging : IAspect
{
//this is not an advice, this method is called to produce advices
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//generic presentation method
var presentation = typeof(Presentation). GetMethod("Of");
//example log on exception
//instance, arguments and exception are Expressions
yield return Advice.Linq.After.Throwing((instance, arguments, exception) =>
{
Expression.Call
(
typeof(Console).GetMethod("WriteLine",...),
Expression.Call
(
typeof(string).GetMethod("Concat", new Type[] { typeof(string[]) }),
Expression.NewArrayInit(typeof(string), arguments.Select(argument => argument.Type == typeof(string) ? argument : ...).ToArray())
)
)
}
}
}
I was looking at using DynamicProxy classes, and I'm fairly new to this concept. Before I got too far down this road, I was wondering how well these classes work with IntelliSense and type safety?
I'm just afraid of using something like Castle DynamicProxy (or some other ones), and after setting everything up finding out that using my objects provides no IntelliSense or type safety. Can anyone shed any light on this?
I'm looking for a straight answer on how DynamicProxy classes are
used, and whether or not they support intellisense, and if so... how?
Well, in explaining how DynamicProxy classes work, you'll have a clear understanding to why they are type safe, and how they are able to work with intellisense so nicely.
Firstly, let's understand what a DynamicProxy actually is. A proxy class is a class that handles member calls on behalf of another class. This is either done through inheritance (most common) or through composition. So, if you were to hand-write a proxy class, here is what it could look like:
public class Customer
{
public virtual string Name { get; set; }
// etc...
}
public class CustomerProxy : Customer
{
public override string Name
{
get
{
// Do additional functionality...
return base.Name;
}
set
{
// Do additional functionality...
base.Name = value;
}
}
}
Two (2) key features play a crucial role in this working appropriately, inheritance and polymorphism. So, to use the Customer class seamlessly, a ProxyGenerator simply would create an instance of the CustomerProxy class, but return it as a type of Customer. It would basically be the same thing as doing Customer customer = new CustomerProxy();. The "dynamic" portion doesn't really have anything to do with the .NET dynamic keyword, but instead should read "Runtime", because it simply means that the proxy class is generated at runtime (while the application is running), instead of at compile-time. Oh, and in case you are wondering how it does this, it uses System.Reflection.Emit
That's the simple version of what a DynamicProxy is. Different frameworks offer different features when it comes to creating these proxy classes. For example, in Castle Windsor's DynamicProxy one could create Mixins and apply additional interfaces to these proxy classes -- that is, your generated proxy class could potentially look something like this: public class CustomerProxy : Customer, ISomeInterface { ... }, even though the Customer class itself did not implement the ISomeInterface. Here is a really good resource for Castle's DynamicProxy (http://kozmic.net/dynamic-proxy-tutorial/). It goes through the various features and use cases for those features.
It is and type safe so intellisense should work just fine with it.
see this example: DynamicProxy tutorial
you can see that they use generics for instanciating the proxy classes. It means that its fully typed so you've got nothing to worry about.
Proxies can be seen as call interceptors (depending of the kind of proxy implementation), so when you are writing your code is like you were working with a defined interface or class so you will get intelliSense.
Then, depending of the kind of proxy you implement "some" calls to the class/interface members will be intercepted.
[Edit]
If you use the dynamic keyword, for example when implementing a dynamic proxy using a DynamicObject obviously you will not have intelliSense, but this caused by the nature of the dynamic keyword and not by the proxy itself. You can take a look at this link to see how to implement a Proxy using a DynamicObject
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();
}
}
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