Best practice for managing / controlling object state with 2 way databinding using Polymer - data-binding

Lets try this explanation again...
I'm new to polymer (and getting back into web dev after a relatively long absence), and I'm wondering what the recommended approach might be to more closely manage object state while employing 2 way databinding. I am currently consuming rest API (json) objects. My question is if polymer keeps a copy of the original object before initiating updates to the bound object's properties/attributes...so one might be able to easily undo the changes? While allowing 2 way databinding to work its magic is often desired, there are cases where I'd like to prevent / delay changes to the object / DOM until the user approves the changes (say via the paper-dialog component for instance). I suppose one could make a temporary copy of the object and bind fields to that version, and then only persist the changes back to the source object upon user approval. In any case, I'd be interested to hear thoughts and see an example or two of recommended approaches (especially if I am off-track with my ideas!)

I suppose one could make a temporary copy of the object and bind
fields to that version, and then only persist the changes back to the
source object upon user approval
This.
Consider that view-models are essentially different from pure data-models (sometimes called business-data). Frequently, the differences are irrelevant and one can use them interchangeably. However, be aware of scenarios where the view-model is distinct (uncommitted user edits are a good example).
The notion of a field editor that requires approval from the user is purely UI/View oriented. Whatever data is managed in that modality is purely in the domain of the view, and fetches/commits to the business-data should be discrete.

Related

How to do updates with GraphQL mutations(Hot Chocolate)

We recently introduced GraphQL to our project, I've never used it before, however I like it a lot.
We decided to go with the HotChocolate library for .NET Core and Apollo for client side.
One thing I am not quite sure is about mutations, specifically peforming updates and partial updates with mutations.
I read somewhere that the practice is and that I should stick with creating specific mutation for each update, for instance updateUsername(), updateAddress(), updateCity() all of them should have specific mutation.
Issue with that is that my codebase will grow enormously if I decide to go in that direction, as we are very much data driven, with a lot of tables and columns per table.
Another question is, how to handle nullable properties, I can create a mutation which accepts some input object, but I'll end up with my entity being overwritten and all nullable properties not provided on the calling end will be set to null.
Is there a way to handle this update partially or I should go with specific update mutation for each property I want updated?
I think you understood the best practice around specific mutations wrong. It's less "have one mutation to update one field" and more "have specific mutations that encapsulate actions in your domain". A concrete example would be creating an "addItemToBasket" mutation, instead of having 3 mutations that update the individual tables related to your shopping basket, etc.
GraphQL is very much centered around front-end development, so your mutations should, in general, closely resemble actions a user can perform in your front-end. E.g. your front-end has an "Add to basket" button and your backend has an "addItemToBasket" mutation that resembles the action of placing an item in the user's basket.
If you design your mutations with this in mind, most of the time you shouldn't be having an issue with partial updates, since the mutation knows exactly what's to do and you are not just letting the user of your schema update fields at will.
If for whatever reason you need to have these partial updates, you likely won't get around implementing the patching yourself, unless your data provider supports it. Meaning you will have to have an input object type with nullable properties and your mutation that decides which fields have been changed and changing them using your data provider.
That being said, there's also a proposal for patching types in the Hot Chocolate repository that should simplify the patching part: https://github.com/ChilliCream/hotchocolate/issues/1326
for instance updateUsername(), updateAddress(), updateCity() all of them should have specific mutation.
Issue with that is that my codebase will grow enormously if I decide
to go in that direction, as we are very much data driven, with a lot
of tables and columns per table.
Correct. That's practically impossible to follow that way for more or less big data-driven applications.
Consider how we implement the patching in our API here. Also consider following the discussion about the patching feature in HotChocolate github thread. Hope, that helps!

Need some clarifications on the Model side of MVC

I guess I would need some really good explanation on some Model related concepts.
In general does the model, as described by frameworks like Robotlegs play the role of an application state holder, or a domain state holder? I originally thought that models are entirely domain based, i.e UserModel, LocationModel, which play the same role that DAO classes play on the server. The more source code I am looking at though, the more I see stuff like UserAccountModel, ShoppingCartModel, etc, full of properties and methods related to the state of the client application, not the domain state.
I see that the people do not bother to add complex relationships to the VO classes, i.e. if a User has a lot of photos, the photos collection is obviously omitted from the UserVO class. Instead, a bunch of PhotoVO objects are loaded from the server whenever necessary, based on a service call with the user ID. Is that some sort of a rule of thumb - in general keeping VOs as "bare" as possible? Doesn't that increase the possible number of calls that must be made to the server to fetch all the data? Moreover, doesn't that fragment the domain model in general? (an entity User class on the server will always have a photos property)
With so many calls to the server, it is normal to fetch some objects that might be already on the client storage. does it make sense to make a client side cache, and check if the object that is going to be fetched is already there, or in general, the overhead of getting it once again will be paid off by the benefits of getting a fully synced object from the server. Otherwise, every object stored on the client side cache must be cared for when a change occurs. I personally think that the overhead of getting an object from the server, which might have already been picked up before is not as big. Better have fresh and synced data I'd say.
I do not believe your question is answerable, because so many of the answers are "it depends." It depends on the application you're building and the needs of the UI.
I don't really understand your distinction between "Domain State" and "Application State." However, I believe that any "Value Object" style classes implemented in the UI should focus on holding the state of specific views. It is extremely rare that a single view is a one to one relationship to database tables. As such, my UI Data Objects may not be identical to server side data objects. Although, it is very common that I will map UI objects to server side objects using AMF. But, it doesn't mean that every object in the UI is implemented server side and every server object is implemented on the UI.
I see that the people do not bother to add complex relationships to
the VO classes,
I'm not sure where you see that; I will often do exactly this. However, it depends what the view is supposed to display. IF the view is not displaying a lot of photos related to the user, then I won't make a remote call to retrieve the user information with all their photos.
With so many calls to the server, it is normal to fetch some objects
that might be already on the client storage.
It depends. I would say that the apps I write, the calls to the server are done as needed; and attempts are made to limit them as appropriate. If I already fetched data and have it cached on the client, then I am going to try to use that cache instead of retrieving the data again.
I'll restate my original assessment: I think the answers to most of your questions depend on the situation, and depend on the app. You seem to start with overally broad generalizations about how things are done. However, I Do not believe they are universal truths. Developer's fight about application architecture issues all the time.

EF4 ASP.NET - Managing Entity Edits between HTTP Posts and Rollback

I am struggling with the following use-case:
User amends an existing order. The order is complex - lots of related 'entities' (addresses, post options, suppliers, makes, models, various items etc). Across multiple http posts.
User wants to discard the changes.
--
I have an order entity and as the user is editing this I am making various changes to the entity associations e.g changing order.address, order.items.add(item)...
In a single post this is fine, but across posts I don't know how best store state. If I store the entities then I cannot save the changes as they are across different data contexts. I have read that it is bad practice to store the data context in the session state i.e. long-lived context. I can't save changes after each edit/post because I cannot roll-back (?). I really would like to work with the entities during the editing process rather than one big save at the end (taking UI settings and applying these in one chunk).
This must be a pretty common problem - it's driving me mad. Any help really appreciated.
Cheers!
We have a similar problem where we are building a complex business object through a multi-page wizard.
Instead of creating a partially complete business object at each step of the wizard, we create a dedicated wizard object that looks pretty similar to the business object, populate that through the wizard. At each step in the wizard, the wizard object is saved into the database. At the end the user can accept it and it is converted to a real business object and then becomes visible to everyone else, or they can bin it and no-one else ever knows it existed.
If this kind of approach was not suitable, I suspect you're looking at some kind of difference tracking, either at the entity or database levels. Neither are simple to implement, work with or manage in a system. The former would be some kind of calculation and storage of n changes to the entities and developing an algorithm to undo them, the latter depends on your RDBMS, but might include versioned rows or similar.
Yes its pretty much common for us. In most scenarios we use the MVC approach. Even without the actual ASP .NET MVC Projects, we use similar ViewModel with our Views/Pages/Scenarios etc. where there is no direct/single entity mapping to the Business Layer (in other words, Business.Entities). This is pretty much similar to DTOs.
It is always easy to use Disconnected EF. We retrieve data and discard the context, then transform the Entities into ViewModels/DTOs if necessary. When you need to persist changes, all you have to do is to create a new context, find the latest entity instance do the changes.
The Views/Pages/Controllers will be managing these ViewModels/DTOs. Tracking Changed and Deleted content can be done by introducing a HistoryList<T> (you can extend a List<T> to implement this).
Once done, using a Controller/Workflow/Component you can observe the ViewModel/DTO and do the necessary changes to your Entities using a new Context to retrieve and persist.
It involves a bit of a coding and I would say its not a perfect solution since it has its own pros and cons.
/KP

Best way to save extra data for user in Drupal 6

I am developing a site that is saving non visible user data upon login (e.g. external ID on another site). We are going to create/save this data as soon as the account is created.
I could see us saving data using
the content profile module (already in use on our side)
the profile module
the data column in the user table
creating our own table
I feel like #1 is probably the most logical place, however creating a node within a module does not seem to be a trivial thing.
#3 feels like a typical way to solve this, but just having a bunch of serialized data in a catchall field does not feel like the best design.
Any suggestions?
IMO, each option has its pro's and con's, and you should be the one to make the final call, given that you are the only one to know what your project is about, what are the critical points of the project, what is the expected typical user pattern, what are the resources available, etc...
If I was totally free to chose, my personal favourites would be option #4, #1 and #5 (wait! #5? Yes: see below!). My guiding principles in making the choice would be:
Keep it clean
Keep it simple
Make it extensible
#1 - The content profile module
This would be a clean solution in that you would make easier for developer to maintain your code, as all the alteration to the user would pass through the same channel, and it would be easier to track down problems or add new functionality.
I do not find it particularly simple as it requires you to interact with the custom API of that module.
As for extensibility that depends from how well the content profile module API is designed. The temptation could be to simply use the tables done by said module for your purpose, bypassing the API's but that exposes you to the possibility that on a critical security update one day in which you are in a hurry the entire system will break down because the schema has changed...
#4 - Creating your own table
This would be a clean solution because you could design your table (and your module to do exactly what you need to), and you could create your own API to be used by other modules. On the other hand you would introduce yet another piece of code altering the registration process, and this might make it more difficult for devs to track problems and expand the system in a consistent way.
This would be very simple to implement code-wise. Also the DB design would benefit though: another thing to consider is that the tables would be very easy to inspect and query. Creating a new handler for views is dead easy in most of the cases: 4 out of 5 you simply use one of the prototype objects shipping with views.
This would be extremely easy to extend, of course. Once you created the module for one field, you could manage as many as you want by mostly copy/pasting the code for one field to another (or to inherit from the same ancestor if you go OOP).
I understand you are already knowledgeable about drupal, but if you need a pointer on how to do that, I gave some direction in this other answer.
#5 - Creating your own table and porting already existing fields there
That would essentailly be #4 minus the drawback of scattering functionality across various modules... Of course if you are already managing 200 fields the other way this is not a viable option, but if you are early into your design, you could consider this.
In my experience nearly every project that requires system integration (meaning: synchronising data for the same user in multiple systems) has custom needs for user registration, and I found this solution the one that suits my need best for two reasons:
I found I reuse a lot of the custom code I wrote from project to project.
It's the most flexible way to integrate data with the other system (in some case I even split data for the user in two custom tables managed by the same module: one that contains custom fields used by drupal only and one that contains the "non visible fields", as you call them. I find this very handy in a lot of scenarios, as it makes very easy to inspect and manipulate the data of the two systems separately.
HTH!
If you're already using the Content Profile module, then I'd really suggest continuing to use it and attach the field to it. You're saving the data when the account is created, and creating a node for the user at the same time isn't that hard. Really.
$node = new stdClass();
$node->title = $user->name; // what I'd use, or you can have node auto title handle the title for you. Up to you!
$node->field_hidden_field[0]['value'] = '$*#$f82hff';
$node->uid = $user->uid;
node_save($node);
Bob's your uncle!
I would go for option 3. Eventually even other modules will store the data in the database against a user. So you could directly save it yourself probably in a more efficient way than those modules.
Of course depending on the size of the data, you can take a call whether to add a new column in the users table or to create a new table for your data with the user's id as the foreign key.

How to get business objects and UI controls to talk to each other

I've got a person object with a name and age property that implements INotifyPropertyChanged. I want to hook this object up to an ASP.NET form so that the 'name' and 'age' properties bind to textboxes in a way that, when changes happen in either place (in the control or in the object) the other will get updated.
Do I create an intermediary class that listens to each textbox change events and the objects change events and handle the updates between them? What's the best way to do this?
I'm unclear on how to get business objects and the UI talking to each other.
I've stressed over this exact problem a lot.
The short answer is, yes, an intermediate item.
The trick is to NOT write ANY code per control. You should be able to place a GUI control on the screen (That may or may not take code), and then bind your business logic to it through a generic binding mechanism.
I have defined the bindings through XML, through properties files, and through constant arrays--there are a million ways...
You probably have to write code per TYPE of object bound (a listbox binds differently than a text control) and you may have to write validators (but specifying the parameters to the validators and which control the validators bind to should also be done in data)
Now all that said, I'd be really surprised if some data-driven auto-binding mechanism didn't already exist, Microsoft has been into that since VB first came out (although their implementations used to be pretty inflexible, I'm sure they do a better job now).
I'm very insistent about the 0 lines of code per control because my job has typically involved configuring complex devices with dozens of pages of controls. A typical client/server system will have 7(!) lines of code PER CONTROL just to transport data from the DB, to the server, to the client, to the screen and back (this is a minimum for plain ole "dumb" code with no smart binding tricks).
0LOC/control may not be a requirement for everyone, but it's a good goal.
Comment response:
I've done most of my stuff manually in Java, so I'm not sure I can be too much help with the specifics.
Searching for C# and binding gave me this which looks promising, although it may be binding straight to a database which is too much IMO, it should bind to a business object, but the concepts should be the same.
One way to create the bindings at first is to manually instantiate binding objects... (Please excuse my Java)
TextControl textCtrl1=new TextControl("Name Goes Here");
new TextBinder(textCtrl1, personObject, nameField);
In Java, that second line gets tricky. When you are binding to a particular field, you HAVE to use reflection to find the setter and getter for that field of the personObject. In C# I think it should be easier.
Anyway, the binder should add itself as a listener to the control and the object, then forward changes back and forth.
Does that help any?
Edit2:
As you noticed, the hard part is noticing when your property is updated. Luckily, that is optional. More often than not, you don't need to update the component once the object is set (I had to deal with this a few times when I had distributed UIs that could update each other).
So, if you assume your object won't change, the "Binding" has to do the following:
get the value from the property and set it in the component.
add itself as a listener to the component.
store the property/object (if you can manipulate properties, you're set here. If not, you need to store the object and property name, and use reflection)
bail and wait for an "updated" event from your component.
When you get the update from your component:
- store the value in the property.
- You may want to set an "Updated" flag or store the original so that if you iterate through all the binding components, you can tell if any updates need to be saved/enable the "ok" button.
Your object should always be pretty much up-to-date now.
As you build a form, you may want to put all your binding controls into a collection so that you can do a few other operations...
A "Save" operation could call each binding control and tell it to copy from the control to the property, that way you don't need to use a listener.
A "Reset" operation can reset all the controls to their original value.
A "Test" operation can ask each control if it's been updated.
. etc
The neat thing about doing it this way is that every "Operation" you wish to add is pretty trivial to add, but automatically affects the entire UI.
You probably also want a little object hierarchy of controls with an abstract base "bind" class, then a specific binder for each type of control (text field, number field, date, spinner, table, pulldown)--I think that's about it.
This can be very simple, but gains complexity rapidly. Try it with a text field and see what you can do. A simple text binding object should just be like 5 lines of code if you can pass "properties" around in C#...
Okay, totally separate answer. As I told you, I'm not very up-to-date with C# technologies, but from what I've heard, LINQ may do this entire job for you.
In fact, LINQ may be made to do exactly what you are trying to do. It doesn't exist in Java, so that's why I gave you the "Manual" version in the other answer.
The comment at the bottom of this page: http://msdn.microsoft.com/en-us/library/z919e8tw.aspx alludes to a better way.

Resources