I am trying with the Debugger to stop when a method attribute is invoked, but I am never seems to get to the break point.
Am I missing something here?
[SecurityImpl("test")]
public void test()
{
}
[AttributeUsage(AttributeTargets.All)]
public class SecurityImplAttribute : Attribute
{
public SecurityImplAttribute(string test)
{
//Break Point Here
}
}
Attributes are only metadata. They aren't actually created as instances unless you use reflection (GetCustomAttributes). You cannot use attributes to add arbitrary code calls, unless you use an AOP framework such as PostSharp, or are using a framework that checks for specific categories of attributes and instantiates/invokes them explicitly (like ASP.NET MVC does).
Attributes are only decorators and they do not execute by .net framework.
Attrubutes are just metadata for your code. They are not executed automatically. If you want to use some metadata, you should get it manually and execute it. In your case constructor of attribute will be executed when you'll try to get method custom attributes:
object[] attributes = methodInfo.GetCustomAttributes(true);
If you want some aspects to be executed automatically, when you invoke method, then you can use some AOP framework, like PostSharp. Here is an example of aspect creation, which executes some actions on method call:
[Serializable]
public class SecurityImplAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
// this code will be executed on method call
}
}
When you apply this attribute to some method, PostSharp will read method's metatada during compilation, and if aspect will be found, PostSharp will inject your code right into binaries.
Related
I have a bunch of methods with varying signatures. These methods interact with a fragile data connection, so we often use a helper class to perform retries/reconnects, etc. Like so:
MyHelper.PerformCall( () => { doStuffWithData(parameters...) });
And this works fine, but it can make the code a little cluttery. What I would prefer to do is decorate the methods that interact with the data connection like so:
[InteractsWithData]
protected string doStuffWithData(parameters...)
{
// do stuff...
}
And then essentially, whenever doStuffWithData is called, the body of that method would be passed in as an Action to MyHelper.PerformCall(). How do I do this?
So, I just went to a AOP session this weekend, and here's a way to do it with PostSharp:
[Serializable]
public class MyAOPThing : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
Console.WriteLine("OnInvoke! before");
args.Proceed();
Console.WriteLine("OnInvoke! after");
}
}
And then decorate methods with [MyAOPThing]. Easy!
.NET Attributes are meta-data, not decorators / active components that automatically get invoked. There is no way to achieve this behaviour.
You could use attributes to implement decorators by putting the decorator code in the Attribute class and call the method with a helper method that invokes the method in the Attribute class using Reflection. But I'm not sure this would be a big improvement over just calling the "decorator-method" directly.
"Decorator-Attribute":
[AttributeUsage(AttributeTargets.Method)]
public class MyDecorator : Attribute
{
public void PerformCall(Action action)
{
// invoke action (or not)
}
}
Method:
[MyDecorator]
void MyMethod()
{
}
Usage:
InvokeWithDecorator(() => MyMethod());
Helper method:
void InvokeWithDecorator(Expression<Func<?>> expression)
{
// complicated stuff to look up attribute using reflection
}
Have a look at frameworks for Aspect Oriented Programming in C#. These may offer what you want.
This type of problem is pretty much what AOP (aspect oriented programming) aims to solve.
Tools such as PostSharp can provide cross-cutting concerns by re-writing the compiled code.
Scott Hanselman's podcast recently discussed AOP, so it might be worth having a listen.
Without the use of code generation, you can't do much against it. You could probably make the syntax better.
But what about using an extension method?
class static MyHelper
{
Wrap<T>(this object service, Action<T> action)
{
// check attribute and wrap call
}
}
usage:
RawFoo foo = ...
foo.Wrap(x => x.doStuffWithData(parameters...));
This is trivial, but you can't make sure that Wrap had been used.
You could implement a generic decorator. This decorator would be used once to wrap the service and then you can't call it without wrapping.
class Decorator<T>
{
private T implementor;
Decorator(T implementor)
{
this.implementor = implementor;
}
void Perform<T>(Action<T> action)
{
// check attribute here to know if wrapping is needed
if (interactsWithData)
{
MyHelper.PerformCall( () => { action(implementor) });
}
else
{
action(implementor);
}
}
}
static class DecoratorExtensions
{
public static Decorator<T> CreateDecorator<T>(T service)
{
return new Decorator<T>(service);
}
}
Usage:
// after wrapping, it can't be used the wrong way anymore.
ExtendedFoo foo = rawFoo.CreateDecorator();
foo.Perform(x => x.doStuffWithData(parameters...));
Check out aspect oriented frameworks. But be aware that while they hide complexity in each method, the existence of AoP features could make your program harder to maintain. It's a tradeoff.
It seems like what you want is similar to behavior of an IoC container or test runner framework, where it isn't actually executing from your assembly, but is running a dynamically emitted assembly built around your code. (Smarter folks than I have called this AOP in other answers)
So maybe in a stub for your app you could scan the other assemblies, build those emitted assemblies (which call MyHelper.PerformCall with the body of the decorated methods) then your program runs against the emitted code.
By no means would I start down the road of trying to write this without evaluating whether some existing AOP framework could accomplish what you need. HTH>
Seeing that you're willing to add a line of code to every method that needs this, why not just make the call to MyHelper from within the method itself, like this?
protected string doStuffWithData(parameters...)
{
MyHelper.PerformCall( () => { doStuffWithDataCore(parameters...) });
}
private string doStuffWithDataCore(parameters...) {
//Do stuff here
}
With ASP.NET I have created a few filters extending both ExceptionFilterAttribute and ActionFilterAttribute. With ActionFilterAttribute I can execute actions before or after the method's execution. I'd like to mimic that behavior on my class. I have a base class called BaseService and whenever a method from this class is invoked I'd like to check if it contains an attribute and if it does execute that. For instance, on my derived classes I have methods like:
public void DoSomething()
{
LoggedUser.RequireAnyRole<RoleX, RoleY>("DoSomething");
// code here
}
public void DoSomething2()
{
LoggedUser.RequireRole<RoleX>("DoSomething2");
// code here
}
Instead of writing LoggedUser.RequireRole... I'd like it to be an attribute. That way I'd just add an attribute on top of DoSomething2: [RequireRole(Roles.X)].
Is this possible? If so, what is the best approach? I was reading something related to callmember, but I'm not sure that's the way to do it. I checked https://github.com/ASP-NET-MVC/aspnetwebstack for its implementation but I think I didn't know how to search for it since I didn't find anything...
I found this article on the subject and tried the following:
public class FailerAttr : Attribute {
public FailerAttr(string s) {
throw new Exception("I should definitely fail!");
}
}
And in unit test project I have the following:
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class Test {
[TestMethod]
public void GoFail() {
// Make sure attribute will get initialized
new Failer();
}
private class Failer {
[FailerAttr("")]
public int Prop { get; set; }
}
}
When I run the test, it succeeds. So, the questions are:
Why it does not fail?
Is it really a bad idea to throw exceptions from attributes? Because I think I need to.
Some environment info (just in case it's relevant):
Unit tests are run via ReSharper's unit test runner (R# v8.2.0.2160)
Visual studio v11.0.61030.0
Since attributes are part of class definition available to you at runtime (it's also called "metadata" in geekspeak) CLR does not instantiate them unless some part of your program asks for them. This makes sense: why bother spending CPU cycles for something that nobody wants to access?
Because of this, the execution of the constructor will never happen unless you ask for that attribute.
Here is one way to ask for an attribute that would make your program fail:
var attr = Attribute.GetCustomAttribute(typeof(Failer).GetProperty("Prop"), typeof(FailerAttr));
This code makes CLR instantiate the FailerAttr, which triggers the exception.
Demo on ideone.
If you do not know the type of the attribute, you can retrieve all attributes at once with this call:
var allAttributes = Attribute.GetCustomAttributes(typeof(Failer).GetProperty("Prop"));
This causes an exception as well (demo).
Attributes are not converted to executable code, they're converted to metadata.
Metadata like this is not used during normal execution, it is only if you start using the metadata, like through reflection, that the attribute type comes back into play.
The constructor or any of the code in the attribute is not executed during compilation. Instead the type and the parameters to the constructor is serialized into the metadata, and only upon inspection using reflection will the constructor actually be executed.
In other words, if you intend this to fail at compile time then you can't.
Try looking for the attributes using reflection, depending on the attribute object is deserialized from the metadata, the constructor may or may not be invoked, but it will definitely not be invoked by just applying it to identifiers.
I have a bunch of methods with varying signatures. These methods interact with a fragile data connection, so we often use a helper class to perform retries/reconnects, etc. Like so:
MyHelper.PerformCall( () => { doStuffWithData(parameters...) });
And this works fine, but it can make the code a little cluttery. What I would prefer to do is decorate the methods that interact with the data connection like so:
[InteractsWithData]
protected string doStuffWithData(parameters...)
{
// do stuff...
}
And then essentially, whenever doStuffWithData is called, the body of that method would be passed in as an Action to MyHelper.PerformCall(). How do I do this?
So, I just went to a AOP session this weekend, and here's a way to do it with PostSharp:
[Serializable]
public class MyAOPThing : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
Console.WriteLine("OnInvoke! before");
args.Proceed();
Console.WriteLine("OnInvoke! after");
}
}
And then decorate methods with [MyAOPThing]. Easy!
.NET Attributes are meta-data, not decorators / active components that automatically get invoked. There is no way to achieve this behaviour.
You could use attributes to implement decorators by putting the decorator code in the Attribute class and call the method with a helper method that invokes the method in the Attribute class using Reflection. But I'm not sure this would be a big improvement over just calling the "decorator-method" directly.
"Decorator-Attribute":
[AttributeUsage(AttributeTargets.Method)]
public class MyDecorator : Attribute
{
public void PerformCall(Action action)
{
// invoke action (or not)
}
}
Method:
[MyDecorator]
void MyMethod()
{
}
Usage:
InvokeWithDecorator(() => MyMethod());
Helper method:
void InvokeWithDecorator(Expression<Func<?>> expression)
{
// complicated stuff to look up attribute using reflection
}
Have a look at frameworks for Aspect Oriented Programming in C#. These may offer what you want.
This type of problem is pretty much what AOP (aspect oriented programming) aims to solve.
Tools such as PostSharp can provide cross-cutting concerns by re-writing the compiled code.
Scott Hanselman's podcast recently discussed AOP, so it might be worth having a listen.
Without the use of code generation, you can't do much against it. You could probably make the syntax better.
But what about using an extension method?
class static MyHelper
{
Wrap<T>(this object service, Action<T> action)
{
// check attribute and wrap call
}
}
usage:
RawFoo foo = ...
foo.Wrap(x => x.doStuffWithData(parameters...));
This is trivial, but you can't make sure that Wrap had been used.
You could implement a generic decorator. This decorator would be used once to wrap the service and then you can't call it without wrapping.
class Decorator<T>
{
private T implementor;
Decorator(T implementor)
{
this.implementor = implementor;
}
void Perform<T>(Action<T> action)
{
// check attribute here to know if wrapping is needed
if (interactsWithData)
{
MyHelper.PerformCall( () => { action(implementor) });
}
else
{
action(implementor);
}
}
}
static class DecoratorExtensions
{
public static Decorator<T> CreateDecorator<T>(T service)
{
return new Decorator<T>(service);
}
}
Usage:
// after wrapping, it can't be used the wrong way anymore.
ExtendedFoo foo = rawFoo.CreateDecorator();
foo.Perform(x => x.doStuffWithData(parameters...));
Check out aspect oriented frameworks. But be aware that while they hide complexity in each method, the existence of AoP features could make your program harder to maintain. It's a tradeoff.
It seems like what you want is similar to behavior of an IoC container or test runner framework, where it isn't actually executing from your assembly, but is running a dynamically emitted assembly built around your code. (Smarter folks than I have called this AOP in other answers)
So maybe in a stub for your app you could scan the other assemblies, build those emitted assemblies (which call MyHelper.PerformCall with the body of the decorated methods) then your program runs against the emitted code.
By no means would I start down the road of trying to write this without evaluating whether some existing AOP framework could accomplish what you need. HTH>
Seeing that you're willing to add a line of code to every method that needs this, why not just make the call to MyHelper from within the method itself, like this?
protected string doStuffWithData(parameters...)
{
MyHelper.PerformCall( () => { doStuffWithDataCore(parameters...) });
}
private string doStuffWithDataCore(parameters...) {
//Do stuff here
}
I need to create a custom attribute that is applicable only for non static class member.
How can I validate this constraint on project compilation or using code analysis tools?
There's no such constraint.
You could always write some post-build event that uses reflection to verify this... Granted, it may not be the most elegant of solutions....
To set this up, you would go into project properties, then the 'Build Events' tab. You would then enter the command line for the reflection based tool you'd write to implement this verification
It's probably not what you're looking for, but it's possible to make such an attribute with PostSharp, you will probably have something like this:
[Serializable]
public sealed class StaticAttribute : OnMethodBoundaryAspect
{
public override bool CompileTimeValidate(System.Reflection.MethodBase method)
{
return method.IsStatic;
}
The OnMethodBoundaryAspect basically wrapps your method inside a try/catch block, and the CompileTimeValidate method determines whether or not the attribute is invoked at runtime.