BreezeJS - handling lookup tables across modules - breeze

We have a large application that allows the user to switch between different modules within the application. Each module needs to be able to save separately, so each module has it's own EntityManager.
There are some lookup tables, though, that we would like to use across the application. If we load the lookup tables at the application level, using a different EntityManager, they are not very usable then within the modules.
For example, if I want to load a 'Countries' lookup table at the application level, I then can't do something as simple as:
Person.Country = lookupDataContext.getCountry('Norway')
if Person is within a module's EntityManager. I will get something like:
"An Entity cannot be attached to an entity in another EntityManager. One of the two entities must be detached first."
Am I understanding BreezeJS correctly? If so, does that mean I need to have the Countries lookup within each module's EntityManager? This seems very limiting.

I believe this question is related to your other question about having multiple EntityManagers. Check out my general thoughts there which cover the scenario you describe here.
To be slightly more specific:
Breeze entities cannot navigate to related entities in a different EntityManager; that's what the error message is telling you.
You probably do want separate instances of the reference entities (such as Countries) in both managers.
You can easily copy any set of entities from one manager to another with export and import methods. You don't have to go back to the server.
Now, instead of a lookupDataContext, each sandbox datacontext can have a sandboxContext.lookups.countries method that delivers the appropriate entities from the proper sandbox manager.
Is this limiting? I don't think it's so bad as long as
you aren't duplicating an enormous amount of data across managers.
the reference entities are essentially immutable during a user session.
a user session doesn't keep too many sandbox managers alive at the same time
you dispose of or re-cycle the sandbox managers (and their datacontexts) when you're done with them.
You should be able to achieve your goal of loading lookups from the server once and managing them centrally in the master manager.
This approach has been very successful in a great number of applications over the last decade (pre-Breeze obviously).
HTH.

Related

How to Cache Multiple Objects Representing the Same User

We have a fairly complicated framework (made up of multiple plugins) that we've developed for all of our future Groovy/Grails applications. One aspect of this framework is the ability to retrieve user information from the various systems that we store this data in. Currently we have three classes that represent a user (one for LDAP (non AD), one for AD, and one for database). The reason for three separate classes is because they access totally disparate systems and are based on different base classes to provide various functionality need to access these systems. There's also dependencies, etc. that require this three class approach. One of these classes (the one for AD) is also used by Spring Security to represent a user. It is also possible to create any user object type from another user object type.
What I'm trying to create is a way for us to cache these objects. For example, during login, one class is always loaded (by Spring Security). However, throughout the process of using the application, another class (for database info for example) might get loaded temporarily. Ideally I'd like to cache these objects (that all represent the same user) so that we don't have to reload information.
In the end what I'm hoping to accomplish, is the ability to pass one user object (say AD) to another user class (say database) factory method, and have the database user class check if it has ever existed before for this user and if so, instead of recreating itself, just grab the cached copy. I'd rather not use a central cache to do all of this caching, but instead store the cached information in the actual objects (just seems cleaner that way).
What I can't figure out though is how to accomplish this (from a design perspective). So I'm looking for recommendation on which design patterns might help me to figure out an approach to creating this functionality.
P.S. Just in case it matters, all user classes extend different base classes, however, they all implement a shared interface.
Sounds like the appropriate caching at the various services that are responsible for looking up the related User instances would be the most appropriate approach. Using the Cache plugin would make this quite trivial.
Your factory method could delegate to the appropriate service method which would be annotated with the correct cache. Just keep in mind that you will need to invalidate items in the cache as well if they are subject to changes.

grails design classes and external data (spreadsheet)

Having a bit of an issues on design, and was hoping I could ask for advice here. Accept that grails may be the completely wrong tool, but such is life.
So have been working away on a web app that basically just present a lot of information from a google spreadsheet and sends some updates back. I have managed to get most of it working but decided to rewrite it to get rid of my ridiculous spaggeti code as well as the many pieces of broken code that lays strewn throughout the project.
The system is relatively small, two-three users. The amount of data is small as well. One worksheets with max 500 rows (four columns) and another one with potentially 5000 (four columns). So all small, but I need it (well, want it) to stay in the google spreadsheet and the application feeding from there.
There are three classes I need for this to work,
Google authentication class keeps information on keys and tokens to speak to google
Google Spreadsheet class keeps information on the source spreadsheet
Google Data Entry keeps information from the two spreadsheets based on a unique id
So here is my question, what should I define these classes as. Thought I would use Domain classes, but then realised that these are stored in a database. Is there a way of keeping domain classes session dependent, I.E., that two users can use the same app on the same server but never see each others data and that the data is destroyed on logout. If not, is there some other class I can use that works similar to Domain class but kept in memory user/session specific.
I'm not really sure what exactly your requirements for those classes, but here are some thoughts anyway.
First, you may want to ask if they can't just be "normal" classes in src/groovy. I say "normal" here in the sense that they may just encapsulate some data and behavior, and you are responsible to create instances of them and call the methods appropriately when needed.
But, if you want to tie some data and behavior to the user session (as you seem to, because you asked for session dependent domain classes), you may want to use a Grails Service with session scope. When you do that, Grails will use a different instance of the service for each session of your application, and reuse the same instance for the same session until it ends.
You may also use a bit of each thing, using one service with session scope and have other classes representing the data that you pass around from the controllers to the service and vice-versa. These could actually be Command Objects if you needed validation and data binding, for example.

What’s the best approach to work with in memory domain objects in Grails?

I’m working on a Grail’s project that has some Domain objects not persisted on the database. They are managed thru a REST API, so all their CRUD operations will be done with this API instead of the database.
The point is to still be able to use some interesting Grails plug-ins (like searching using Compass).
For instance, the administration the Domain objects Users is going to be managed with the REST API, so when the Users list is displayed a the REST method to retrieve the list of users will be invoked on the remote server. I hope this use case is clear enough :)
I can think on several ways to design that but I'm not sure what’s the best:
Should I create the Domain Objects in the controller (and delete the
previous Users stored in memory)?
It seems it’s possible to define a Domain Class not persistable (with
mapping I think) but I’m not sure if this is the best approach or
where to load the data.
It is better not to model as a Grails the User as Domain object?
Thanks in advance!
I would wrap the REST interactions in a service, and call the service from a controller. In that case, the service would get the response and create its objects, passing the list back to the controller. Controllers should just handle incoming requests, invoke application components, and return responses.
It seems you want models to represent the data in the other application, which is a good idea. Since you don't need GORM, you might want to define them in the 'groovy' folder of your app instead of the domain models folder. Then I think they will just be objects.
I'd go with non-domain objects in src folder - though, need to check if it's possible to use the mentioned plugins with them.
I wonder what domain class functionality you wish to get out of non-persistent classes?

ASP.NET MVC models when using external web services

I'm getting started on a new MVC project where there are some peculiar rules and a little bit of strangeness, and it has me puzzled. Specifically, I have access to a database containing all of my data, but it has to be handled entirely through an external web service. Don't ask me why, I don't understand the reasons. That's just how it is.
So the CRUD will be handled via this API. I'm planning on creating a service layer that will wrap up all the calls, but I'm having trouble wrapping my head around the model... To create my model-based domain objects (customers, orders, so on..) should I:
Create them all manually
Create a dummy database and point an ORM at it
Point an ORM at the existing database but ignore the ORM's persistence in lieu of the API.
I feel like I've got all the information I need to build this out, but I'm getting caught up with the API. Any pointers or advice would be greatly appreciated.
Depending on the scale of what you're doing option 3 is dangerous as you're assuming the database model is the same as that exposed by the external service. Options 1 and 2 aren't IMHO much different from each other - in either case you'll have to decide what your objects, properties and behaviours are going to be - it just boils down to whether you're more comfortable doing it in classes or database tables.
The key thing is to make sure that the external service calls are hidden behind some sort of wrapper. Personally I'd then put a repository on top of that to handle querying the external service wrapper and return domain objects.
In general, ORMs are not known for their ability to generate clean domain model classes. ORMs are known for creating data layers, which you don't appear to need in this case.
You could probably use a code generation tool like T4 to code generate a first pass at your domain model classes, based on either the web service or the database, if that would save you time. Otherwise, you probably would just manually create the domain objects. Even if you code generate a first pass at your domain objects, it's unlikely there is a clean 1-1 mapping to your domain objects from either the database or web service, so you will likely need to spend significant time manually editing your code generated domain classes anyway.

DDD principlers and ASP.NET MVC project design

Two part questions
I have a product aggregate that has;
Prices
PackagingOptions
ProductDescriptions
ProductImages
etc
I have modeled one product repository and did not create individual repositories for any of the child classes. All db operations are handled through product repository.
Am I understanding the DDD concept correctly so far? Sometimes the question comes to my mind that having a repository for lets say packaging options could make my life easier by directly fetching a the packaging option from the DB by using its ID instead of asking the product repository to find it in its PackagingOptions collection and give it to me..
Second part is managing the edit create operations using ASP.MVC frame work
I am currently trying to manage all add edit remove of these child collections of product through product controller(sound right?).
One challenge I am now facing is;
If I edit a specific packaging option of product through
mydomain/product/editpackagingoption/10
I have access to the id of the packaging option
But I don't have the ID of the product it self and this forces me to write a query to first find the product that has this specific packaging option then edit that product and the revelant packaging option. I can do this as all packaging option have their unique ID but this would fail if I have collections that don't have unique ID.
That feels very wrong..
The next option I thought of is sending both the product and packaging option IDs on the url like;
mydomain/product/editpackagingoption/3/10
But I am not sure if that is a good design either.
So I am at a point that I am a bit confused. might be having fundamental misunderstandings around all of this...
I would appreciate if you bear with the long question and help me put this together. thanks!
In my mind, this is one of those muddy things that pops into DDD.
In code, I treat an aggregate root as a container for any "relationships" it has and any Entity Objects that cannot exist without the Aggregate root.
For instance, let's take the Customer->Order->LineItem->Product example that's been bludgeoned to death by now. The aggregate root as I've displayed it is customer in this scenario. That stated, you don't always want to get to the order through the customer. You might want to find orders on a specific date.
Turning it on it's side, you also wouldn't have a Customer that doesn't have an order. The two are in a somewhat symbiotic relationship so one isn't the aggregate root of the other.
The point is that you don't want to have to load a customer through an order, but you don't necessarily want to load an order through the customer either.
Starting at Order, however, it's unlikely that you'd want to just retrieve a LineItem and you're certainly not going to be creating them w/o an order. To that end, the Order serves as the gateway to LineItems. LineItems wouldn't need their own controller or repository. They only exist within the Order itself and, as such, are part of the Order (in this case, Order becomes the aggregate root) and are managed by the Order Entity.
But, a LineItem would likely have a relationship to a Product within the system. Products would have their own controllers, repositories, etc because they can exist outside of the Aggregate root.
In summary to my rambling, I tend to look at it this way: if an Entity can exist by itself, it should have a controller. Entities that cannot exist on their own (LineItems in this case) should only be managed solely by their container (aggregate root).
Will some DDD purist please correct me if/where I'm wrong?
As to the second part of your question, I would need some more details about how you envision these other Entities working. With what you've put here, I'd imagine that PackagingOptions are related to a product and would be part of a Product aggregate root. Now, implying that you're editing them begs the question of is this a lookup table in the system or are they one-off values and, as such, should be treated as Value Objects?
Kaivalya,
Regarding your last comment (stateless http):
It depends on the context. Before getting into the details, I should tell you a basic principle about aggregates:
Aggregates define a group of related objects that should be treated as a single unit for the purpose of data change.
This is extremely important. The purpose of having Aggregates is to enforce invariants. For example, you may have a policy like "An Order cannot exceed $500". Then, to enforce this policy, you put Order and OrderItem together in the Order Aggregate. This way, any time you add a new OrderItem, it should be added via Order object. There, you can check the total price and make sure it does not exceed $500. If you don't have such invariants in your domain, then there is no point loading all these objects together.
Now, getting back to your comment:
If you do have invariants that should be enforced, then it is okay to load the entire aggregate even though it may have some overhead. Yes, HTTP is stateless and you load your whole aggregate just for modifying one of its child objects and then throw it out. That is okay. What is important the most here is that you are enforcing your invariants. This is what DDD is for.
The purpose of DDD is to capture all business logics in your domain. You could definitely achieve a better performance if you didn't have to load the entire aggregate, but how would you enforce your invariants? You'd most likely have to do it in your stored procedure. Yes, it works, and it is fast, but dealing with business logics in stored procedures during maintenance is a nightmare. That is why DDD has evolved. So you can model your business requirements using object-oriented languages/tools, so they are easier to understand and modify.
Just remember, DDD is a great approach but not for all types of projects. If you are dealing with a project in which there are lots of business logics and the chances of them changing due to the nature of a business is high, then you should use DDD. However, if your project is more of a "read something/writing something" without much business logic involved, using DDD is a headache. You could simply use LINQ to SQL (or SqlDataAdapters) and send your objects to your Views. You don't even have to worry about finding Entities, Value Objects, Aggregates, Repositories, etc.
Hope this helps,
Mosh

Resources