Handling two events sequentially in Axon - rabbitmq

Can I put a sequence between (or execute with certain time gap) two events to be handled sequentially
in axon. Both the events are created at same time. Below are the sample events.
As my second event depends on the execution results of first one. I am using RabbitMq to publish for messaging.
#EventHandler
public void handleEvent1(Event1 event) {
LOG.debug("An event of type {}, occured.", event.getClass().getName());
}
#EventHandler
public void handleEvent2(Event2 event) {
LOG.debug("An event of type {}, occured.", event.getClass().getName());
}

Would you mind elaborating on the use case where you need this for?
I have an answer ready for your question, but maybe I can suggest a different course of action based on the scenario you need this in.
Events will be handled in the order they've been given to the message source you use.
From an EventStore, that would mean you will receive the events in the global index order of each of the events. The globalIndex is a field on each EventMessage used to denote it's order in the entire event store.
When using AMQP/RabbitMQ as the message source a similar ordering holds. Which ever event is earlier on the queue will be handled firstly on the consuming side.
If you thus want Event1 to be handled prior to Event2, then it'll need to be published prior to the other. Control over the publication order is thus key if you require a guaranteed order. Axon doesn't provide handles to adjust the handling order of events, as it's far more ideal if your system doesn't rely on the event order directly. The handling component should stand on it's own, not making assumptions on the matter.
Hope this helps you out Amit!

Related

Lync 2013 UCMA WCF Web Service

What I want to do is create a WCF service just to get the availability of a user. I have gone through the following quick-start example:
Name: SubscribePresence
http://msdn.microsoft.com/en-us/library/office/dn454835(v=office.15).aspx
I have managed to do this but i feel that its not the most efficient way to just get a users availability.
At the moment I create a end point subscribe to a users presence and wait for the response to come back and from that i get the users availability. (I'm simplifying this down).
What I would ideally like though is just to quickly get a users availability without subscribing to a users presence and close the connection as soon as i have retrieved the availability.
I was wondering if anyone knows of an example that i can have a look at or that they have implemented themselves
any advice would be appreciated
You can also do a one-time presence query. From MSDN:
If a one-time presence query to a remote presentity is desired, creating a view and tearing it down is a suboptimal solution for an application. In addition, the application needs to wait and track whether all presence information has been received.
An alternative is to use the BeginPresenceQuery(IEnumerable<String>, [], EventHandler<RemotePresentitiesNotificationEventArgs>, AsyncCallback, Object) and EndPresenceQuery(IAsyncResult) methods on the endpoint’s PresenceServices property.
See http://msdn.microsoft.com/en-us/library/office/hh383136%28v=office.14%29.aspx
Example
You can call the presence query like this. The null argument on 3rd position is the event handler which will fire when presence is recieved, it's not required since we process the results of the EndPresenceQuery instead. You could also pass an eventhandler and not care about the results of the EndPresenceQuery, thats up to you.
endpoint.PresenceServices.BeginPresenceQuery(
new[] { "sip:user#example.com" }, // Collection of sip addresses to query
new[] { "state" }, // Collection of presence catrgories to query
null, // The eventhandler to call when presence is recieved
(ar) => {
var result = endpoint.PresenceServices.EndPresenceQuery(ar);
// process the recieved containers in 'result' here.
},
null); // The state object
However, when you run a WCF service for presence which will be queried multiple times, I would say it might be better to subscribe to presence than to do single queries every time. I build a similar system once with the following logic:
Get an incoming presence request on WCF.
If this SIP uri presence is known to the WCF service (is subscribed), return immediately the cached presence.
If it is not known, subscribe to the presence.
When presence is recieved, return the result and add the presence to the cache.
Any time a subscribed user updates their presence, an event is fired to update the cache.
If no presence queries are recieved for a single user for a certain period of time, unsubscribe from the presence and remove from cache.
The main advantage here is that for multiple subsequent queries for the same user's presence, you do not query the Lync server each time. Your service responses will be a lot faster, and you get presence pushed rather than having to poll for it each time.

CacheEntryCreated event--again

Cross posted from JBoss Infinispan Discussions
I'm trying to implement some code that takes actions whenever an entry is created in one of my Infinispan caches. I realized quickly that the CacheEntryCreatedEvent object delieved to my #CacheEntryCreated method does not contain the newly created entry so I went searching for a solution.
I found various discussions about the problem with the solution being to catch the #CacheEntryModified event that is delivered after the #CacheEntryCreated event and take the object when the isPre()=false. However, I think I missed something because in all the disucssions none address the situation where you have a modification event that represent a elgitimate modification of an existing entry and not a creation.
Does this mean that my #Listener object has to maintain state information between the delivery of events? My #CacheEntryModified has to integate the event object, determine its a create event (i.e. getValue() == null && isPre() == true) and then wait for the next #CacheEntryModified event before grabbing the newly created object?
This bring up the obvious question of what to do if another #Listener object vetoes the modification before the second #CacheEntryModified (i.e. isPre() == false) event is delivered?
How do other peopel handle this situation?
I suppose the best way to do it now is with a ThreadLocal in your listener.
The future 5.3.0 release will improve this a lot, CacheEntryCreatedEvent will have a getValue() method and CacheEntryModifiedEvent will have a isCreated() method: https://github.com/infinispan/infinispan/commit/1aa2554e1c5ea46318402975de946f2e9ea44442#diff-22

How to use interface as events in CommonDomain and NEventStore?

I'm conducting a test using JOlivers CommonDomain and EventStore with NServiceBus. I need to raise an event in my Aggregate like this:
RaiseEvent(bus.CreateInstance<IPhoneNumberChanged>(m => { m.Number = number; }));
And then later i have this handler:
private void Apply(IPhoneNumberChanged phoneNumberChangedEvent)
{
this.Number = phoneNumberChangedEvent.Number;
}
Unfortunately this doesn't work. I get an exception: "CommonDomain.Core.HandlerForDomainEventNotFoundException: Aggregate of type 'Phone' raised an event of type 'IPhoneNumberChanged' but not handler could be found to handle the message.".
The problem here is the object created from "bus.CreateInstance" since it works with pure concrete classes. But I need my events as interfaces. Can this be solved?
EDIT: Just a note - I don't have to use "bus.CreateInstance" to create the object, it's just the easiest (only) way I currently have to raise the 'IPhoneNumberChanged'. Any other way would also be great - just as long as I have an interface as argument in the handler.
In your constructor for your Phone aggregate, simply add the following:
this.Register<IPhoneNumberChanged>(this.Apply);
That will take care of the exception. The default internal routing mechanism inside of the CommonDomain is a registration-based router than understands how to get an event to the appropriate Handle method--all without using reflection. Another router has been written and is already part of the CommonDomain project which uses reflection and is more convention based.
One quick thought regarding your event name. Rather than saying that the phone number changed, you may want the event to indicate why the phone number changed. From a domain perspective, the why of something is always more interesting and important that the what. The fact that a phone number changed usually isn't interesting. The fact that it changed because the person moved or cancelled their account or whatever--that's interesting and very likely important as well.

Ncqrs recreate the complete ReadModel

Using Ncqrs, is there a way to replay every single event ever happened (all aggregate types) and feed these through my denormalizers in order to recreate the whole read model from scratch?
Edit:
I though it's be good to provide a more specific use case. I'm building this inside a ASP.NET MVC application and using Entity Framework (Code first) for working with the read models. In order to speed up development (and because I'm lazy), I want to use a database initializer that recreates the database schemas once any read model changes. Then using the initializer's seed method to repopulate them.
There is unfortunately nothing built in to do this for you (though I haven't updated the version of ncqrs I use in quite a while so perhaps that's changed). It is also somewhat non-trivial to do it since it depends on exactly what you want to do.
The way I would do it (up to this point I have not had a need) would be to:
Call to the event store to get all relevant events
Depending on what you are doing this could be all events or just the events for one aggregate root, or a subset of events for one or more aggregate roots.
Re-create the read-model in memory from scratch (to save slow and unnecessary writing)
Store the re-created read-model in place of the existing one
Call to the event store one more time to get any events that may have been missed
Repeat until there are no new events being returned
One thing to note, if you are recreating the entire read-model database from scratch I would off-line the service temporarily or queue up new events until you finish.
Again there are different ways you could approach this problem, your architecture and scenarios will probably dictate how best to do it.
We use a MsSqlServerEventStore, to replay all the events I implemented the following code:
var myEventBus = NcqrsEnvironment.Get<IEventBus>();
if (myEventBus == null) throw new Exception("EventBus is not found in NcqesEnvironment");
var myEventStore = NcqrsEnvironment.Get<IEventStore>() as MsSqlServerEventStore;
if (myEventStore == null) throw new Exception("MsSqlServerEventStore is not found in NcqesEnvironment");
var myEvents = myEventStore.GetEventsAfter(GetFirstEventIdFromEventStore(), int.MaxValue);
myEventBus.Publish(myEvents);
This will push all the events on the eventbus and the denormalizers will process all the events. The function GetFirstEventIdFromEventStore just queries the eventstore and returns the first Id from the eventstore (where SequentialId = 1)
What I ended up doing is the following. At the service startup, before any commands are being processed, if the read model has changed, I throw it away and recreate it from scratch by processing all past events in my denormalizers. This is done in the database initializer's seed method.
This was a trivial task using the MS SQL event storage as there was a method for retrieving all events. However, I'm not sure about other event storages.

Use Dojo's Publish Subscribe Model

We are working on a portal environment. On one of our page we have two portlets. When some action happens on one portlet, we have to minimize the other portlet and viceversa.
So we feel that this is a suitable situation where we can use Dojo's publish/subscribe model. But I'm a bit confused if I need to use different topics [One when some action happens on Portlet A, and the second topic when some action occurs on PortletB] or one topic [something like minimize]. Can someone please guide me.
This is really up to you, and depends on your needs.
Topics are free-form texts, so you can arrange it in any text format you like.
My own experiences have been to treat a topic as an "event". Therefore, one topic, one event.
My experience has also been that it is tremendous beneficial to implement "commands" in the same system as events -- so you have a universal command/event system.
Events (therefore topics) do not have to correspond to your portlets. For instance, one portlet can have multiple events (if they make sense), or one event can be shared by multiple portlets (for shared functionalities or for cross-portlet communcations).
Parameters and data can be passed with the event (i.e. topic) as arguments.
Now, a good trick I've learnt is to have "sub-topics" -- i.e. topics that are prefixed with an parent topic, when things want to subscribe to a particular instance of event.
Example: Assume we have an event called "/portlets/showhide" which is published by any portlet when it is shown or hidden, together with the id of the portlet and a boolean variable indicating whether it is shown or hidden.
Now, assume that a portlet will also publish topics called "/portlets/showhide/{id}" (with true/false argument) and "/portlets/showhide/{id}/show" (no arguments) when shown, together with the generic "/portlets/showhide" topic (event).
Now assume some handler object is really only interested when the "xyz" portlet is hidden. It doesn't have to subscribe to "/portlets/showhide" and listen to all those events of other portlets that it is not interested in. It can simply subscribe to "/portlets/showhide/xyz/hide". When number of subscriptions increase in a large system, this kind of optimizations can come in quite handy.
You can use one topic in which pass additional parameters. Something like this:
// PortletA
dojo.publish("onPortletAction", [{sender: "PortletA"}]);
// PortletB
dojo.publish("onPortletAction", [{sender: "PortletB"}]);
....
dojo.subscribe("onPortletAction", dojo.hitch(window, window.processAction));
window.processAction = function(data) {
if (data.sender == "PortletA"){
//to do something
}
if (data.sender == "PortletB") {
//to do something
}
}