Saving multiple nested objects with a single request on parse.com - parse-platform

I have two Classes, and Email class and and EmailAssignment class. The Email class saves an email address and a createdBy pointer to a user. The EmailAssignment class holds a pointer to an Email instance and a pointer to a Project instance.
What I'd like to do is batch save all of my email classes and email assignment classes in one request. Is this possible?
For example, when I query EmailAssignment classes I can includeKey["email"] to retrieve the nested pointer object as well. I'm looking for the inverse of this for saving objects.
Can it be done? I'm working with ios client, but I doubt that matters.

PFObject.saveAll() saves an array of objects. Maybe more to the point: when saving any object, parse will save any dirty (new or changed) objects pointed to by the object being saved.
Because of that, you may be able to limit your saveAll to a smaller set, to just the "from" side of the relations.

Related

Model derivative fetch properties for object id(s)

We have some big models where we need to read properties via the model derivative api. Reading all properties leads to an out of memory of the heap. We need to check the properties of each object for a custom prop set in a cad program like revit or navisworks.
So we are exploring to fetch properties for an object, explained here:
https://forge.autodesk.com/blog/new-objectid-query-parameter-model-derivative-properties-api
But after reading the metadata for the guid, we have like 50k of objectids or more. Thats too much to fetch the properties separately per object.
Is there a possibility to:
- fetch properties for multiple object id's?
- Fetch the properties for an object id and all his children?
Or is there another recommendation on how to handle such big models where the response when reading all the properties is too big (and we don't know up front which objectIds to read properties from)?
kind regards
I completely understood your question and as I know you working with .nwm format which is basically includes all the files from project (this is the reason for such amount objects in metadata)
For such case you can use middle-ware server with custom helpers methods, please take a look on this repo from Cyrille Fauvel,
https://github.com/cyrillef/propertyServer
It can help you working with multiple id, with range of id's, some methods you can take as base for your own.
Also, as far as I understood you getting property programatically so maybe you can some how use 'name' field in metadata object which is also can be unique as 'guid'.

'Existing Entity' constraint

I'm reading some data from an excel file, and hydrating it into an object of class A. Now I have to make sure that one of the fields of the data corresponds to the Id of a specific Entity. i.e:
class A{
protected $entityId;
}
I have to make sure that $entityId is an existing id of a specific entity (let's call it Foo). Now this can be achieved using the choice constraint, by supplying the choices option as all of the existing ids of Foo. However this will obviously cause a performance overhead. Is there a standard/better way to do this?
I'm a bit confused about what you are doing, since you seem to talk about Excel parsing, but at the same time you mention choices, which in my opinion relate to Forms.
IMO you should handle directly the relationship to your entity, instead of only its id. Most of the time it is always better to have directly the related entity as attribute of your class A than only the id, and Symfony manipulates such behaviours pretty well.
Then just have your Excel parser do something like this:
$relatedEntity = $this->relatedEntityRepository->find($entityId);
if (!$relatedEntity) {
throw new \Exception();
}
$entity->setRelatedEntity($relatedEntity);
After doing this, since you were talking about Forms, you can then use an EntityType field which will automatically perform the request in database. Use query_builder if you need to filter the results.

instantiating a domain object from form input

In DDD, your domain object's properties are mostly readonly from the outside. Now, in MVC, you'll typically get the object provided to you from the view or repository, but how do you go about this in Webforms, where you read the form inputs manually and apply them to the domain object? Do you create a DTO and give the domain object a Create method that takes the DTO?
The common pattern for recording an action or activity in a domain model, is to model the action as an object associated with the thing, people and places it interacts with.
So by example, if one had Orders associated with a Product, one would typically create the Order via an Order method on the applicable product. Data representing the Order captured via the UI would be passed to that Order method.
This represents the simple case for illustration purposes.
Do you create a DTO and give the domain object a Create method that takes the DTO?
No, you will typically have a piece in the middle, a message handler which is responsible for taking the DTO and converting it to values recognized by the domain. The domain objects have command methods that are used to update the state of the model.
So something like
Receive the DTO
Lookup the appropriate handler for that DTO
Parse the DTO, creating the value types recognized by the domain
Load the target aggregate from the repository
Invoke the command on the target, passing domain value types as arguments.
"Input validation" typically happens in step 3. "Business validation" typically happens on step 5.
A good approach is to make your domain entities always valid, always consistent. How you make them consistent right from creation is simply through the entity's constructor or a Factory that will check that the provided input is good enough to construct a valid entity.
Do you create a DTO and give the domain object a Create method that
takes the DTO?
The Domain layer doesn't have a dependency to other layers, so you can't reference an external DTO there. Entity constructors and Factories typically take primitive values or value objects (sometimes other entities) as an input, not DTO's.

Parameter validation vs property validation

Most (almost all?) validation frameworks are based on reading object's property value and checking if it obeys validation rules.
Do we really need it?
If we pass valid parameters into object's constructor, property setters and other methods, object seems to be perfectly valid, and property value checks are not needed!
Isn't it better to validate parameters instead of properties?
What validation frameworks can be used to validate parameters before passing them into an object?
Update
I'm considering situation where client invokes service method and passes some data. Service method must check data, create / load domain objects, do business logic and persist changes.
It seems that most of the time data is passed by means of data transfer objects. And property validation is used because DTO can be validated only after it has been created by network infrastructure.
This question can spread out into wider topic. First, let's see what Martin Fowler has said:
One copy of data lies in the database itself. This copy is the lasting
record of the data, so I call it the record state.
A further copy lies inside in-memory Record Sets within the application. This data
was only relevant for one particular session between the application
and the database, so I call it session state.
The final copy lies
inside the GUI components themselves. This, strictly, is the data they
see on the screen, hence I call it the screen state.
Now I assume you are talking about validation at session state, whether it is better to validate the object property or validate the parameter. It depends. First, it depends on whether you use Anemic or Rich Domain Model. If you use anemic domain model, it will clear that the validation logic will reside at other class.
Second, it depends on what type of object do you build. An Framework / operation /utility object need to have validation against object property. e.g: C#'s FileStream object, in which the stream class need to have valid property of either file path, memory pointer, file access mode, etc. You wouldn't want every developer that use the utility to validate the input beforehand or it will crash in one operation, and giving wrong error message instead of fail fast.
Third, you need to consider that "parameter can come in many sources / forms", while "class / object property only has 1 definition". You need to place the parameter validation at every input source, while object property validation only need to be defined once. But you also need to understand the object's state. An object can be valid in some state (draft mode) and not in other state (submission mode).
Of course you can also add validation into other state level as well, such as database (record state) or UI (screen state), but it also have different pros/cons.
What validation frameworks can be used to validate parameters before passing them into an object?
C#'s ASP.Net MVC can do one kind of parameter validation (for data type) before constructing into an object, at controller level.
Conclusion
It depends entirely on what architecture and kind of object you want to make.
In my experience such validations were done when dealing with complex validation rules and Parameter object. Since we need to keep the Separation of concerns - the validation logic is not in the object itself. That's why - yes we
we really need it
What is more interesting - why construct expensive objects and later validate them.

Entity Framework in detached mode with MVC application

I have started working out with Entity Framework (EF) for an MVC n-tier application. It would seem that very obvious that this being a web application (which is stateless), I would have to use detached object models. There is no ambiguity with doing an Add operation. However when doing an edit there are here are two ways
Fetch the original object in context, attach the updated object and
then save to database. Something like mentioned in answer to this
question
EF4 Context.ApplyCurrentValues does not update current values
Set individual modified properties explicitly using the IsModified property of individual fields of the object like
mentioned in this article
http://msdn.microsoft.com/en-us/data/jj592677.aspx
Method 1 has disadvantage of having to load object into memory from database each time an update needs to be performed.
Method 2 would require having to manually pass which fields to be set as IsModified to true from wherever the object an be updated. So for e.g. for each object, I may need to create a boolean collection object for each field of the object.
e.g.
SaveEntity(EntityClass e, EntityStateClass ec)
{
context.Entry(e).Property("Name").IsModified = ec.NameState;
context.SaveChanges();
}
class EntityStateClass{ public bool NameState;}
I would prefer method 2 simply for the sake of performance but I am hindered by the n-tier architecture and repository pattern I am using. My Repository interface restricts save method for any object to be
SaveEntity(EntityClass e);
So I cannot pass the "state" object. Context class is not available and should not be available outside DAL. So I cannot set property outside. Is there any "proper" way to achieve this ?
Note: Self-Tracking Entity is also out of question since I cannot send entities with state to client (the browser) since I am intent on keeping the html lightweight.
EDIT: After a lot of thinking, I am trying to use following mechanism to keep track of modified state for each field in my domain class
Declare a partial class for entity class.
For each field that is updateable, declare a boolean property like "IsModified_FieldName"
Set the "IsModified_FieldName" property when the field is set.
However for this I need Entity Framework to generate explicit properties for me instead of implicit properties that it auto-generates. Does EF provide an handle to do this ?
Here is sample code of what I am trying to achieve
//Save Method for class EntityClass.
SaveEntity(EntityClass e)
{
context.Entry(e).Property("Name").IsModified = e.IsModified_Name;
context.SaveChanges();
}
//EntityClass is class autogenerated by EF
public partial class EntityClass
{
//This is auto-generated property by EF
public string Name {get; set;}
/* This is what I would like EF to do
private string name;
public string Name
{
get {return Name;}
set {
name = value;
//this is what I would like to do
this.IsModified_Name = true;
};
}
*/
}
//This is another partial definition for EntityClass that I will provide
public partial class EntityClass
{
//This property will be set to true if "Name" is set
public bool IsModified_Name {get; set;}
}
PS: It seems the information I have provided is not sufficient and therefore there are no responses.
I am using DbContext (Database first model)
EF auto-generates the class files for me. So each time I update my database, the class files are regenerated.
To your concrete question: The entities are generated by a T4 template and it should be possible to modify this template (which is in text format) to generate the entities in a way you want to shape them.
But I have a few remarks about your concept:
In a web application data are usually changed by a user in a browser. To have a definite knowledge what really has been changed you need to track the changes in the browser (probably by some Javascript that sets flags in the data (a ViewModel for example) when a user edits a text box for instance).
If you don't track the changes in the browser what happens? The data get posted back to the server and you don't know at the server side (with MVC in a controller) which property has been changed. So, your only chance is to map all properties that has been posted back to your EntityClass and every property will be marked as Modified, no matter if the user really did a change or not. When you later call SaveChanges EF will write an UPDATE statement that involves all those properties and you have an unnecessary overhead that you you want to avoid.
So, what did you win by setting individual properties instead of setting the whole entity's state to Modified? In both cases you have marked all properties as Modified. Exceptions are partial changes of an entity, for example: You have a Customer entity that has a Name and City property and a view that only allows to edit the Name but not the City and a corresponding ViewModel that only contains a Name property. In this case your procedure would only mark the Name property of the Customer entity as Modified but not the City. You might save here a little bit because you don't save the City property value to the database. But you still save the Name even if it didn't change.
If you use solution 1 (ApplyCurrentValues) you have to load the entity first from the database, yes, but it would only mark the properties as Modified that really changed compared to their values in the database. If the user didn't change anything no UPDATE would be written at all.
Keep in mind that you are only at the beginning to implement your concept. There are other changes to the data that can happen in the browser than only scalar property changes, namely relationship changes. For example a user changes the relationship from an Order to a Customer or you have a view that has an Order and a collection of OrderItems and the user cannot only edit the Order header but also edit the OrderItems and remove and add new OrderItems. How do you want to recognize when the data come back from the browser to the server which collection item has been added and which has been removed - unless you track all those changes in the browser and send tracking information back to the server in addition to the actual data or unless you reload the Order and OrderItems from the database and merge the changes into the original entities from the database?
Personally I would vote for option 1 for these reasons:
You can use real POCOs that don't carry additional tracking information. (BTW: I have some doubt if you aren't reinventing the wheel by implementing your own tracking that EF change tracking proxies provide out of the box.)
You don't need to track changes in the browser which can become quite complex and will require Javascript in every Edit view to write change flags into hidden form fields or something.
You can use standard features of EF without having to implement your own tracking.
You are required to load entities from the database when you want to update an entity, that's true. But is this the real performance bottleneck in a web application where data have to run through the wire back and forth (and reflection (which isn't really known as to be fast) is involved by the model binder)? I have nothing said if your database is remote from the web server and connected by a 9600 baud modem. But otherwise, your plan is not only premature optimization, it is kind of premature architecture. You are starting to build a potentially complex architecture based on "it could be slow" to solve a performance problem that you actually don't know of whether it really exists.

Resources