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
Related
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
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.
I'm using a 3rd party lib to do some work. I'm passing an object to the lib and it performing some actions on each property of the object. It enumerates properties using reflection. This is how it implemented and I can't change it.
I don't know which and how many properties should be processed by the lib at compile-time. This information only available at run-time. So I can't create class declaration in my source code.
It seems dynamic feature of .net4 can't help me because lib using reflection, not dynamic.
Actually I can see only two options here:
Create a huge class definition like this:
class Data
{
public object P1 {get; set;}
public object P2 {get; set;}
....
public object PN {get; set;} // N should be at least 10.000
}
Generate class definition at runtime and use CSharpCodeProvider to compile an use it.
Can you suggest me any other options?
And sadly, I can't replace this lib with another one.
Using the first approach will lead to high memory consumption. I would have chosen use TypeBuilder class to create new types at the runtime.
What you're looking for is known as a Property Bag. You may be able to implement something like this by using ICustomTypeDescriptor to expose additional metadata (assuming your library supports it).
If your consuming library is using Reflection directly (and not taking advantage of designer features like Type Descriptors) then your best bet is probably dynamic generation of a proxy wrapper with the additional properties. Castle DynamicProxy is one good way to do this.
EDIT:
Actually, I'm not sure if Castle supports adding new properties to the proxy object. You might be stuck using IL Emit directly via TypeBuilder. This is non-trivial, as you'll need to learn enough about IL Emit to generate the property accessors and there's a bit of a learning curve. That said, it's interesting and fun stuff and worth the effort if you have the time.
I guess it's about regular GUI element like Grid or PropertyGrid.
Then I would start from reflecting grid's method that accept class instance as parameter, and if it is possible fill internal Dictionary<PropertyInfo, instance> or Dictionary<Name,Value> with my own vales.
If this is impossible, instead of Emit, try to use System.CodeDom:
Link
Alright, so after a few hours of me playing around to no avail, I built a model:
[AttributeUsage(AttributeTargets.All)]
public class PublicAttribute : System.Attribute
{
public enum Access { Public, Private }
public PublicAttribute(string Name, Access acs)
{
}
public PublicAttribute(string Name, Access acs, Action get, Action set)
{
}
}
So that if somebody were to do something like this:
[Public("PublicProperty", PublicAttribute.Access.Public)]
private string PrivateProperty = "hello";
or
[Public("PublicProperty", PublicAttribute.Access.Public, ()=>{return PrivateProperty;}, ()=>{PrivateProperty = value})]
private string PrivateProperty = "hello";
and then if somebody was trying to access PrivateProperty, they could just go:
ContainingClass.PublicProperty = //ect
"PublicProperty". and that is because of the attribute, and it would use those get/set accessors.
What I'd like to know:
Is this even possible?
Is there something that already does this?
If its possible, (even if there is something else) How do i do this?
Basically no to all 3, as C# is a strongly typed language. Even with duck typing what you're trying to achieve doesn't fit the language.
The attributes you've written allow you to interrogate the properties that have those attributes in the class, but you still need to use Reflection to discover which properties of the attribute class are set. The syntax you want to use is checked at compile-time.
No, this is not possible using attributes. Properties are part of the class metadata emitted by the C# compiler, and the C# compiler does not consider custom attributes.
You may be able to do this by using a post-processor such as PostSharp, which can rewrite your assembly after the fact, and can be instructed to consider custom attributes. However, you still wouldn't be able to include a delegate in the attribute: the set of types that can be stored in attribute state is extremely limited.
Microsoft made the WebMethodAttribute in a way reminiscent of what you're trying to describe making it represent more permission than C# public, effectively making a method available outside the application domain to the entire Internet (a very global scope). You might read it to get real implementation insight and ideas.
But you're hitting it very simply. You'll have to program some infrastructure to make it work. It's not automatic and you don't have access to Microsoft's source code for all the details.
I've created a simple Attribute:
[AttributeUsage(AttributeTargets.Method)]
public class InitAttribute : System.Attribute
{
public InitAttribute()
{
Console.WriteLine("Works!");
}
}
and I apply it to a simple method:
static class Logger
{
public static string _severity;
public static void Init(string severity)
{
_severity = severity;
}
[Init()]
public static void p()
{
Console.WriteLine(_severity);
}
}
What is going on is pretty streight-forward. Only, I expect the attribute to perform an action (printing Works!), but this does not happen.
Addictionally, printing "Works!" is of course just for debugging purposes: I'd like to access the instance's property _severity (to check if is != null, for example), but everything I keep reading about attributes (that are pretty new to me) is about accessing the class' methods or properties and so on via reflection. Once I've evaluated _severity, how can I modify the behavior of the decorated method (in this case, rise an exception "Logger is not initialized" and do not execute it)?
Any help appreciated.
If you need to perform an action as control enters a method, you should look at aspect-oriented programming and frameworks such as PostSharp. Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.
Attributes only allow decoration of types and members, but the attribute itself cannot acces the decorated object. You will have to use the constructor parameters of the attribute to pass in any data you require to work with within the attribute.
If you wish to use attributes to automatically alter the behaviour of their target objects, you will have to look at AOP solutions like PostSharp.
The attribute is never actually instantiated and so its constructor is never called. The attribute remains as meta-data until you use reflection to retrieve it. As has been mentioned previously what you are after is an Aspect Oriented Programming tool. PostSharp works by altering the assembly as a post-build step. If you are using the Castle Windsor or Unity Inversion of Control Containers they both offer AOP capabilities as well.