WCF RIA Services / intercept or subscribe to a RaiseDataMemberChanging - wcf-ria-services

So I'm new to the concept of routed events, but I know that messages are flying everywhere when fields are changing via the RaiseDataMemberChanging / RaiseDataMemberChanged messages.
The quick question is how to I "listen" for those routed messages?
I would like my view model, in a MVVM correct matter, intercept a message that a field is being updated, deep down in the heirarchy of tables. If a change occurs in a child (a date range), that date range change has some business logic associated with it that works from top down.
I've know that I can use partial methods to inject code during the changing and changed events, but the design (one to one relationship) means that a change to the child, in the context of the child, has no reference the parent (Parent has a one to one reference to child, but child has no reference to parent).
Yes I can add the reference from the child to the parent (making the parent have both a one to one, as well as a one to many relationship), but during creation of the entity, this creates a problem - parent has to exist before the child entity exists, and the child entity has to exist before a reference to the parent can exist. This design requires an insert of the parent, and child, then an update of the child - which confuses WCF RIA Services during the inital creation process.
Sorry for the long winded explaination, but I'll even consider design changes if this all makes sense to anyone that cares to comment.
Any input would be appreciated.

I'm using a subscription to the PropertyChanged events of the Entity in question. It seems like a lot of work to filter out all the events for a couple of fields.
Using RX, I'm hoping that the resources used are minimal, and the weak reference avoids the memory link issue when a strong reference is used to deal with events:
Observable.FromEventPattern<PropertyChangedEventArgs>(this.FlowEntity, "PropertyChanged")
.Where(pPropertyChanged => (
pPropertyChanged.EventArgs.PropertyName.EndsWith("Date")) ||
pPropertyChanged.EventArgs.PropertyName == "Capacity"
)
.Subscribe(pObserver => this.RaiseFlowEntityDateChanged(this, pObserver.EventArgs));
FlowEntity is the child entity that I'm monitoring from the parent. I then raise custom event using the parent entity, rather than the entity that actually holds the event.
I can't raise this event from the partial methods, as the child entity would not have the context of the parent.

Related

Multi Object Unbound Action for updating Contained Entities in OData

In OData, a contained entity does not have an entity set. All operations on it should be through the parent entity. And this is true for single-object APIs.
Can we have an unbound action to update multiple such contained entities by directly providing the ID with no parent in context? Would this be according to the Odata specs?
Thanks and Regards,
Jyothi
You could do it, but as an Unbound Function that is technically all it is, Unbound, there is nothing in the specification preventing you from doing it this way but it would not be constrained to a specific resource by route. That makes the Action unintuitive in terms of both discovery and expectations.
The OData way to do this would be to bind the operation to the Parent Entity. If the operation affects or retrieves data across multiple entities or you really want to avoid needing to resolve the Parent key, then it should still be bound to the Collection rather than being Unbound.
Reserve Unbound Actions for operations that are outside of the model, diagnostics or other esoteric implementations that otherwise don't have a single natural place in the OData Schema.
Having an Action That targets single or multiple Contained Entities without reference to the Parent is in the vicinity of being an Anti-Pattern, though I can not cite any sources that explicitly support this claim, the general reason for Contained Entities at all is because you can't directly reference the contained entity without the Parent Key, it was designed for scenarios where the Parent Key forms part of the Key for the contained item.
A classic example is Invoice and InvoiceLines. If your InvoiceLines Key is a simple Line Number and is only unique within the Invoice parent, so in the Database this might be a composite key using InvoiceId and LineNumber. In this case we can only expose this Entity as being Contained within a specific Invoice because there is no other way to uniquely reference a single InvoiceLine item.
If your Contained Entity has a unique Key AND you intend on performing operations directly against these Entities without reference to the Parent Entity then that Entity really should be exposed as a top-level collection of it's own.

Event Sourcing. Aggregates with Children lists or with ParentID?

Should I store in Aggregate lists of children or only ParentID?
Lists of children can be huge (thousands). Adding or removing one child would mean saving back to storage thousands and thousands children when only one added or removed.
ParentID is very easy to manage. It makes all aggregates simple (no lists!). It allows to quickly create lists by simply querying aggregates by their ParentID. It allows arbitrary level of hierarchies that can be quickly rebuilt recursively without creating huge aggregates.
If I'd go with ParentID, should I add to events table the field ParentIdGuid to refer to the parent of the aggregate so i can quickly generate lists?
EDIT:
Brad's answer made me realize that parentid will not be included in the resulting json of the child objects that were updated, since I would only include the fields that had changed. Therefore I cannot rely on json indexing of postgress. That means i would have to create a parentid column on the events table itself.
A parent ID on the child is definitely the way to go. Think of a database foreign key. The relationship is held as a parent ID pointer in the child record.
When you instantiate your AR in memory to use it, you should populate the list of children using the ParentID pointer. If this is expensive, which it sounds like it is, maybe you implement a populate-on-demand function so you don't pay the price unless it's necessary.
There are 2 approaches to the Events table. It either contains all properties of the entity after the change is made, or it can contain just the modified fields. If you’re in the camp of saving all properties, then the ParentID should be in each event. If you prefer to save just the changes, then somewhere in the event list for that entity should be the ParentID; possibly just in the creation event. With Event Sourcing you add up all the change events to arrive at the current state, so this would give you the ParentID in the entity.

Entity Framework separate initialization context and info models

I am trying to set up multiple DbContext objects in my solution. One will be the initialization context and the others will be bounded contexts.
The scenario I am having difficulty resolving is as follows:
Having two database tables, a parent object and a child object. Upon initialization the tables are created okay with all the properties on, however in the bounded context I want to use the parent object and only return a subset of properties from the child object.
At the moment both the initialization context and the bounded context use the same parent class so therefore I can't use a third info object for the child object in the bounded context.
Would I therefore need to create another parent object for use in the bounded context which uses another child object with subset of properties?
So would I need in the initialization context a parent and child object and in the bounded context a separate parent and child object where the child object only has a subset of properties and the parent object points to that child?
I am quite happy to create the child class with a subset of properties but it seems a bit long winded to create a separate parent object to point to the child info object but I can't see a way around this.
Having watched Julie Lermans TechEd Europe 2014 "Entity Framework Model Partitioning in Domain-Driven Design Bounded Contexts" https://www.youtube.com/watch?v=rGA_FNew-6g I have decided to go down the route of having a master context purely for database migrations.
I found the idea of using events and message queues and separating the data into different tables in the database interesting but it's probably a bit heavy handed for our needs at the moment.

DependencyProperty analogue for WPF MVVM Model

I have my MVVM and the model consists of a number of related classes, but for the sake of this question we'll focus on just four.
GrandParentModel, ParentModel, ChildModel and Contact.
These all inherit from ModelBase which has an implementation of INotifyPropertyChanged on it.
So each of the three models has a Contact property. If Child doesn't have a property it is supposed to look to Parent, and if Parent is blank it will look to GrandParent. If the contact changes at the grandparent level I'd like any dependants, ie any sub parents and their children to raise a PropertyChanged event for their Contact too.
I think everything I'm going to do will be supported by the DependencyProperty system, but I don't want to use that as this is my Model, separation of concerns and all that. So I'm putting together a mini implementation, which is all fine.
My question is has anyone been down this path before and is there anything I should be worried about in the future? My Spidey-Senses are tingling and I don't know why.
Thanks
Ian
Edit: The relationship between the objects here is that a grandparent has any number of parents has any number of children. My current model has a property on each which points at the parent (null in the case of a grandparent) and a parent/grandparent has a collection of child objects.
I've been down this path, and it's not pretty. Basically you have to subscribe to the PropertyChanged event of ParentModel from your ChildModel. You have to take care if your child can change parents. Then when you get notified of a change in the parent from the child's point of view, you have to raise your own PropertyChanged event on the child. It gets ugly because you can end up with hanging event handlers that you forgot to clean up.
A better method would be to create your own Model-specific analog to DependencyProperty. Basically in your constructor of ChildModel you "declare" that property Contact delegates to property Contact of object Parent when null. You do that using a little helper class that observes the PropertyChanged event on the ParentModel object and have it execute a PropertyChanged event on the child when appropriate. Also have it watch for the Parent property to change on the child.
You could use the MVVM Light message bus. Have the grandparent and parent all send a message when their Contact property changes. Have the child listen for those messages. When it gets a message, then check to see if it matches its own parent or grandparent, and raise a PropertyChanged event if necessary. This is better than either method above because you don't have to keep track of when your parent or grandparent changes. You're less likely to have bugs. It also uses weak references, so it won't hold on to objects the way event handlers do.
Now what I've been doing is getting away from having my model objects implement INotifyPropertyChanged. I introduced a Presenter layer between my Model and my ViewModel. The Presenter actually constructs a ViewModel out of small ViewModel "widgets" (one widget might be a ChangeValue<T> widget, for instance). I have a rules engine that tells the Presenter how to compose a ViewModel out of widgets for a given Model. The Presenter handles all user input (basically executing a lambda against the Model), but since it knows that a user action just took place, it knows that something in the Model might have changed. After the Model action is complete, it copies all of the data from the Model to the ViewModel. The ViewModel inspects the incoming data and raises a PropertyChanged event if the field actually changed. Obviously that's the most compliated way of doing it, but it gives you a really clean Model and neither the ViewModel nor the Presenter contains any Model (domain/business) logic.

RIA services presentation model with 1-many or many-many relationships

I'm trying to get a presentation model (discussed here and here) working in RIA. All the examples I can find are simple, flat data entities with no 1-many or many-many relationships, which are what I can't get working - specifically, on updates and inserts into associative relationships.
Queries I can get working fine - I have my presentation classes marked up with Association attributes (and Include attributes, where appropriate), and I have a good understanding about how data is loaded into the client side and maintained there as entities. I also have inserts of new entities covered. However, I'm experiencing the following problems. For the following examples, assume we have simple Album and Artist entities, where an Album has a single artist and an Artist can have zero to many albums. Both have a Name property.
On the client side, if I do myArtist.Albums.Add(anAlbum) or myArtist.Albums.Remove(anAlbum), nothing happens. HasChanges returns false. (Note that myArtist and anAlbum were obtained solely in code by loading the entities and iterating to get references to specific entities: I'm not doing anything in UI or with DomainDataSources yet, just dinking around).
If I update the Name on an Artist and SubmitChanges, when the Update method gets called on the server, the Albums collection is null.
Does anyone have any suggestions, or can you point me to an example that uses more complex objects?
EDIT (keeping the above for posterity): Alright, it appears that the second issue (a reference to an entity or a collection of entities showing as null when Update gets called on the server) exists because the child entites aren't marked as Changed and so they aren't being serialized and sent back. I know you can force that to happen by using [Composition] and I have gotten it to work that way, but this is not a compositional relationship and I want both entities to be "top-level" entities. How can I mark an entity as changed?
The problem was that my [Association] attributes weren't correctly defined. I didn't realize that the association's Name property has to be the same on both sides of the association. When the names are the same and you do a build, the generated code on the client uses a different constructor for the EntityCollection used by the "parent" to refer to the "children" than it does if the associations aren't set up right. The new constructor takes callbacks that do a little bit of extra handling when you call Add and Remove on the collection - specifically, they take the child entity you are adding or removing and modify the property on it that refers to its parent so that everything remains in sync: the collection you removed the object from, the collection you added it to, and the object's reference to its parent.