Reflection to find all methods with a PostSharp aspect applied - c#

I have an OnMethodBoundary aspect I created to keep track of progress events in a template method. One of the things that would be useful to know in terms of the overall progress is the number of progress steps that are required by my process before it finishes, i.e. the number of methods tagged with my [AffectsProgress] attribute.
Rather than hard coding it and having to maintain that as I add and remove methods, I've tried using System.Reflection to determine that with code like the following (there were many variants I tried):
typeof (MyModuleWithProgressSteps)
.GetMethods(/* whatever BindingFlags I need */)
.SelectMany(x => x.CustomAttributes.Where(attribute => attribute.AttributeType == typeof (AffectsProgress)))
However, even though I was able to see other attributes when I removed the Where clause, I was unable to find any PostSharp aspects. My naive guess is that PostSharp aspects that interfere with the call stack upon execution aren't actually traditional method attributes and so the System.Reflection library doesn't see them.
Does anyone know of a way I could get what I'm looking for either with System.Reflection or with PostSharp itself? I came across ReflectionSearch and IAspectRepositoryService which require the Ultimate edition but I'm not sure if those are sufficient or not.
Edit: Resolved by #Daniel Balas. Using that answer and the information I found here I ended up with a custom aspect that looked like this and was able to be detected at runtime by reflection:
[Serializable]
[MulticastAttributeUsage(PersistMetaData = true)]
internal class AffectsProgress : OnMethodBoundaryAspect
{
public override void OnExit(MethodExecutionArgs args)
{
// do all my progress-related stuff here
}
}

Multicast attributes are by default removed during the multicasting phase and all instances (there can be quite many if you i.e. multicast to all methods) are passed internally to the Aspect Framework.
You can tell the multicast engine not to remove metadata so that you can access the attribute at runtime. This is done like this:
[MulticastAttributeUsage(PersistMetaData = true)]
Aspect attributes will then be present on declarations on which they have been applied on (i.e. MethodLevelAspect on methods, TypeLevel aspect on types, etc.).

Aspects get weaved as IL code by PostSharp, so the attributes that represent aspects have disappeared after PostSharp has done its post-processing.
The ReflectionSearch should help here (I never tried on my own), because it says:
These methods are only available at build time.
And at build time, that's the last chance to access an aspect attribute before it disappears.

Related

Instantiating object with full name

quick theoric question. I have the following code:
if (partnership != null && partnership.UseCustomNotifier)
{
//some behavior
}
else
{
Integration.Protocol.Client.Notifier protocolNotifier = new Integration.Protocol.Client.Notifier();
}
I have two implementations for partnership that are chosen using reflection. Integration.Protocol is not in the usings. Implementation should be chosen dynamically; thing is, if I comment that last line (the instantiation of protocolNotifier), it will only chose one implementation (the one that does not come from the Integration.Protocol, because is the only one available). Otherwise, it will be chosen dynamically using reflection.
I know that this code sucks (I've improved it already), but I was curious on why this behavior was ocurring. I would guess that when the solution compiles before running, it checks that line where protocolNotifier is instantiated and adds the using on compilation time. Is this correct? Does it only happen within the scope of the method? Or the whole class? I am curious on how the .NET compiler works in those situations.
If I understand you correctly:
partnership is an object of a type that is chosen by using reflection to find all available classes with that name (we'll call it Partnership) and creating an object of the found type
The Integration.Protocol namespace has a class called Partnership (or whatever it's actually called), but there is also another class called Partnership in either this project's code or some other library that you're already using elsewhere
Depending on if you include that last line or not, your reflection code picks one or the other
If I'm correct in that, then I believe the behaviour you're seeing is simply because it's loading the Integration.Protocol library (assuming that is a separate DLL and not actually part of the current project code).
If you show us the code of how you set partnership, then we can confirm this. But if I'm correct, then if you don't use Integration.Protocol in that last line, then that library simply isn't loaded, and your reflection code won't find anything from that library.
It's not that "adding the using on compilation time", because using statements just allow you to not include the namespace when referring to classes. It doesn't have anything to do with whether libraries are loaded at runtime or not.

What does the [Intrinsic] attribute in C# do?

A quick Google search for "instrinsic attribute c#" only returns articles about other attributes, such as [Serializable]. Apparently these are called "intrinsic attributes".
However, there is also an attribute in C# that is itself called [Intrinsic] and I'm trying to figure out what exactly it is and how it works. It doesn't exist on the common attributes page of the .NET Documentation, or anywhere else in the documentation as far as I can see.
This attribute is used inside of .NET Core in several places, for example, in the System.Numerics.Vectors folder, such as Vector2_Intrinsics.cs. Code snippet:
[Intrinsic]
public Vector2(float x, float y)
{
X = x;
Y = y;
}
Here's what I've managed to find after a very limited search through dotnet/corefx repository on github.
[Intrinsic] marks methods, properties and fields that can be potentially replaced/optimized by JIT. Source code comments say something similar (IntrinsicAttribute.cs):
Calls to methods or references to fields marked with this attribute may be replaced at some call sites with jit intrinsic expansions. Types marked with this attribute may be specially treated by the runtime/compiler.
Purpose
For core developers, [Intrinsic] serves at least two purposes:
it notifies the developer that the code of the marked field, method or property can be replaced by VM. So, if the code changes, the change should probably be introduced in both places;
it is used as a flag for JIT-optimizer to quickly identify methods that can potentially be optimized.
To give a rough example: JIT-optimizer can replace Enum.HasFlag with a simple bitwise comparison in some cases and not in the others. To do this it needs to identify the method as Enum.HasFlag, check some conditions and replace it with a more optimal implementation. The optimizer can identify the method by name, but, for performance reasons, it's better to filter out methods by a simple flag before performing string comparisons.
Usage
The attribute is only relevant to core developers. You should only use it in an internal class and only in the case when you want to propose very specific JIT-level optimizations for it. [Intrinsic] is pretty much restricted to a small set of widely used .Net classes, that, for some reason, can't be optimized by other means.
from the comments: I'm planning to propose a Color struct for .NET Core which needs to behave similarly to other built-in types for consistency.
You should probably not use [Intrinsic] in your initial proposal. After it passes, you can think about optimization, and if you have a valid scenario when Color will benefit from low level optimizations, you can suggest using [Intrinsic] on some of its methods or properties.
How It Works
Here's how [Intrinsic] is currently used in core:
it is defined as a well-known attribute (wellknownattributes.h):
case WellKnownAttribute::Intrinsic:
return "System.Runtime.CompilerServices.IntrinsicAttribute";
VM parses it and sets the IsJitIntrinsic flag to true for a method (methodtablebuilder.cpp):
if (bmtProp->fIsHardwareIntrinsic || (S_OK == GetCustomAttribute(pMethod->GetMethodSignature().GetToken(),
WellKnownAttribute::Intrinsic,
NULL,
NULL)))
{
pNewMD->SetIsJitIntrinsic();
}
this flag is used to set another flag in method attributes (jitinterface.cpp):
if (pMD->IsJitIntrinsic())
result |= CORINFO_FLG_JIT_INTRINSIC;
this flag is later used to filter out methods which are obviously not intrinsic (importer.cpp):
if ((mflags & (CORINFO_FLG_INTRINSIC | CORINFO_FLG_JIT_INTRINSIC)) != 0)
{
const bool isTail = canTailCall && (tailCall != 0);
call = impIntrinsic(newobjThis, clsHnd, methHnd, sig, mflags, pResolvedToken->token, readonlyCall, isTail,
pConstrainedResolvedToken, callInfo->thisTransform, &intrinsicID, &isSpecialIntrinsic);
impIntrinsic then calls lookupNamedIntrinsic to identify (mostly by name) methods that really (not just potentially) should be optimized;
after all of that importer can perform optimizations based on method. For example, optimization for Enum.HasFlag (importer.cpp):
case NI_System_Enum_HasFlag:
{
GenTree* thisOp = impStackTop(1).val;
GenTree* flagOp = impStackTop(0).val;
GenTree* optTree = gtOptimizeEnumHasFlag(thisOp, flagOp);
if (optTree != nullptr)
{
// Optimization successful. Pop the stack for real.
impPopStack();
impPopStack();
retNode = optTree;
}
else
{
// Retry optimizing this during morph.
isSpecial = true;
}
break;
}
DISCLAIMER: as far as I can tell, the attribute's behaviour is not properly documented anywhere and, thus, is subject for change. The description above is only relevant to code currently in master, this part of core is actively developed and the whole process can be changed in the future.
History
Here's a short timeline of [Intrinsic] based on github repository history:
At some time before 2014 [JitIntrisic] attribute was introduced as a part of System.Numerics with a goal to support new processor instructions (see How does JitIntrinsicAttribute affect code generation?).
On June 6, 2016, Chris McKinsey opened an issue #5626. "Optimize enum1.HasFlag(enum2) into inline bittest without boxing allocations when types are the same". At the time, Enum.HasFlag had a well-known performance issues (see What is it that makes Enum.HasFlag so slow?).
While working on the issue Andy Ayers suggested to introduce a universal mechanism to introduce JIT intrinsics (Issue #13813: Add more flexible method for specifying jit instrinsics)
This led to two pull requests: New jit intrinsic support introduced the general mechanics for [Intrinsic] and JIT: optimize Enum.HasFlag implemented it for Enum.HasFlag. I suggest going through both of them as they are extremely illustrative on the changes that come with [Intrinsic].
Later, during the discussion about moving Vector classes to the CoreLib it was suggested that [JitIntrinsic] isn't used anywhere and should be replaced/removed:
#jkotas: We should not need the JitIntrinsicAttribute. As far as I know, this attribute was future proofing, never used for anything real. We should delete it, and use the IntrinsicAttribute from CoreLib instead.
Promptly, [JitIntrinsic] was removed and replace by [Intrinsic] (Replace JitIntrinsicAttribute with IntrinsicAttribute). That's how this attribute came to be in Vector2.
Explanation:
Special types are indicated to the compiler using the
IntrinsicAttribute custom attribute. If a type is annotated with the
IntrinsicAttribute attribute, the compiler knows not that the
implementation for the given type will be present at runtime.
Methods for types marked as Intrinsic can declare methods to be
extern, in which case the implementation is assumed to be available at
runtime.
Source: MSIL to JavaScript Compiler, section 4.4.1.1
Link: http://tenpow.com/Academics/MSIL2JS/MSIL2JS.pdf
In general, I would suggest not to care about it, nor use it for your own classes.

Why is Object.GetType() a method instead of a property?

From a design perspective, I wonder why the .NET creators chose System.Object.GetType() instead of a System.Object.Type read-only property.
Is it just a (very minor) design flaw or is there rationale behind there?
Any lights welcome.
If you look at the GetType() declaration in Reflector you'll find this:
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
What that combination of attribute and extern means is that this method is actually implemented in unmanaged code inside the .NET runtime itself. The GUID question in this article goes into further details. They obviously did this for performance reasons after determining that figuring out the Type would be faster if handled at a lower level.
This leads to two reasons not to implement the GetType method as a property. Firstly you can't define properties extern as you can with methods, so it would need to be handled in native .NET code. Secondly even if you could define them as extern, performing an unsafe, unmanaged call from inside a property would definitely break the guidelines for property usage since it's much harder to guarantee that there are no side effects.
The guidelines say that a property should represent a state of the object, it should not be expensive performance wise, and it should not have side effects apart from computing/setting that state. My guess is GetType() does not respect these rules so they made it a method.
GetType() is a slightly expensive operation. If it were a property it would encourage uses like
DoStuff(obj.Type);
....
DoStuff(obj.Type);
etc.
instead of
Type type = obj.GetType();
DoStuff(type);
....
DoStuff(type);
and that would be not so optimal. So they made it a method to suggest that it should be called sparingly.
As I understand it, it is in general considered good practice for internal fields or values which are trivial to calculate to be exposed using a property, and other values, which may require more time or other resources to calculate, to be exposed using a method.
Only Microsoft can answer that question, but I think it's because several classes in the .NET Framework create their own overloaded versions of GetType() with extra parameters. If it would have been a property, they couldn't use the same name (because properties don't have parameters).
Just my thoughts on the subject.
A bit late reply but crashed into the question while trying to find something related.
It is possible for GetType to throw an exception. Framework guidelines state that properties should not throw exceptions. This is one more reason why it should be a method instead of property.

What problems does reflection solve?

I went through all the posts on reflection but couldn't find the answer to my question.
What were the problems in the programming world before .NET reflection
came and how it solved those problems?
Please explain with an example.
It should be stated that .NET reflection isn't revolutionary - the concepts have been around in other framework.
Reflection in .NET has 2 facets:
Investigating type information
Without some kind of reflection / introspection API, it becomes very hard to perform things like serialization. Rather than having this provided at runtime (by inspecting the properties/fields/etc), you often need code-generation instead, i.e. code that explicitly knows how to serialize each of your types. Tedious, and painful if you want to serialize something that doesn't have a twin.
Likewise, there is nowhere to store additional metadata about properties etc, so you end up having lots of additional code, or external configuration files. Something as simple as being able to associate a friendly name with a property (via an attribute) is a huge win for UI code.
Metaprogramming
.NET reflection also provides a mechanism to create types (etc) at runtime, which is hugely powerful for some specific scenarios; the alternatives are:
essentially running a parser/logic tree at runtime (rather than compiling the logic at runtime into executable code) - much slower
yet more code generation - yay!
I think to understand the need for reflection in .NET, we need to go back to before .NET. After all, modern languages like like Java and C# do not have a history BF (before reflection).
C++ arguably has had the most influence on C# and Java. But C++ did not originally have reflection and we coded without it and we managed to get by. Occasionally we had void pointer and would use a cast to force it into whatever type we wanted. The problem here was that the cast could fail with terrible consequences:
double CalculateSize(void* rectangle) {
return ((Rect*)rectangle)->getWidth() * ((Rect*)rectangle)->getHeight());
}
Now there are plenty of arguments why you shouldn't have coded yourself into this problem in the first place. But the problem is not much different from .NET 1.1 with C# when we didn't have generics:
Hashtable shapes = new Hashtable();
....
double CalculateSize(object shape) {
return ((Rect)shape).Width * ((Rect)shape).Height;
}
However, when the C# example fails it does so with a exception rather than a potential core dump.
When reflection was added to C++ (known as Run Time Type Identification or RTTI), it was hotly debated. In Stroustrup's book The Design and Evolution of C++, he lists the following
arguments against RTTI, in that some people:
Declared the support unnecessary
Declared the new style inherently evil ("against the spirit of C++")
Deemed it too expensive
Thought it too complicated and confusing
Saw it as the beginning of an avalanche of new features
But it did allow us to query the type of objects, or features of objects. For example (using C#)
Hashtable shapes = new Hashtable();
....
double CalculateSize(object shape) {
if(shape is Rect) {
return ((Rect)shape).Width * ((Rect)shape).Height;
}
else if(shape is Circle) {
return Math.Power(((Circle)shape).Radius, 2.0) * Math.PI;
}
}
Of course, with proper planning this example should never need to occur.
So, real world situations where I've needed it include:
Accessing objects from shared memory, all I have is a pointer and I need to decide what to do with it.
Dynamically loading assemblies, think about NUnit where it loads every assembly and uses reflection to determine which classes are test fixtures.
Having a mixed bag of objects in a Hashtable and wanting to process them differently in an enumerator.
Many others...
So, I would go as far as to argue that Reflection has not enabled the ability to do something that couldn't be done before. However, it does make some types of problems easier to code, clearer to reader, shorter to write, etc.
Of course that's just my opinion, I could be wrong.
I once wanted to have unit tests in a text file that could be modified by a non-technical user in the format in C++:
MyObj Function args //textfile.txt
But I couldn't find a way to read in a string and then have the code create an object instance of the type represented by the string without reflection which C++ doesn't support.
char *str; //read in some type from a text file say the string is "MyObj"
str *obj; //cast a pointer as type MyObj
obj = new str; //create a MyObj
Another use might be to have a generic copy function that could copy the members of an class without knowing them in advance.
It helps a lot when you are using C# attributes like [Obsolete] or [Serializable] in your code. Frameworks like NUnit use reflection on classes and containing methods to understand which methods are tests, setup, teardown, etc.

Have trivial properties ever saved your bacon?

There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over.
I understand the arguments, but I don't think it's good advice in most cases.
Does anyone have an example of a time when it really mattered? When writing a trivial property made something important possible in the future (or when failing to use one got them in to real trouble)?
EDIT: The DataBinding argument is correct, but not very interesting. It's a bug in the DataBinding code that it won't accept public fields. So, we have to write properties to work around that bug, not because properties are a wise class design choice.
EDIT: To be clear, I'm looking for real-world examples, not theory. A time when it really mattered.
EDIT: The ability to set a breakpoint on the setter seems valuable. Designing my code for the debugger is unfortunate: I'd rather the debugger get smarter, but given the debugger we have, I'll take this ability. Good stuff.
It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming.
Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing a public field. Fast enough that I'll never notice.
Some non-trivial things that come to mind
A public field is totally public, you can not impose read-only or write-only semantics
A property can have have different get versus set accessibility (e.g. public get, internal set)
You can not override a field, but you can have virtual properties.
Your class has no control over the public field
Your class can control the property. It can limit setting to allowable range of values, flag that the state was changed, and even lazy-load the value.
Reflection semantics differ. A public field is not a property.
No databinding, as others point out. (It's only a bug to you. - I can understand Why .net framework designers do not support patterns they are not in favour of.)
You can not put a field on an interface, but you can put a property on an interface.
Your property doesn't even need to store data. You can create a facade and dispatch to a contained object.
You only type an extra 13 characters for correctness. That hardly seems like speculative generality. There is a semantic difference, and if nothing else, a property has a different semantic meaning and is far more flexible than a public field.
public string Name { get; set; }
public string name;
I do recall one time when first using .net I coded a few classes as just fields, and then I needed to have them as properties for some reason, and it was a complete waste of time when I could have just done it right the first time.
So what reasons do you have for not following convention? Why do you feel the need to swim upstream? What has it saved you by not doing this?
I've had a trivial property save me a couple of times when debugging. .Net doesn't support the concept of a data break point (read or write). Occasionally when debugging a very complex scenario it was important to track read/writes to a particular property. This is easy with a property but impossible with a field.
If you're not working in a production environment, it's simple to refactor a field -> property for the purpose of debugging. Occasionally though you hit bugs that only reproduce in a production environment that is difficult to patch with a new binary. A property can save you here.
It's a fairly constrained scenario though.
I used to think the same thing, Jay. Why use a property if it's only there to provide direct access to a private member? If you can describe it as an autoproperty, having a property at all rather than a field seemed kind of silly. Even if you ever need to change the implementation, you could always just refactor into a real property later and any dependent code would still work, right?. Well, maybe not.
You see, I've recently seen the light on trivial properties, so maybe now I can help you do the same.
What finally convinced me was the fairly obvious point (in retrospect) that properties in .Net are just syntactic sugar for getter and setter methods, and those methods have a different name from the property itself. Code in the same assembly will still work, because you have to recompile it at the same time anyway. But any code in a different assembly that links to yours will fail if you refactor a field to a property, unless it's recompiled against your new version at the same time. If it's a property from the get-go, everything is still good.
I'll answer your question with another one: have you ever really benefited from not making all your types and members public? I suspect I haven't directly prevented any bugs by doing so. However, I've encapsulated my types properly, only exposing what's meant to be exposed. Properties are similar - good design more than anything else. I think of properties as conceptually different from fields; they're part of the contract rather than being fundamentally part of the implementation. Thinking about them as properties rather than fields helps me to think more clearly about my design, leading to better code.
Oh, and I've benefited occasionally from not breaking source compatibility, being able to set breakpoints, log access etc.
Part of the idea is that those properties may not be trivial in the future - if you bound external code to a field and later wanted to wrap that in a property, all of the dependent code would have to change, and you may not be able to do that, especially in the case where you are a control designer or have libraries that you can't control, etc.
Not to mention there are certain .NET practices that will not allow you to use a field - databinding particularly.
I am sure there are other good reasons as well. Why does it matter to you? Use an automatic property and be done with it. Seems like something not worth being concerned about to me...
It's much easier to debug a problem involving a field if it is wrapped by a property accessor. Placing breakpoints in the accessor can quite quickly help with finding re-entrancy and other issues that otherwise might not be caught. By marshaling all access to the field through an accessor, you can ascertain exactly who is changing what and when.
In .NET, from my understanding, you cannot databind to public fields; but only to properties. Thus, if you want to do databinding, you have no choice.
I once had fields that I wanted to expose from a windows from project which allowed the stats for the program (TotalItems and SuccessfulItems).
Later I decided to display the stats on the form and was able to add a call in the setter that updated the display when the property changed.
Obviously, if you're not creating a shared class library, and you're not using DataBinding, then using a field will cause you no problems whatsoever.
But if you're creating a shared class library, you'd be foolish IMHO to do otherwise than follow the guidelines, for the usual three reasons:
consumers of your shared class library may want to use DataBinding.
consumers of your shared class might want binary compatibility, which is not possible if you switch from a field to a property.
the principal of least surprise implies you should be consistent with other shared class libraries including the .NET Framework itself.
IMHO there is no such thing as a trivial property as people have been calling them. Via the way things such as databinding work, Microsoft has implied that any bit of data that is a part of the public interface of an object should be a property. I don't think they meant it merely to be a convention like it is in some other languages where property syntax is more about convention and convenience.
A more interesting question may be: "When should I use a public field instead of a property", or "When has a public field instead of a public property saved your bacon?"
Fields which are of structure types allow direct access to the members thereof, while properties of such types do not. Consequently, if Thing.Boz were a field of type Point, code which wants to modify its X value could simply say Thing.Boz.X += 5;; if Thing.Boz were a mutable property, it would be necessary to use var tmp = Thing.Boz; tmp.X += 5; Thing.Boz = tmp;. The ability to write things more cleanly with the exposed field is often, but not always, a blessing.
If it will always be possible for Boz to be a field, modifying its members directly will be cleaner, faster, and better than copying it to a temporary variable, modifying that, and copying it back. If the type of Boz exposes its mutable fields directly (as structures should) rather than wrapping them in trivial wrappers, it will also be possible to use things like Interlocked methods on them--something that's simply impossible with properties. There's really only one disadvantage to using fields in that way: if it's ever necessary to replace the field with a property, code which relied upon the thing being a field will break, and may be hard to fix.
In short, I would posit that in cases where one isn't concerned about being able to swap in different versions of code without having to recompile any consumers, the biggest effect of using properties rather than fields is to prevent consumers of the code from writing code which would take advantage of (and rely upon) the semantics of exposed fields which are of structure types.
Incidentally, an alternative to exposing a field of a structure type would be to expose an ActOnXXX method. For example:
delegate void ActionByRef<T1>(ref T1 p1);
delegate void ActionByRef<T1,T2>(ref T1 p1, ref T2 p2);
delegate void ActionByRef<T1,T2,T3>(ref T1 p1, ref T2 p2, ref T3 p3);
// Method within the type that defines property `Boz`
void ActOnBoz<T1>(ActionByRef<Point, T1> proc, ref T1 p1)
{
proc(ref _Boz, ref p1); // _Boz is the private backing field
}
Code which wanted to add some local variable q to Thing.Boz.X could call Thing.ActOnBoz((ref Point pt, ref int x) => {pt.X += x;}, ref q); and have the action performed directly on Thing._Boz, even though the field is not exposed.

Categories