MRTKv2: How get the spatial awareness observers - mrtk

A common question when working with Spatial Awareness (aka Spatial Mapping) in MRTK is how to access the spatial observers to configure them individually.
The question arises since the GetObserver methods of the IMixedRealitySpatialAwarenessSystem interface are marked as obsolete.

The version 2.0.0 release of MRTK has standardized the pattern for accessing data providers across services in order to
Provide a consistent pattern across all service types.
Enable services to add data provider support without requiring a breaking interface change.
The following example demonstrates this pattern to access spatial awareness mesh observers.
if (CoreServices.SpatialAwarenessSystem != null)
{
IMixedRealityDataProviderAccess dataProviderAccess =
CoreServices.SpatialAwarenessSystem as IMixedRealityDataProviderAccess;
if (dataProviderAccess != null)
{
IReadOnlyList<IMixedRealitySpatialAwarenessMeshObserver> observers =
dataProviderAccess.GetDataProviders<IMixedRealitySpatialAwarenessMeshObserver>();
// Modify the observer(s)
foreach (IMixedRealitySpatialAwarenessMeshObserver observer in observers)
{
// Set the mesh to use the occlusion material
observer.DisplayOption = SpatialMeshDisplayOptions.Occlusion;
}
}
}

Related

DDD - Should optimistic concurrency property (etag or timestamp) ever be a part of domain?

Theoretically speaking, if we implement optimistic concurrency on Aggregate Root level (changing entities in AR changes version on AR) and lets say we use timestamp for version property (just for simplicity) - should timeline ever be a property on AR or should it be a part of read model on one side and on other (for example, updates) be a separate argument to application service like:
[pseudo]
public class AppService{
.
.
.
public void UpdateSomething(UpdateModelDTO model, int timestamp)
{
repository.GetModel(model.Identifier);
model.UpdateSomething(model.something);
repository.ConcurrencySafeModelUpdate(model, timestamp);
}
}
I see pros/cons for both but wondering which is by-the-book solution?
[UPDATE]
To answer question from #guillaume31, i expect usual scenario:
On read, version identifier is read and sent to client
On update, client sends back the identifier and repository returns some kind of an error if version identifier is not the same.
I don't know if its important but i want to leave responsibility for creating/updating version identifiers themselves to my database system.
I assume, else you won't be asking this question, you are using your Domain model as Data model (i.e. Hibernate entity), then you have already introduced infrastructural concerns into your domain model, so I would suggest to go ahead and add the timestamp to AR.
There's no by-the-book solution. Sometimes you'll already have a field in your aggregate that fits the role nicely (e.g. LastUpdatedOn), sometimes you can make it non-domain data. For performance reasons, it may be a good idea to select the field as part of the same query that fetches the aggregate though.
Some ORMs provide facilities to detect concurrency conflicts. Some DBMS's can create and update a version column automatically for you. You should probably look for guidelines about optimistic concurrency in your specific stack.
The Aggregate should not care about anything else but business related concerns. It should be pure, without any infrastructure concerns.
The version column in the database/persistence is an infrastructure concern so it should not be reflected in the Aggregate class from the Domain layer.
P.S. using timestamps for optimistic locking is weird; you would better use an integer that is incremented every time an Aggregate is mutated and that is expected to have the (loaded-version + 1) when a save is executed.
public void UpdateSomething(UpdateModelDTO model)
{
(model, version) = repository.GetModel(model.Identifier);
model.UpdateSomething(something);
repository.ConcurrencySafeModelUpdate(model, version + 1);
}
Update: here is an implementation example in java.

Doesn't DDD and CQRS/ES break the persistence agnosticity of DDD?

The Domain model in DDD should be persistence agnostic.
CQRS dictates me to fire events for everything I wan't to have in my read model. (And by the way to split my model into a write model and at least one read model).
ES dictates me to fire events for everything that changes state and that my aggregate roots must handle the events itself.
This seems not to be very persistence agnostic to me.
So how could DDD and CQRS/ES be combined without heavy impact of this persistence technology to the domain model?
Is the read model also in the DDD domain model? Or outside of it?
Are the CQRS/ES events the same as DDD domain events?
Edit:
What I took out of the answers is the following:
Yes, for ORM the implementation of the domain model objecs will differ than that with using ES.
The question is the false way around. First write the domain model objects, then decide how to persist (more event like => ES, more data like => ORM, ...).
But I doubt that you will ever be able to use ES (without big additions/changes to your domain objects) if you did not make this decision front up, and also to use ORM without decide it front up will cause very much pain. :-)
Commands
Boiled down to its essence, CQRS means that you should split your reads from your writes.
Typically, a command arrives in the system and is handled by some sort of function that then returns zero, one, or many events resulting from that command:
handle : cmd:Command -> Event list
Now you have a list of events. All you have to do with them is to persist them somewhere. A function to do that could look like this:
persist : evt:Event -> unit
However, such a persist function is purely an infrastructure concern. The client will typically only see a function that takes a Command as input and returns nothing:
attempt : cmd:Command -> unit
The rest (handle, followed by persist) is handled asynchronously, so the client never sees those functions.
Queries
Given a list of events, you can replay them in order to aggregate them into the desired result. Such a function essentially looks something like this:
query : target:'a -> events:Event list -> Result
Given a list of events and a target to look for (e.g. an ID), such a function can fold the events into a result.
Persistence ignorance
Does this force you to use a particular type of persistence?
None of these functions are defined in terms of any particular persistence technology. You can implement such a system with
In-memory lists
Actors
Event Stores
Files
Blobs
Databases, even
etc.
Conceptually, it does force you to think about persistence in terms of events, but that's no different than the approach with ORMs that force you to think about persistence in terms of Entities and relationships.
The point here is that it's quite easy to decouple a CQRS+ES architecture from most implementation details. That's usually persistent-ignorant enough.
A lot of the premises in your question present as very binary/black-and-white. I don't think DDD, CQRS, or Event Sourcing are that prescriptive--there are many possible interpretations and implementations.
That said, only one of your premises bother me (emphasis mine):
ES dictates me to fire events for everything that changes state and
that my aggregate roots must handle the events itself.
Usually ARs emit events--they don't handle them.
In any case, CQRS and ES can be implemented to be completely persistence agnostic (and usually are). Events are stored as a stream, which can be stored in a relational database, a NoSQL database, the file system, in-memory, etc. The storing of events is usually implemented at the boundaries of the application (I think of this as infrastructure), and domain models have no knowledge of how their streams are stored.
Similarly, read models can be stored in any imaginable storage medium. You can have 10 different read models and projections, with each of them stored in a different database and different format. Projections just handle/read the event stream, and are otherwise completely decoupled from the domain.
It does not get any more persistence agnostic than that.
Not sure how orthodox this is, but a current event sourced entity model I have does something like this, which might illustrate the difference . . . (C# example)
public interface IEventSourcedEntity<IEventTypeICanRespondTo>{
void When(IEventTypeICanRespondTo event);
}
public interface IUser{
bool IsLoggedIn{get;}
}
public class User : IUser, IEventSourcedEntity<IUserEvent>{
public bool IsLoggedIn{get;private set;}
public virtual void When(IUserEvent event){
if(event is LoggedInEvent){
IsLoggedIn = true;
}
}
}
Very simple example - but you can see here that how (or even IF) the event is persisted is outside the domain object. You can easily do that through a repository. Likewise CQRS is respected, because how I read the value is separate from how I set it. So for example, say I have multiple devices for a user, and only want them logged in once there's more than two?
public class MultiDeviceUser : IUser, IEventSourcedEntity<IUserEvent>{
private IEnumerable<LoggedInEvent> _logInEvents = . . .
public bool IsLoggedIn{
get{
return _logInEvents.Count() > MIN_NUMBER_OF_LOGINS;
}
}
public void When(IUserEvent ev){
if(ev is LoggedInEvent){
_logInEvents.Add(ev);
}
}
}
To the calling code, though, your actions are the same.
var ev = new LoggedInEvent();
user.When(ev);
if(user.IsLoggedIn) . . . .
I think you can still decouple your domain from the persistence mechanism by using a satellite POCO. Then you can implement your specific persistence mechanism around that POCO, and let your domain use it as a snapshot/memento/state.

Domain Driven Design modelling queries

I'm building a new application and am new to Domain Driven Design. I've been reading through the documentation and I've managed to model most of the domain model but I would like some advice about two queries:
I have two domain objects channel and program. I've modelled these both as entities as both can be accessed independantly. A channel can have a list of programs so I have put this as an attribute of channel. My query is how should I populate the program list. Is it OK for the getChannerById method in ChannelService to first get the channel information and then call the ProgramService to get the list of programs for the channels e.g:
Channel {
String channelId
List <Program> programList
}
Program {
String programId {
}
ChannelService {
Channel getChannelById(String channelId)
}
ProgramService {
Program getProgramById(String programId)
List <Program> getProgramsByChannelById(String channelId)
}
I have a product domain object but some of its attributes (e.g. specification and compatability) involve quite time consuming operations. These attributes are not required all the time so is it OK to put these as part of the domain object and have seperate service methods that populate these attributes when required e.g.
Product {
String productId
Specification specification
List <Product> compatibleProducts
}
ProductService {
Product getProduct(String productId);
void getProductSpecifications(Product product);
void getCompatibleProducts(Product product);
}
Any advice would be very much appreciated.
When designing entities in DDD you shouldn't create associations from one entity to another such that the association is used for display or query purposes alone. While it is true that a channel has a set of programs, is the association between channel and the set of its programs required for the channel entity? More importantly, if you're only considering the query aspect then you may not need be forcing DDD upon your code. Instead, when designing entities consider the behavior that these entities need to implement. If your entities have no behavior but are only used as data containers then you don't need DDD. To answer your question, I would use read model classes that satisfy requirements of each query. For example, for your product model, if one query requires the specification attribute and another doesn't, create distinct read-model classes for those queries. These classes are not entities, they are simple read-only value objects, they don't have any behavior and their job is to represent data. In regards to implementing the query you have several options. Calling both the ChannelService and the ProgramService is one option. However, if the data is all stored together in a single database, why not just create a repository that returns all required data with one call? Take a look at my post on read-models in DDD for more on this topic.

DDD Repositories and Factories

i've read a blog about DDD from Matt Petters
and according and there it is said that we create a repository (interface) for each entity and after that we create a RepositoryFactory that is going to give instances (declared as interfaces) of repositories
is this how project are done using DDD ?
i mean, i saw projects that i thought that they use DDD but they were calling each repository directly, there was no factory involved
and also
why do we need to create so much repository classes, why not use something like
public interface IRepository : IDisposable
{
T[] GetAll();
T[] GetAll(Expression<Func> filter);
T GetSingle(Expression<Func> filter);
T GetSingle(Expression<Func> filter, List<Expression<Func>> subSelectors);
void Delete(T entity);
void Add(T entity);
int SaveChanges();
}
i guess it could be something with violating the SOLID principles, or something else ?
There are many different ways of doing it. There's is not single 'right' way of doing it. Most people prefer a Repository per Entity because it lets them vary Domain Services in a more granular way. This definitely fits the 'S' in SOLID.
When it comes to factories, they should only be used when they add value. If all they do is to wrap a new operation, they don't add value.
Here are some scenarios in which factories add value:
Abtract Factories lets you vary Repository implementations independently of client code. This fits well with the 'L' in SOLID, but you could also achieve the same effect by using DI to inject the Repository into the Domain Service that requires it.
When the creation of an object in itself is such a complex operation (i.e. in involves much more than just creating a new instance) that it is best encapsulated behind an API.

How To Implement The Query Side Of CQRS in DDD?

I have implemented the command side of DDD using the domain model and repositories, but how do I implement the query side?
Do I create an entirely new domain model for the UI, and where is this kept in the project structure...in the domain layer, the UI layer, etc?
Also, what do I use as my querying mechanism, do I create new repositories specifically for the UI domain objects, something other than repositories, or something else?
From my understanding of CQRS you would create a set a DTOs that fulfil the requirements of the user interface screens or applications that may need to consume them.
Where this exists in the project is based on the requirements as it would depend if you were going to expose these DTOs via web services.
In which case I wouldn't put it in the Web Layer but rather in the Application layer or a dedicated Façade layer.
Then you would have a read only repository or data access layer which populates the DTOs directly. I think that the Query side of things should be optimized for read performance in which case direct queries/stored procedures on database views or tables and SqlDataReaders would do the best job here. But it would definitely be worth abstracting this access behind an interface so you can add a cached implementation later down the track.
If you're using an ORM and want to map from your Domain Entities to the DTOs then you could have a generic QueryRepository which has methods which take an ISpecification or similar construct for defining your queries then a DtoAssembler object for creating the Dtos from your Domain objects.
Then have an implementation has a first class object for each of the queries you are going to perform.
Here's a fairly contrived example but I hope it gives you an idea.
public interface ISpecification<T>
{
Expression<Func<T, bool>> Predicate { get; }
}
public class ActiveCustomersSpecification : ISpecification<Customer>
{
private Expression<Func<Customer, bool>> predicate;
public ActiveCustomersSpecification()
{
predicate = c => c.IsActive;
}
#region ISpecicfication<Customer> Members
public Expression<Func<Customer, bool>> Predicate
{
get { return predicate; }
}
#endregion
}
public interface IQueryRepository<T>
{
IQueryable<T> GetQuery(ISpecification<T> specification);
IEnumerable<T> FindAllBy(ISpecification<T> specification);
}
public class CustomerDtoAssembler
{
public CustomerDto AssembleFrom(Customer customer)
{
var customerDto = new CustomerDto
{
Id = customer.Id
};
return customerDto;
}
}
I think willbt has given you a really good starting point.
I would add that if you do opt to continue to use the ORM as the data-access strategy for queries you would be well-advised to consider defining a fetching strategy tailored to the data you expect you'll need to access (I'm thinking specifically about NHibernate here, by the way). What this means is you can decide whether to lazy-load or to eager-load the objects and collections associated with a particular Aggregate Root object.
The NCommon project by Ritesh Rao offers an excellent (work in progress) demonstration of how to define a different fetching strategy for different purposes.
Ritesh explains it really well in his blog.
Go ahead and have a look at the source:
here's the IFetchingStrategy interface
and this shows the use of fetching strategies in a unit test
In the test 'Repository_For_Uses_Registered_Fetching_Strategies' the call to
NHRepository<Order>().For<NHRepositoryTests>()
...causes the fetching strategies registered against the NHRepositoryTests class to be used, and therefore the OrderItems and Products will be eager loaded without messing about with NHibernate mapping configurations.

Resources