How should I design a multiscreen feature? - meteor

I work on a webapp with a workspace, where the user can create, load, and edit documents. This workspace is built with several areas, each taking care of a part of the job. A set of document loaded in a workspace is called a "project" and is stored in a "project" collection.
The data involved in a project is of two types:
the set of documents attached to the project. It is stored in the mongo document in the "project" collection
the current document a specific user is working on. I do not store it yet, I just use a set of global reactive variables to load a document and the attached informations when a user click on it. It means every time a user access to the workspace/project, he will not find the previously loaded documents but no documents loaded at all.
I now want to store the second type of data with one major requirement: to allow the user to work in an "extended mode" where one of the panels is in a dedicated browser window (supposedly on another screen). It means that if he clicks on a document in a window, the document is loaded in the other window/screen.
As far as I know, I can't send information directly from one browser window to another. I have to use the server to relay the information. So the user clicks on a document > the new loaded document id is sent to the server > the other window update accordingly.
Is my assumption correct? (the server must relay the info)
To implement this feature, I figured out a couple of solutions:
I attach a "project" field to the user profile mongo document. In each of these fields, I will have the last items loaded for each project and I will use this field to update one screen from the other.
I create a specific field in each project document where, for each user who worked on the project, I store the currently loaded document and its settings.
The first option suppose to load every project information along with the user profile (i.e. in every page) and could lead to send many times useless informations.
The second option will trigger the meteor reactivity mechanisms each time a user loads an item (without actually modifying the project) for every user connected to the project.
Each option has serious downsides, and I would like to know which one seems to be the better to you and if you can think of other alternatives.

You ought to be able to use one of the reactive local storage packages for Meteor especially if you are not concerned about not supporting non-HTML5 browsers... Can't give a massive amount of guidance on what one having not used most of them but the HTML5 local storage is usable across tabs and seems like a good place to store your data without a round trip to the server whilst also allowing it to persist between tabs.
You could also roll your own implementation (may be simpler than trying to find a package to match your needs exactly) by adding a listener to the app for local storage setitem() and removeItem() events as per this helpful guide from which the below code has been shamelessly copied...
if (window.addEventListener) {
// Normal browsers
window.addEventListener("storage", handler, false);
} else {
// for IE (why make your life more difficult)
window.attachEvent("onstorage", handler);
};
function handler(e) {
console.log('Successfully communicate with other tab');
console.log('Received data: ' + localStorage.getItem('data'));
//Add in your code to display the document on the second tab
}
localStorage.setItem('data', 'hello world');

Related

Storing Temp. Data in ASP.NET Core (NopCommerce)

Dear StackOverflow community,
For a project of mine I need to store (Temporary) data somewhere else than a Database. Actually its a little more complicated. I have a checkout page in NopCommerce where users can select them delivery moment or even location for example pickup. This data has to be store temporary untill the user made the payment. Only then I will request the data and store in DB. So that later I can retrieve the data and display in my dashboard, So that I know when the package is scheduled to be shipped.
Requirements:
Endurement: 12-24 Hours.
Store as user specific data.
Data has to be safed for quite a few sessions. Depends on the user. For example. If the user chooses a delivery moment but desides to look somewhere else before paying. This data has to be stored all those sessions.
If possible serverside.
I have quite a few options following Microsoft:
Session and state management in ASP.NET Core
Now I have tried storing data in Memory (Caching data) using 'MemoryCacheEntryOptions'. The problem is that its application wide. And its hard to maintain with hundreds of users.
Other option is 'Session state'.
The problem is that this data only endures a single session. I need to hold the data for atleast 12 to 24 hours.
Then we have 'Temp Data'. This seems like a promising option. Its great since it is kept until the is has been used/read. You even have 'Peek' and 'Keep' Methods to keep the data while peeking. Problem: It requires a controller. And requesting the data is a callback Method that doesnt require a Controller.
'Query Strings' Well its not much is it? This may be not user critical data BUT seems like query string isnt what Im looking for.
'Hidden Fields' Not really suitable either. It is therefore not form data.
'HttpContext.Items' Definetly not suitable. Data is only stored for single request.
'Cache' Way to hard to maintain user specific data.
So my question is. How do I save all this data temporary, if possible server side for a day atleast with hundreds of users at the same moment. And request the data later in a callback, to store it in DB until the order is shipped.
NopCommerce exposes a class called GenericAttributeService in Nop.Services.Common. This allows you to store your custom attribute data, specific to each customer.
To use it, first inject the GenericAttributeService into your class (controller, service class, etc).
private readonly IGenericAttributeService _genericAttributeService;
public MyFancyController(IGenericAttributeService genericAttributeService)
{
_genericAttributeService = genericAttributeService;
}
To save the data for current customer, use SaveAttribute and save an key-value pair you need:
_genericAttributeService.SaveAttribute<string>(_workContext.CurrentCustomer, "MyKeyName", "Value to save for this customer")
_genericAttributeService.SaveAttribute<int>(_workContext.CurrentCustomer, "My2ndKeyName", model.id)
To get the data use GetAttributesForEntity, where the entity is your key value.
var attribute = _genericAttributeService.GetAttributesForEntity(_workContext.CurrentCustomer.Id, "Customer").Where(x => x.Key == "MyKeyName").FirstOrDefault();
To delete the attribute use DeleteAttribute:
_genericAttributeService.DeleteAttribute(attribute);
Notice that we used _workContext which helps expose the current customer.
This already works well with other temp functionality already existing in the application, such as managing shopping carts, wish lists, etc, so browsing the source code for other examples can also be helpful.

How do you manage adding new attributes on existing objects when using firebase?

I have an app using React + Redux and coupled with Firebase for the backend.
Often times, I will want to add some new attributes to existing objects.
When doing so, existing objects won't get the attribute until they're modified with the new version of the app that handles those new attributes.
For example, let's say I have a /categories/ node, in there I've got objects such as this :
{
name: "Medical"
}
Now let's say I want to add an icon field with a default of "
Is it possible to update all categories at once so that field always exists with the default value?
Or do you handle this in the client code?
Right now I'm always testing the values to see if they're here or not, but it doesn't seem like a very good way to go about it. I'd like to have one place to define defaults.
It seems like having classes for each object type would be interesting but I'm not sure how to go about this in Redux.
Do you just use the reducer to turn all categories into class instances when you fetch them for example? I'm worried this would be heavy performance wise.
Any write operation to the Firebase Database requires that you know the exact path to the node that you're writing.
There is no built-in operation to bulk update nodes with a path that is only partially known.
You can either keep your client-side code robust enough to handle the missing properties, or you can indeed run a migration script to add the new property to each relevant node. But since that script will have to know the exact path of each node to write, it will likely first have to read/query the database to determine those paths. Depending on the number of items to update, it could possibly use multi-location updates after that to update multiple nodes in one call. E.g.
firebase.database().ref("categories").update({
"idOfMedicalCategory/icon": "newIconForMedical",
"idOfCommercialCategory/icon": "newIconForCommercial"
"idOfTechCategory/icon": "newIconForTech"
})

How can I make changes on my Collections locally (minimongo)?

What to do when I want to make changes on my data Collection but I do not want to persist it? In other words, I want to make changes on minimongo, locally, but I do not want to spread it to world.
Use _collection.
MyCollection = new Meteor.Collection('my-collection');
// Subscribe as you see fit
Meteor.subscribe('my-publication');
// Now, to make updates locally you can access the documents in the collection without
// making any calls to the sever.
MyCollection._collection.insert({key:value});
MyCollection._collection.update({key:value}, {key:value});
Works with the usual mini-mongo operations.
This is undocumented and might change in future releases of Meteor without notice.
According to the docs, we can create a Collection and set its name as null. It will create an unmanaged (unsynchronized) local collection.
Unfortunately, it seems to not be possible to make local changes in synchronized collections.
You can create what I call a "local mirror" of a shared collection. Here's a gist with baisc functionality: https://gist.github.com/belisarius222/4715531
The idea is that you wire up a new local collection (new Meteor.Collection(null)) so that any change in the shared collection gets applied to the local collection too.

Flex-Cairngorm/Hibernate - Is EAGER fetching strategy pointless?

I will try to be as concise as possible. I'm using Flex/Hibernate technologies for my app. I also use Cairngorm micro-architecture for Flex. Because i'm beginner, i have probably misunderstand something about Caringorm's ModelLocator purpose. I have following problem...
Suppose that we have next data model:
USER ----------------> TOPIC -------------> COMMENT
1 M 1 M
User can start many topics, topics can have many comments etc. It is pretty simple model, just for example. In hibernate, i use EAGER fetching strategy for unidirectional USER->TOPIC and TOPIC->COMMENT relations(here is no question about best practices etc, this is just example of problem).
My ModelLocator looks like this:
...
public class ModelLocator ....
{
//private instance, private constructor, getInstance() etc...
...
//app state
public var users:ArrayCollection;
public var selectedUser:UserVO;
public var selectedTopic:TopicVO;
}
Because i use eager fetching, i can 'walk' through all object graph on my Flex client without hitting the database. This is ok as long as i don't need to insert, update, or delete some of the domain instances. But when that comes, problems with synchronization arise.
For example, if i want to show details about some user from some UserListView, when user(actor) select that user in list, i will take selected index in UserList, get element from users ArrayCollection in ModelLocator at selected index and show details about selected user.
When i want to insert new User, ok, I will save that user in database and in IResponder result method i will add that user in ModelLocator.users ArrayCollection.
But, when i want to add new topic for some user, if i still want to use convenience of EAGER fetching, i need to reload user list again... And to add topic to selected user... And if user is in some other location(indirectly), i need to insert topic there also.
Update is even worst. In that case i need to write even some logic...
My question: is this good way of using ModelLocator in Cairngorm? It seems to me that, because of mentioned, EAGER fetching is somehow pointless. In case of using EAGER fetching, synchronization on Flex client can become big problem. Should I always hit database in order to manipulate with my domain model?
EDIT:
It seems that i didn't make myself clear enough. Excuse me for that.
Ok, i use Spring in technology stack also and DTO(DVO) pattern with flex/spring (de)serializer, but i just wanted to stay out of that because i'm trying to point out how do you stay synchronized with database state in your flex app. I don't even mention multi-user scenario and poling/pushing topic which is, maybe, my solution because i use standard request-response mechanism. I didn't provide some concrete code, because this seems conceptual problem for me, and i use standard Cairngorm terms in order to explain pseudo-names which i use for class names, var names etc.
I'll try to 'simplify' again: you have flex client for administration of above mentioned domain(CRUD for each of domain classes), you have ListOfUsersView(shows list of users with basic infos about them), UserDetailsView(shows user details and list of user topics with delete option for each of topic), InsertNewUserTopicView(form to insert new topic) etc.
Each of view which displays some infos is synchronized with ModelLocator state variables, for example:
ListOfUsersView ------binded to------> users:ArrayCollection in ModelLocator
UserDetailsView ------binded to------> selectedUser:UserVO in ModelLocator
etc.
View state transition look like this:
ListOfUsersView----detailsClick---->UserDetailsView---insertTopic--->InsertTopicView
So when i click on "Details" button in ListOfUsersView, in my logic, i get index of selected row in ListOfUsers, after that i take UserVO object from users:ArrayCollection in ModelLocator at mentioned index, after that i set that UserVO object as selectedUser:UserVO in ModelLocator and after that i change view state to UserDetailsView(it shows user details and selectedUser.topics) which is synchronized with selectedUser:UserVO in ModelLocator.
Now, i click "Insert new topic" button on UserDetailsView which results in InsertTopicView form. I enter some data, click "Save topic"(after successful save, UserDetailsView is shown again) and problem arise.
Because of my EAGER-ly fetched objects, i didn't hit the database in mentioned transitions and because of that there are two places for which i need to be concerned when insert new topic for selected user: one is instance of selectedUser object in users:ArrayCollection (because my logic select users from that collection and shows them in UserDetailsView), and second is selectedUser:UserVO(in order to sync UserDetailsView which comes after successfull save operation).
So, again my question arises... Should i hit database in every transition, should i reload users:ArrayCollection and selectedUser:UserVO after save in order to synchronize database state with flex client, should i take saved topic and on client side, without hitting the database, programmatically pass all places which i need to update or...?
It seems to me that EAGER-ly fetched object with their associations is not good idea. Am i wrong?
Or, to 'simplify' :) again, what should you do in the mentioned scenario? So, you need to handle click on "Save topic" button, and now what...?
Again, i really try to explain this as plastic as possible because i'm confused with this. So, please forgive me for my long post.
From my point of view the point isn't in fetching mode itself but in client/server interaction. From my previous experience with it I've finally found some disadvantages of using pure domain objects (especially with eager fetching) for client/server interaction:
You have to pass all the child collections maybe without necessity to use them on a client side. In your case it is very likely you'll display topics and comments not for all users you get from server. The most like situation you need to display user list then display topics for one of the selected users and then comments for one of the selected topics. But in current implementation you receive all the topics and comments even if they are not needed to display. It is very possible you'll receive all your DB in a single query.
Another problem is it can be very insecure to get all the user data (or some other data) with all fields (emails, addresses, passwords, credit card numbers etc).
I think there can be other reasons not to use pure domain objects especially with eager fetching.
I suggest you to introduce some Mapper (or Assembler) layer to convert your domain objects to Data Transfer Objects aka DTO. So every query to your service layer will receive data from your DAO or Active Record and then convert it to corresponding DTO using corresponding Mapper. So you can get user list without private data and query some additional user details with a separate query.
On a client side you can use these DTOs directly or convert them into client domain objects. You can do it in your Cairngorm responders.
This way you can avoid a lot of your client side problems which you described.
For a Mapper layer you can use Dozer library or create your own lightweight mappers.
Hope this helps!
EDIT
What about your details I'd prefer to get user list with necessary displayable fields like first name and last name (to display in list). Say a list of SimpleUserRepresentationDTO.
Then if user requests user details for editing you request UserDetailsDTO for that user and fill tour selectedUser fields in model with it. The same is for topics.
The only problem is displaying list of users after user details editing. You can:
Request the whole list again. The advantage is you can display changes performed by other users. But if the list is too long it can be very ineffective to query all the users each time even if they are SimpleUserRepresentationDTO with minimal data.
When you get success from server on user details saving you can find corresponding user in model's user list and replace changed details there.
Tell you the truth, there's no good way of using Cairngorm. It's a crap framework.
I'm not too sure exactly what you mean by eager fetching (or what exactly is your problem), but whatever it is, it's still a request/response kind of deal and this shouldn't be a problem per say unless you're not doing something right; in which case I can't see your code.
As for frameworks, I recommend you look at RobotLegs or Parsley.
Look at the "dpHibernate" project. It implements "lazy loading" on the Flex client.

Best practices for control permissions?

Hey all, I need some advice on this...
We have certain permissions setup in the database for certain levels of control a user can have over the application. Disabled, ReadOnly and Edit.
My question is: Are there more generic/better ways to handle permissions applied to a form element on the page than writing a security method/check per page to enable/disable/hide/show proper controls depending on the permissions allowed?
Anyone have any experience handling this in different ways?
Edit:
I just thought about the possibility of adding constants for each layer that needs security and then adding an IsAuthorized function in the user class that would accept a constant from the form that the control is on, and return boolean to enable/disable controls, this would really reduce the amount of places I'd have to hit when/if I ever need to modify the security for all forms.
Cheers!
Sorry for going slightly off-topic here, but learn from my mistake:
I had a simple web app one time that I was developing and I thought that I'd setup 3 levels of security: limited read-only (public), read-limited write (user), read-write (admin). The users table had a level of security in it and everything worked fine... until I needed finer control over security levels as the project grew. It all started with a user that needed more than user control in one area of the program but not full admin control.
What I should have done was setup an expandable system with finer control even though I didn't need it at first. This would have saved me sooo much time.
I think there are more possibilities than you are considering.
Hidden/Visible - is the field visible or not
Blanked/System/Unchanged - does the system initially set the value to blank, or to some business-rule-provided value, or is it left as-is
ReadOnly/Editable - can the user change the value
Required/LeaveBlank/Optional - is the field required to not be blank, or can it be left blank assuming it was blank to begin with, or is it optional and can be blank in any case
Also you need to consider a lot of factors that go into making the decision
Role - usually the user has 1 or more roles, and those roles can allow or disallow different possibilities
Status - the status of the object in question often controls which fields are editable, regardless of role
Object - often the values of the object itself determine what is allowed when, beyond just's it's status
Task - you might break down editing things into more than just read and edit
Section - I often want to control the settings for an entire section of the object or screen, and all the controls inherit those settings, but can override them on an individual basis if needed
Implementation?
First, make sure you have a clear vision of how the page lifecycle is handled. Mine usually goes something like this.
Get the object they are editing, usually from session state, sometimes if they are doing a "new" operation you may need to create a stub data structure for them to work on
If this is the first time the page is loading up, populate choices into dropdowns, this is usually a generic process, done only once
If this is a postback, update the object being edited by reading in values off the controls
Process events such as button clicks
Run through all your business edits, these should alter the data structure they are editing
Update the visibility and editability of the controls based on all the data you have on hand
Populate the controls with the data from the object being edited, including validation messages, or error messages
You may want to check how django handles forms and validates them. Forms are handled like models, they have their own class, so their field list, validation rules and display logic is no more scattered throughout the view, the controller and the helper. With such a structure, it's pretty clear where the hidden/readonly/editable logic belong.
It seems that such a feature is not yet implemented in rails. It's not only a time-saver, it keeps your code clean and structured. You could start by creating a base class for forms, where validation is separated from the controller.
To work properly, I have found that access levels should be in this increasing order:
NONE, VIEW, REQUIRED, EDIT.
Note that REQUIRED is NOT the top level as you may think it would be since EDIT (both populate & de-populate permission) is a greater privilege than REQUIRED (populate-only permission).
The enum would look like this:
/** NO permissions.
* Presentation: "hidden"
* Database: "no access"
*/
NONE(0),
/** VIEW permissions.
* Presentation: "read-only"
* Database: "read access"
*/
VIEW(1),
/** VIEW and POPULATE permissions.
* Presentation: "required/highlighted"
* Database: "non-null"
*/
REQUIRED(2),
/** VIEW, POPULATE, and DEPOPULATE permissions.
* Presentation: "editable"
* Database: "nullable"
*/
EDIT(3);
From the bottom layer (database constraints), create a map of fields-to-access. This map then gets updated (further restrained) at the next layer up (business rules + user permissions). Finally, the top layer (presentation rules) can then further restrain the map again if desired.
Important: The map must be wrapped so that it only allows access to be decreased with any subsequent update. Updates which attempt to increase access should just be ignored without triggering any error. This is because it should act like a voting system on what the access should look like. In essence, the subsequent layering of access levels as mentioned above can happen in any order since it will result in an access-level low-water-mark for each field once all layers have voted.
Ramifications:
1) The presentation layer CAN hide a field (set access to NONE) for a database-specified read-only (VIEW) field.
2) The presentation layer CANNOT display a field when the business rules say that the user does not have at least VIEW access.
3) The presentation layer CANNOT move a field's access up to "editable" (nullable) if the database says it's only "required" (non-nullable).
Note: The presentation layer should be made (custom display tags) to render the fields by reading the access map without the need for any "if" statements.
The same access map that is used for setting up the display can also be using during the submit validations. A generic validator can be written to read any form and its access map to ensure that all the rules have been followed.
(Also see thread: Best Practices for controlling access to form fields)

Resources