How to access certain EStructuralFeatures of an EMF Model? - attributes

I know that there are ways to access an EAttribute of an Eclipse EMF model by its featureID or by its name via different indirect approaches. For that I found the following: Eclipse EMF: How to get access EAttribute by name?
But what if I don't know the name of the attribute I want to get? Let's say, based on the design, the model has some fixed attributes by the developer, along with the features that can be set dynamically by the user.
So, for the time being I use the getEAllStructuralFeatures() and use indexes via get() to reach to the by-the-user-created attributes, since I know that the list I get will have the fixed attributes of the model as its first elements beginning with the index 0. But I find this solution unclear and inefficient. Also in some cases, that I want to work, not suitable.
E.g: IEMFEditProperty prop = EMFEditProperties.list(editingDomain, EMFMODELPackage.Literals.EMFMODEL.getEAllStructuralFeatures().get(X));
Do you know a solution or a workaround for this problem? As far as I can see, there are no direct methods to get such dynamically created features of the model.
Every help will be appreciated.

I have been working on a similar case recently where I first tried to define an EStructuralFeature to access exactly the setting/attribute of the object that I needed.
But if you look at how things work internally in ECore, you will find out, that there is no way this will ever work, since the indices are bound to the object identity of the EStructuralFeature objects created at runtime for the specific context (i.e. EClass instance).
My approach was then to either inspect the features proposed by EClass.getEAllStructuralFeatures or to iterate over the features and inspect the object returned by EObject.eGet for this very feature (where EClass eClass = eObject.eClass()).
Example: In a UML profile I have defined a UML Stereotype called "Bean" with a property called FactoryEntity. The property shall reference a UML Class with the Stereotype "Entity" that is closest to this very bean and for which a static factory method will be generated.
In the model I would then have one UML Class typed as Bean and one as Entity.
And for the Class typed as "Bean" I would then set a value for the attribute/property factoryEntity defined in the profile.
The question was then how the property value would be accessible in ECore. I ended up iterating the List of available EStructuralFeature of the EClass of the EObject and checking the type of the object returned by eGet.
final EObject eObject = (EObject) holdingClass.getValue(stereotype, stereoTypePropertyName);
final EList<EStructuralFeature> allEStructFeats = eObject.eClass().getEAllStructuralFeatures();
for(EStructuralFeature esf : allEStructFeats)
{
final Object o = eobject.eGet(esf);
if(o instanceof org.eclipse.uml2.uml.Class)
{
return (org.eclipse.uml2.uml.Class) o;
}
}
Maybe that is not the most elegant way to access structural features but it is the only one I thought was robust enough to last.
Please let me know if you have any suggestions on how to improve this.

Related

How to specify the return type of a method that returns a list of values in StarUML?

I have two classes (say Database and Record). In Database class, I have a method named getRecords() that returns a list of Record objects.
In Java, the above method can be written as:
List<Record> getRecords(){..}
In StarUML, while designing Class diagram, I tried giving
+getRecords() : Record[0..*]
But StarUML refused to create method like above. When I tried with the one below, it works
+getRecords() : ArrayList<Record>
But this is more specific to Java. I want to implement something like Record[0..*] in StarUML. Is it possible to write methods in such format or the Java style of return type is the only solution ?
I don't know why StarUML refuses to parse the text, but you can still create it via model.
Add the operation and call it getRecords()
Right-click on the operation (in diagram or model), and select Add > Parameter
Select parameter in Model Explorer (probably the parameter is already selected when you created it) and set the direction parameter to return. This is how UML represents return types.
(Configure the type, multiplicity, and anything else you need.)
Note that the default collection in UML is Set, so you should check isOrdered, as List is an ordered collection.

Retrieving a value object without Aggreteroot

I'm developing an application with Domain Drive Design approach. in a special case I have to retrieve the list of value objects of an aggregate and present them. to do that I've created a read only repository like this:
public interface IBlogTagReadOnlyRepository : IReadOnlyRepository<BlogTag, string>
{
IEnumerable<BlogTag> GetAllBlogTagsQuery(string tagName);
}
BlogTag is a value object in Blog aggregate, now it works fine but when I think about this way of handling and the future of the project, my concerns grow! it's not a good idea to create a separate read only repository for every value object included in those cases, is it?
anybody knows a better solution?
You should not keep value objects in their own repository since only aggregate roots belong there. Instead you should review your domain model carefully.
If you need to keep track of value objects spanning multiple aggregates, then maybe they belong to another aggregate (e.g. a tag cloud) that could even serve as sort of a factory for the tags.
This doesn't mean you don't need a BlogTag value object in your Blog aggregate. A value object in one aggregate could be an entity in another or even an aggregate root by itself.
Maybe you should take a look at this question. It addresses a similar problem.
I think you just need a query service as this method serves the user interface, it's just for presentation (reporting), do something like..
public IEnumerable<BlogTagViewModel> GetDistinctListOfBlogTagsForPublishedPosts()
{
var tags = new List<BlogTagViewModel>();
// Go to database and run query
// transform to collection of BlogTagViewModel
return tags;
}
This code would be at the application layer level not the domain layer.
And notice the language I use in the method name, it makes it a bit more explicit and tells people using the query exactly what the method does (if this is your intent - I am guessing a little, but hopefully you get what I mean).
Cheers
Scott

System.ComponentModel.BindingList: Add(object) vs. AddNew()

What is the difference between the System.ComponentModel.BindingList methods Add(object) and AddNew()? The MSDN documentation says this:
Add: Adds an object to the end of the Collection<T>.
AddNew: Adds a new item to the collection.
It seems like both methods add an item to the collection, but Add(object) does it in one shot whereas AddNew() is slightly more complicated. My tests with Add(object) seem to be working, but I want to know if I am using the correct method.
So what is the difference between these methods?
AddNew() creates the object for you (that's why it doesn't have a parameter).
It's designed to be used by grids, which don't know how to create a new object to pass to Add().
AddNew() is very handy (it’s the well-known Factory design pattern) when you implement a class derived of BindingList().
It allows your code to initialize new items with values that depend on the list itself - e.g. a foreign key to the parent object if the binding list contains a list of children.

Preventing StackOverflowException while serializing Entity Framework object graph into Json

I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Can we get declared properties of a Groovy class by its order?

I created a plain Groovy class (i.e Person class)with some properties. Now I want to get those declared attributes (which I've defined in my class) with their order, but I don't know how to do it.
I've tried to use Person.metaClass.getProperties() but it retrieves not only declared properties but also built-in Groovy ones.
Could you please help me on this: just get declared properties by its order when declaring.
Thank you so much!
I can't see a use case, but the compiler could reorder all fields declaration while creating bytecode. I'm pretty sure ordering is not a constraint on fields though it should mostly be the case for not modified/enhanced class
As per the JVM spec, generated fields should be marked SYNTHETIC (like generated methods) in the bytecode, so you can test with :
Person.getDeclaredFields().grep { !it.synthetic }
and filter the base Groovy fields like ClassInfo,metaClass and others beginning by __timestamp
But I'm not a specialist, there could be another way I don't think of
There was a question about this on the mailing list back in February of this year
The answer is, no. There is no way to get properties in the order they are declared in the class without doing some extra work.
You could parse the source file for the class, and generate an ordered list of property names from that
You could write a custom annotation, and annotate the fields with this annotation ie: #Order(1) String prop
You could make all of the classes where this matters implement an interface which forces them to have a method that returns the names of the properties in order.
Other than that, you probably want to have a re-think :-(

Resources