Colliding aspects in postsharp - postsharp

I am using the PostSharp solution for INotifyPropertyChanged by decorating my business classes with the [NotifyPropertyChanged] attribute.
All works fine.
Now I wrote a custom aspect that handles property changes so that I get some custom flags set when some special properties change. This aspects is named [HandlePropertyChanged] and works when used alone.
Now I try to use both aspects in combination. As I read on the PostSharp page I can manually order them to ensure a fixed order by using
[NotifyPropertyChanged(AspectPriority = 0)]
[HandlePropertyChanged(AspectPriority = 1)]
In this case, I can build my solution, but because "NotifyPropertyChanged" runs before "HandlePropertyChanged", the changes on my properties are already done and the custom logic does not run correctly.
If I try this
[HandlePropertyChanged(AspectPriority = 0)]
[NotifyPropertyChanged(AspectPriority = 1)]
my build fails with the error at the bottm of the text (see below).
Best would be to simply do what NotifyPropertyChanged does in my custom aspect and forget about the PostSharp aspect
Is this possible?
0: Error C:\Source\WAVE\WAVE.Data.Contracts\Entities\Base\EntityBase.cs (17,16) PS0115: Conflicting aspects on "TopMotive.WAVE.Data.Contracts.Entities.Base.EntityBase`1": according to aspect dependencies, transformation "Instantiation of aspect PostSharp.Patterns.Model.NotifyPropertyChangedAttribute" should be located both before and after transformation "Instantiates binding collection for field "PostSharp.Patterns.Model.NotifyPropertyChangedAttribute/LocationBindings".".

This bug is fixed in PostSharp 5.0.52 and PostSharp 6.0.16 RC.

Try superior and free alternative: Stepen Cleary's Calculated Properties.
https://github.com/StephenCleary/CalculatedProperties/blob/master/README.md
I used both in production and found it to be far better than PostSharp's aspect.
Also from PostSharp docs:
"If a property getter calls a virtual method from its class or a delegate, or references a property of another object (without using canonical form this.field.Property), PostSharp will generate an error because it cannot resolve such a dependency at build time. The same limitations apply when your property getter contains complex data flows, such as loops, or calls to methods (except property getters) of other classes.
When this happens, you can either refactor your code so that it can be automatically analyzed by PostSharp, or you can take over the responsibility for analyzing the code"
None of those limitations apply to Calculated Properties. It can do loops, virtual methods, LINQ to objects, basically any runtime dependencies that you can imagine doesn't matter how indirect. Dependency graph rewires itself at runtime and just works without any ceremony. They are also fast.

Related

Globally Tag EF Core Queries with ".TagWithCallSite()"

With the release of the .TagWithCallSite() method in EF Core 6.0 I was wondering if there is a way to apply this globally on every query run via a DbContext in some way?
It would be much better to apply this across the whole project without having to put it on each query individually.
TagWithCallSite accepts parameters marked with CallerFilePathAttribute and CallerLineNumberAttribute which are filled in by compiler (or manually if needed) during build so it is impossible to set up globally.
No, you cant't do that.
When you explicitly define TagWithCallSite(), complier automatically fills default parameters filePath and lineNumber. It is not possible to define that for all queries because compiler do not store such information in Expression Tree.

Autofac Interface Ambiguity

"The ambiguity, is in the box" - Monty Python.
Autofac is having a problem resolving an interface. See attached solution.
The Interface, IAmbiguous, is defined in project ACommon. It is implemented in project AInjectable. The AInjectable project does not / cannot reference ACommon. The AInjectable project defines IAmbiguous as an existing item brought in with a file link.
The UI project calls ACommon Inject and attempts to register the AInjectable assembly. IAmbiguous is not ambiguous initially but after a builder.RegisterAssemblyTypes command it becomes "ambiguous in the namespace." There is no error thrown when the container is built but the registration is not there.
Registration can be done "AsImplementedInterfaces" if Named and Keyed is not used. But then there is no way to Resolve the registration because the service IAmbiguous is "ambiguous in the namespace."
This question was double-posted as an issue on Autofac. It is not an Autofac problem. I will copy/paste the answer from the issue in here; for future readers, if you want to see the repro solution, go check out the full issue
What you're doing by including the same interface in two different assemblies isn't something you should be doing. Note that by doing that, your AInjectable class is not implementing the interface from the ACommon project. It's implementing a different but identically named interface.
This sort of thing is a problem - having the same type (interface, class, whatever) name in two different assemblies. We even had a problem (#782) where we had a System.SerializableAttribute in Autofac as a shim for .NET Core. You really just can't do that.
You'll also see the same thing if you try to make a static extension method class that has the same namespace and name as some other static extension method class. Ambiguous references.
Without doing Reflection.Emit style code generation, you won't be able to declare an interface in one assembly ("Assembly A") and implement that interface in a different assembly ("Assembly B") without having Assembly B reference Assembly A. That's just how .NET works. What you're seeing is a manifestation of that when you use Autofac, but it's not caused by Autofac. It's caused by you doing something you shouldn't be doing in .NET.
The fix is to define your interfaces in a separate assembly that everyone implementing the interfaces can reference. (Or you can try to dynamically generate code using Reflection.Emit or Roslyn or something, but that's waaaay harder.)

How to get an OrderedSet of OccurrenceSpecifications from a Lifeline in QVTo?

From the diagram on page 570 of the UML spec I concluded that a Lifeline should have the events property, holding an OrderedSet(OcurrenceSpecification). Unfortunately it is not there, at least in the QVTo implementation that I use.
All I have is the coveredBy property, serving me with an (unordered) Set(InteractionFragment). Since my transformation relies on the correct order of MessageOcurrenceSpecification I somehow need to implement myself what I expected to be implemented by the missing events property.
This is what I have so far:
helper Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {
return self.coveredBy->selectByKind(OccurrenceSpecification)->sortedBy(true);
}
Obviously sortedBy(true) does not get me far, but I don't know any further. Who can help?
All I could find so far were other people struggling with the same issue years ago, but no solution:
https://www.eclipse.org/forums/index.php/m/1049555/
https://www.eclipse.org/forums/index.php/m/1050025/
https://www.eclipse.org/forums/index.php/m/1095764/
Based on the answer by Vincent combined with input from a colleague of mine I came up with the following solution for QVTo:
-- -----------------------------------------------------------------------------
-- Polyfill for the missing Lifeline::events property
query Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {
return self.interaction.fragment
->selectByKind(OccurrenceSpecification)
->select(os: OccurrenceSpecification | os.covered->includes(self))
->asOrderedSet();
}
I don't know if it is possible, using directly coveredBy to get an ordered collection. As coveredBy is unordered, if you access it directly by the feature, you will have an unpredictible order and if you try to access it using the eGet(...) stuff, the same result will occur.
However, if I understood correctly, there is a "trick" that could work.
It relies on the assumption that each OccurrenceSpecification instance you need is held by the same Interaction that contains the Lifeline and uses the way EMF stores contained elements. Actually, each contained element is always kind of 'ordered' relatively to its parent (and for each collection so EMF can find elements back when XMI references are expressed using the element position in collections). So, the idea would be to access all the elements contained by the Interaction that owns the lifeline and filter the ones that are contained in coveredBy.
Expression with Acceleo
This is easy to write in MTL/Acceleo. In know you don't use it, but it illustrates what the expression does:
# In Acceleo:
# 'self' is the lifeline instance
self.interaction.eAllContents(OccurrenceSpecification)->select(e | self.coveredBy->includes(e))->asOrderedSet()
with self.interaction we retrieve the Interaction, then we get all the contained elements with eAllContents(...) and we filter the ones that are in the self.coveredBy collection.
But it is way less intuitive in QVT as eAllContents(...) does not exist. Instead you have to gain access to eContents() which is defined on EObject and returns an EList which is transtyped to a Sequence (in QVT,eAllContents() returns a ETreeIterator which is not transtyped by the QVT engine).
So, how to gain access to eContents() in the helper? There is two solutions:
Solution 1: Using the emf.tools library
The emf.tools library give you the ability to use asEObject() which casts your object in a pure EObject and give you more methods to access to (as eClass() for example...etc).
import emf.tools; -- we import the EMF tools library
modeltype UML ...; -- all your metamodel imports and stuffs
...
helper Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {
return self.interaction.asEObject().eContents()[OccurrenceSpecification]->select(e | self.coveredBy->includes(e))->asOrderedSet();
}
Solution 2: Using oclAstype(...)
If for some reason emf.tools cannot be accessed, you can still cast to an EObject using oclAsType(...).
modeltype UML ...; -- all your metamodel imports and stuffs
modeltype ECORE "strict" uses ecore('http://www.eclipse.org/emf/2002/Ecore'); -- you also register the Ecore metamodel
...
helper Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {
return self.interaction.oclAsType(EObject).eContents()[OccurrenceSpecification]->select(e | self.coveredBy->includes(e))->asOrderedSet();
}
Limitation
Ok, let's be honest here, this solution seems to work on the quick tests I performed, but I'm not a 100% sure that you will have all the elements you want as this code relies on the strong assumption that every OccurrenceSpecification you need are in the same Interaction as the Liteline instance. If you are sure that all the coveredBy elements you need are in the Interaction (I think they should be), then, that's not the sexiest solution, but it should do the work.
EDIT>
The solution proposed by hielsnoppe is more eleguant than the one I presented here and should be prefered.
You are correct. The Lifeline::events property is clearly shown on the diagram and appears in derived models such as UML.merged.uml.
Unfortunately Eclipse QVTo uses the Ecore projection of the UML metamodel to UML.ecore where unnavigable opposites are pruned. (A recent UML2Ecore enhancement allows the name to be persisted as an EAnnotation.) However once the true property name "events" has been pruned the implicit property name "OccurrenceSpecification" should work.
All associations are navigable in both directions in OCL, so this loss is a bug. (The new Pivot-based Eclipse OCL goes back to the primary UML model in order to avoid UML2Ecore losses. Once Eclipse QVTo migrates to the Pivot OCL you should see the behavior you expected.)

xtext check annotation issue

I'm using the #Check annotation in order to validate my dsl. my dsl is for json.
at first the method was invoked for a specific object and once per change
but it suddenly doesn't work in the same way anymore (and i'm not sure what i've done that effected it)
the method signature is:
#Check
public void validateJson(ObjectValue object) {...}
now its entering this method for each node in the gui although i'm editing only one node
The validator works normally in this case. When Xtext re-parses your model, it cannot always avoid re-creating the EMF model that is validated in the Check expression - in other words, the model is practically re-created every time, thus warranting a full validation.
However, in some cases, it is possible that only a partial re-creation of the model is necessary - in these cases it is possible that not all elements are re-validated (however, I am not sure whether this optimization was included).

MEF: Importing on Fields

Is it recommended that we place an Import on a property instead of a field? I tried it on a field and it is working but Resharper is telling me a warning that the field was never initialized.
ReSharper doesn't recognize that MEF will be setting the variable and since there is no guarntee that MEF will be setting the variable (example if it isn't put into a container for example), so it is reasonable for ReSharper to warn about this. You can either ignore it or simply initialize the field to null (or default(T)).
As for whether or not you should use a property or field I think using a field is fine (assuming it is not public). I generally reserve properties for things I want to expose publicly. One special case to consider here is that there are some issues having Imports on private members in low trust scenarios like SL or paritial trust because MEF uses reflection and you cannot use private reflection in some of those scenarios.