How to raise Play's max_fetch_depth? - orm

I am getting NullPointerException when accessing member fields only 3 levels deep in my view template:
#tfz.modelTfzTyp.simulierteTfzTyp.typ
If I use getter functions instead, it works. But it is cumbersome.
I am using Ebean and I read that Hibernate has a max_fetch_depth. I am suspecting that something similar is causing my problems. How do I make Play load more objects eagerly?

This has nothing to do with the max_fetch_depth property.
Dynamic fetching is allowed by byte code enhancement on the models, and it works only for the getters.
See the official documentation:
Enhancement of direct Ebean field access (enabling lazy loading) is only applied to Java classes, not to Scala. Thus, direct field access from Scala source files (including standard Play 2 templates) does not invoke lazy loading, often resulting in empty (unpopulated) entity fields. To ensure the fields get populated, either (a) manually create getter/setters and call them instead, or (b) ensure the entity is fully populated before accessing the fields.

Related

Data binding without a ViewModel

I am doing something I have never tried before. I am trying to create dynamic UI and bind it to a dynamic model. In other words, my web service is going to send back a small metadata description of my UI and the raw data to bind to it. Therefore, at build time, I don't know what UI I will be constructing and I don't know what my model will be. Binding them together seems VERY difficult if not impossible.
Mvx allows me to bind UI directly to a model WITHOUT it being an MvxViewModel. However, if I bind directly to the Model returned by the web service, I lose the ability to RaisePropertyChanged() since that only comes from MvxViewModel.
Normally, I would write a ViewModel that wraps the Model and have all the wrapped setters call RaisePropertyChanged(). However, in this case, my model is dynamic so I can't wrap it with a ViewModel at compile time since I don't know what it is until runtime.
Is there some cool trick I can use to construct a ViewModel that can wrap any C# model class and send out property changed events without knowing what properties the model class has until runtime?
I just discovered the DLR and the DynamicObject which seems to be perfect, but due to Apple restrictions, it will not work on Xamarin.iOS.
Without teasing DynamicObject into life on iOS, the main approaches that think of are:
You could change your webservice generation code so that it produces INotifyPropertyChanged - I've used libraries that do this - e.g. http://stacky.codeplex.com/SourceControl/latest#trunk/source/Stacky/Entities/Answer.cs - and if you can't change the webservice code generation itself, you might still be able to wrap or pervert the generated code using some kind of t4 or other templating trick.
You could investigate some kind of code that maps the web service objects to some kind of observable collection (Kiliman has suggested this in comments)
You could look at some kind of valueconverter (or maybe valuecombiner) which does the binding - I can fairly easily imagine a valueconverter which takes a wrapped model object and a string parameter (the property name) and which uses those two together (with some reflection) to work out what to do. I'm not as sure how this one would work with nested model objects... but even that could be possible...
You could look at some kind of custom binding extension for MvvmCross. This isn't as scary as it sounds, but does require some reflection trickery - to understand what might be involved take a look at the FieldBinding plugin - https://github.com/MvvmCross/MvvmCross-Plugins/tree/master/FieldBinding
During the actual data-binding process, the plugin will be called via IMvxSourceBindingFactoryExtension - that would be your opportunity to hook into some other custom change event (rather than INotifyPropertyChanged). It might take a little experimentation to get this right... especially if you have nested objects (which then require "chaining" within the binding)... but I think it should be possible to produce something this way.
I am not sure if what I finalized on supports all possible functionality, but so far, it seems to satisfy everything that I need.
I really liked the idea of writing my own IMvxSourceBindingFactoryExtension. However, in investigating how to do that, I started playing with the functionality that already exists within MvvmCross. I already knew that MvvmCross would honor an ObservableCollection. What I didn't know was that I could use [] in my binding expressions AND that not only would integer indexers work, but also string indexers on a Dictionary. I discovered that MvvmCross sample code already has an implementation of ObservableDictionary within its GIT repo. It turns out, that is all that I needed to solve my problem.
So my model contains static properties AND an ObservableDictionary<string,object> of dynamic properties where the key is the name of the dynamic property and the value is the value of the property.
My ViewModel wraps this model class to send out PropertyChanged notifications on the static properties. Since the Dictionary of dynamic properties is observable, MvvmCross already handles changes to members of that dictionary, including 2-way.
The final issue is how to bind to it in my binding expression. That is where the [] comes in. If my ObservableDictionary property name is called UserValues and it contains a value at key user1, then I can 2-way bind to it by using: UserValues[user1] and everything seems to work perfectly.
One issue I see is that I am now requiring my dynamic data source to return an ObservableDictionary to me instead of just a Dictionary. Is that asking too much?

How to duplicate an entity with all of its properties and collections

The standard Jspresso action cloneEntityCollectionFrontAction allows to duplicate the selected rows in a table.
The duplication is limited to the current model and do not take account of collections if exist (ie : the collections are not automatically duplicated)
how to deeply duplicate an entity with all of its collections ?
Second related question : I tried to write by myself an action in order to realize the duplication of the collections. Below a part of the action I wrote :
Offer newOffer = bc.getEntityFactory().createEntityInstance(Offer.class);
Offer clonedNewOffer = bc.cloneInUnitOfWork(newOffer);
clonedNewOffer.setCustomer(curOf.getCustomer());
clonedNewOffer.setEndApplicationDate(curOf.getEndApplicationDate());
clonedNewOffer.setName(curOf.getName());
clonedNewOffer.setStartApplicationDate(curOf.getStartApplicationDate());
I called the getter and setter for each property which is not satisfying because if I add new property or collection to the model, the method must be manually updated.
Is there a way to write a more smart / flexible method ?
Hi Vincent,
Regarding the answer you made and your latest proposal, I changed my backend with the following one :
Offer newOffer = bc.getEntityFactory().createEntityInstance(Offer.class);
Offer clonedNewOffer = bc.cloneInUnitOfWork(newOffer);
CarbonEntityCloneFactory.carbonCopyComponent(curOf, clonedNewOffer, bc.getEntityFactory());
bc.registerForUpdate(clonedNewOffer);
But the registerForUpdate failed due to Data constraints are not satisfied error.
I checked the Id property of the clonedNewOffer and the Id is already the same than curOf Id property.
I understand the meaning of a "carbon copy" which is a strictly copy of all the properties, so, from a backend,
how could I duplicate an entity in order to create a new one ?
Both CloneComponentCollectionAction and CloneComponentAction perform the actual component and entity cloning using a configurable strategy that implement IEntityCloneFactory. Jspresso provide 3 implementations of this interface :
CarbonEntityCloneFactory that deals with scalar cloneable properties but ignores all relationships. It's almost never used directly by application code.
SmartEntityCloneFactory inherits from CarbonEntityCloneFactory and deals with relationships the following way :
clone the references if they are compositions or assign the same references to the clone.
add the cloned component to the same collections than the original belongs to.
HibernateAwareSmartEntityCloneFactory inherits from SmartEntityCloneFactory and deals with lazy initialized properties. This is the implementation that is used by default if you use an Hibernate backend.
As a rule of thumb, you can expect the SmartEntityCloneFactory to perform what you expect about references but ignore dependent collections in order to avoid too deep recursive cloning; so what you've experienced is per-design. If you feel like there is room for improvement, feel free to open a feature request on the Jspresso GitHub. Thinking about it, we could maybe do better about composition dependent collections.
When you want to deal with deeper cloning than what's provided by the SmartEntityCloneFactory (or HibernateSmartEntityCloneFactory), the way to go is to create your own cloning strategy. Of course, you can inherit the default strategy and complete the cloning by overriding the cloneEntity method by calling the super implementation and deal specifically with the collections you want to clone.
Once your strategy is implemented, just inject it either globally in the application by replacing the default one, i.e. :
bean('smartEntityCloneFactory', class: 'your.CustomEntityCloneFactory',
parent: 'smartEntityCloneFactoryBase')
or specifically on one of the clone actions of your application by injecting your custom strategy on the action, e.g. :
bean('myCustomEntityCloneFactory', class: 'your.CustomEntityCloneFactory',
parent: 'smartEntityCloneFactoryBase')
action('customCloneAction', parent: 'cloneEntityCollectionFrontAction',
custom:[entityCloneFactory_ref: 'myCustomEntityCloneFactory']
)
Regarding your second related question, if you are inside your entity clone factory implementation (or have access to an instance of it) and want to clone an entity or a component using the strategy, just call the cloneComponent or cloneEntity method.
If you just want to copy all the scalar properties of an entity or component on a clone and don't have access to a clone factory, you can use the following static utility method :
CarbonEntityCloneFactory.carbonCopyComponent(IComponent, IComponent, IEntityFactory)
Using the above method will solve your implementation robustness.

Iterate over non null entities in model using linq

How do you iterate over the entities within a model in mvc 4 using entity framework 5.0? Looking for a more elegant process using linq.
Example: AnimalModel may have Cat, Dog, Pig entities. How would I detect just the entities and ignore other properties in the AnimalModel such as isHarry, Name, isWalking, isJumping. Is there a way to do this without using reflection, something within EF5 that allows for just looking at non-null entity values.
The main reason I am interested in this technique is to reduce code bloat and perform generic CRUD operations on the data across all entities and sub entities.
Possible Reference: link
I can't see how you can achieve this without using reflection at all.
You could try the following : Get all the EF types in the assembly which hosts them e.g.
var types = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == "NamespaceWhereEFEntitiesLive"
select t;
You may need to ply around a bit with the above query, but you get the idea.
You can then iterate through the properties of AnimalModel, check whether the property is of any type returned in types. e.g.
foreach(var prop in AnimalModelProperties) {
if (types.Contains(prop.GetType())
}
Note that the above for loop is a bit of a guess, but the pseudo-code should clarify what I'm looking to explain.
When you use EF to insert/update, it automatically ingores all irrelevant properties. If you want an implementation that takes properties from existing objects, then applies them to the database, you could use the relatively new upsert.
If you want a custom way to upsert a graph of objects...
If you are using either database-first or model-first (if you have an EDMX), you could use T4 templates to generate code that does this.
If you want this technique to support navigation properties, you will need some sort of assumption to prevent loops e.g. update from one to many, not the other way around and not many-to-many properties, or use the EDMX's optional description to place a hint on which navigation properties to visit.
Using reflection is a simpler solution, however, although, even with reflection you'll need to decide which way to go (e.g. using attributes (which you can get the T4s to add via the above assumptions/tricks)).
Alternatively, you could convert this technique (that I wrote) to work with EF, thus explicitly specifying where to visit in the graph in the using code, (using dbset.SaveNavigation(graph, listOfPropertyPaths) instead of writing complex code that assumes what you want it to do when you write dbset.Save(graph) (I have successfully done so in the past, but haven't uploaded it yet).
Also see this related article that I have recently found (I haven't tried it yet).
By the way, null properties do have significance in updating the database, often, you won't want to ignore them.

Neo4j - Wrapping/Inheriting a Node object

I'm developing kind of a social network with neo4j, and i wanted to make my Node object a bit more specific for my own needs. Does it considered a good practice to wrap a neo4j Node object or to inherit from it?
My problem with the wrapping approach arises when indexing the nodes objects with the built in Lucene engine. For example, what benefits will i earn if i'll wrap my Node object with a "Profile" class (with methods such as "addFriend", "setFirstName", etc..), but on the other hand, whenever i will run a query against my index i'll get back raw Node objects and not my wrapped objects? I can make some dirty solution for this case, by saving a reference for the wrapped object inside my node properties, but it looks very strange for me to do it.
What would you recommend to do in such case, in order to get a clean and well designed code?
Thanks.
I have found that wrapping a Node does not lead to very maintainable code/design. As you mentioned, one thing you need to take care of is not returning a Node but translating it to your domain object.
If your object has mostly getX methods, then you can just execute Cypher queries, compose your domain object(s) and return those. You don't even need to wrap the Node in this case- all you need is some property that you can use to look up the Node.
If you have setX methods, then you can update the Node via Cypher statements either via a save that updates all properties or on each setX (not great, as you'd be updating too often the setX method now implies persistence). Either of the two approaches does not require the Node to be wrapped.
I tried in earlier projects to wrap the Node but found that it leads to much more trouble and a generally smelly design. Now I work with pure domain POJOS's and keep Neo4j code in the persistence layer only, and this works much better for me. You haven't mentioned which language you're using- if Java, then I believe Spring Data can take care of a lot of boilerplate code.
Put your search code INTO the class they belongs to.
If you need to get, I don't know, something like getFriends from a Post class, you will create the method fromPosts into the Person class, and the getFriends method into Post.
From post, you will call the query from Person class, execute the query and return an Array / List of the nodes mapped into the Person class.
So your getFriends method into the Post class will be something like:
Person.fromPosts(self).results.map { |node| Person.new(node) }
Is simple to do that doing just a map of the result with a Person.new (or new Person, depend from which language are you using) and pass the node to the Person. This means that you must have a new method that populate object from a node.
Spring Data Neo4j is the definitive solution to your need, it maps annotated entity classes to Neo4j with advanced mapping functionality and provides access to nodes and relationships at different levels of abstraction.

Does adding PetaPoco attributes to POCO's have any negative side effects?

Our current application uses a smart object style for working with the database. We are looking at the feasibility of moving to PetaPoco instead. Looking over the features I notice you can add attributes to make it easier to CRUD objects. Does adding these attributes have any negative side effects that I should be aware of?
Has anyone found a reason NOT to use these decorators?
Directly to the use of the POCO object instance itself? None.
At least not that I would be aware of. Jon Skeet should be able to provide more info because he knows compiler inner workings through and through, so he knows exactly what happens with this metadata after it's been compiled.
Other implications indirectly related to these
There are of course implications when accessing these declarative attributes, because they're read using reflection which is normally a slow process.
But there's nothing to worry here, because PetaPoco is a smart library and reads these only once then compiles & caches these things, so you only get penalized once then you get blazing performance afterwards. Because it uses compiled code.
Non-performance related implications
By putting attributes (any) on your classes/properties/methods you somehow bind your code to particular engine that will use this class, because they're directives for this particular engine to understand your code.
In case of PetaPoco attributes this means that your class can be used with PetaPoco but not with some other DAL (ie. EF) unless you add attributes of that one as well (EF Code First uses the very same approach with attributes).
The second implication is related to back-end database. In case you rename a table, column or any other part that is provided in your PetaPoco attribute as a constant magic string, you will subsequently have to change this string as well. This just means that you have to be thorough when doing database changes...
One downside is that it breaks the separation between the "domain" layer and the "data" layer, since it introduces the PetaPoco file (which contains data logic) to domain classes that should really not have any knowledge or dependency on the data layer.
If you're doing a single-project MVC app or something then it's okay to just use the Models directory for both, but for non-trivial and separated apps you'll have to have two PetaPoco files or play around with abstracting portions of the file in order to annotate your models without making them "know too much" about the underlying data, or else have you specify the table and/or primary key name all over the place.