NServiceBus message timeout with timeToReachQueue - msmq

I'm trying to set a timeout for a message to arrive to a queue using MSMQTransportProtocol in NServiceBus.
I've read this: http://docs.particular.net/nservicebus/msmq/connection-strings and trying to implement timeToReachQueue property (from my understanding).
What I did is to add a TimeToReachQueue property to my message:
public class PlaceOrder : IMessage
{
[MessagingDescription("MsgTimeToReachQueue")]
public TimeSpan TimeToReachQueue { get; set; }
public Guid Id { get; set; }
public string Product { get; set; }
}
In the client that sends the message I have placed the following in app.config:
<connectionStrings>
<add name="NServiceBus/Transport"
connectionString="deadLetter=true;
journal=true;
useTransactionalQueues=true;
cacheSendConnection=true;
timeToReachQueue=01:01:01"/>
</connectionStrings>
I have tried different time stamps values - basically I'm trying to an impossible time for the message to arrive - I'm purposely want it to time out.
But whatever value I set in the the connection string it doesn't seem to apply. Message always arrives successfully, and if I check the timeToReachQueue property in debug, I see that all the values are zero - not the value I try to set.
I even tried the following in my EndpointConfig:
configuration.UseTransport<MsmqTransport>().ConnectionStringName("NServiceBus/Transport");
What am I missing here?

I'm trying to set a timeout for a message to arrive to a queue
The thing is that even if the message arrives at the queue within that timeframe (due to network issues) it could very well end up sitting in that queue for a long time (potentially due to the processing code being down).
I think that TimeToBeReceived is what you're looking for. See this previous thread:
NServiceBus setting time to be received
What the documentation is talking about when it says This sets the underlying Message.TimeToReachQueue is the MSMQ message's TimeToReachQueue property (as is described in the link) rather than the property on your own message object.

Related

How to create a good PATCH endpoint when some properties can change and some can't based on the status of the resource?

Consider I have the following Resource:
public class Foo
{
public string Text {get; set;}
public int ReminderInDays {get; set;}
// Determined by resource itself
public FooStatus Status {get;set;}
}
Now, let's say we want to be able to update these. Normally, you could create a PATCH endpoint:
PATCH api/foos/1 with a body that contains both Text and ReminderInDays. (I do not use stuff like Jsonpatch where you can submit only the changed properties).
This would work fine. But how about the following scenario:
Text can change when Status is New and Submitted
ReminderInDays can change when Status is New
If I were to use my PATCH example, I could use a body like the following when status is New, and everything would be OK:
{
"Text": "Hello World!",
"ReminderInDays": 3
}
But if I were to use this when the status of the resource is Submitted and I would change ReminderInDays to 5, the Resource would throw an error because I am not allowed to change that property anymore. Based on this information, the only way I can think of having 1 endpoint to change both, is to ignore the ReminderInDays property when the Resource tells me the property can't be changed.
This seems like an ugly solution to me. You need to submit useless data to the API which is a waste.
Another solution is to have 2 endpoints:
PATCH api/foos/1/text
PATCH api/foos/1/reminderInDays
This isn't really RESTFUL, but would solve my issues.
Does anyone have any other ideas? What is the right thing to do :)?

WEB API 2 how to set Content-Type server side?

I have a customer that has a specific API design I am required to comply with. The logic I host with my WEB API code allows the customer to make simple changes to a resource that exists on my system (change, delete etc.).
The interface is very simple:
public IHttpActionResult Post(OpRequest opRequest)
public class OpRequest
{
public string op { get; set; }
public string data { get; set; }
}
Based on the value of "op", i parse "data" to complete the operation.
My question is related to the Content-type header in their request. They do not send a Content-Type header at all, but the actual data they POST is "application/x-www-form-urlencoded" for some requests and "application/json". for other requests. Works fine when they send urlencoded, but throws "415 unsupported media" error when they send JSON.
My thought is that I need to intercept their request, detect the content-type and set it before it reaches my logic, but I am not certain how to do that. I must use a single operation to accommodate all Content-types. Is this possible?

Event MyEvent has ID 2 which is already in use

I am implementing event tracing using EWT in a Service Fabric application and are faced with these errors
ERROR: Exception in Command Processing for EventSource MyCompany-ServiceFabricApplication-LiveDataReader: Event OnCommandMessageReceived has ID 2 which is already in use
The "OnCommandMessageReceived" is my custom event
[Event(2, Level = EventLevel.Verbose, Message = "Queue client created '{0}'")]
public void OnQueueClientCreated(string queueClientName)
{
if (IsEnabled())
{
WriteEvent(2, queueClientName);
}
}
I have multiple/many of these errors and I have tried to messing around with numbers but ...
Is there some Powershell command or else that can tell what IDs are in use or is there a safe range or something?
PS: When that event is fired i can see it in visual studio diagnostic events viewer but the Message is empty. It would be cool if it displayed the message from the payload. Is that possible?
ETW Events must have an unique ID per provider. So look if you have other events with ID 2 and change tie ID to a different value.

How do I access SOAP headers in a Spyne srpc method?

Forgive me if I am just being thick but the Spyne documentation on headers seems a bit thin and the link to the sample code is broken. I think I found the sample code here but it only seems to access the headers in a listener callback function. I need access to it in the srpc method if possible.
What I would like to do is something like this (this does not work):
class MyRequest(ComplexModel):
Messages = Array(Unicode)
class MyHeader(ComplexModel):
TrackingID = ByteArray
class MySoapService(ServiceBase):
#srpc(MyRequest, _in_header=MyHeader)
def PostMessages(req, hdr):
logging.info(u'RECEIVED: {0:s}'.format(hdr.TrackingID))
If it helps, I am trying to replace a service written in .NET that just defines the message headers in the message contract like this:
[MessageContract]
public class MyRequest
{
[MessageHeader]
public Guid TrackingID { get; set; }
[MessageBodyMember]
public String[] Messages { get; set; }
}
You can't read header data from within an srpc function. #srpc is for existing functions that you don't want to touch. You should always use #rpc unless you know you need #srpc
Decorate your function using #rpc. This passes the rpc context (conventionally named ctx) as first argument to your function. Then, ctx.in_header is where you'll find the header data. You can also set ctx.out_header to alter outgoing response headers.
Also, pull requests for docs are pure gold to me :)

Two big question marks about CQRS

I'm a C# developer but I read nearly every tutorial about cqrs out there, doesn't matter if the language was Java, because I want to learn the structure and base of cqrs.
But now I think, the fact that I read so much tutorials is the problem because there are differences in the tutorials and now I'm confused and don't know which technique I have to use.
Two main questions are running wild in my head and maybe some of you can bring some clarity in there.
On the command side, where should I place the logic to call my ORM for example?
Some tutorials do that in the command handler (what is more logic to me) and some do it in the event handlers which will be fired by the command handler which in that case do only validation logic.
For the event store and to undo thinks, which data do I have to save into the db, some tutorials save the aggregate and some save the event model.
I hope that someone can explain me what pattern to use and why, maybe both in different scenarios, I don't know.
An practical example would be great. (Only pseudo code)
Maybe a User registration, RegisterTheUser command:
Things to do:
Check if the username is already in use
Add user to db
Send confirmation mail (In command or in the UserIsRegistered event?)
Fire event ConfirmationMailSended or only UserIsRegistered event?
Kind regards
EDIT:
Here is my current implementation (Simple)
public class RegisterTheUser : ICommand
{
public String Login { get; set; }
public String Password { get; set; }
}
public class RegisterTheUserHandler : IHandleCommand<RegisterTheUser, AccountAggregate>
{
public void Handle(AccountAggregate agg, RegisterTheUser command)
{
if (agg.IsLoginAlreadyInUse(command.Login))
throw new LoginIsAlreadyInUse();
agg.AddUserAccount(command);
CommandBus.Execute<SendMail>(x => { });
EventBus.Raise<UserIsRegistred>(x => { x.Id = agg.UserAccount.Id; });
}
}
public class UserIsRegistred : IEvent
{
public Guid Id { get; set; }
}
public class AccountAggregate : AggregateBase
{
public AccountAggregate(IUnitOfWork uow)
{
UnitOfWork = uow;
}
private IUnitOfWork UnitOfWork { get; set; }
public UserAccount UserAccount { get; set; }
public void AddUserAccount(RegisterTheUser command)
{
UserAccount = new UserAccount
{
Id = Guid.NewGuid(),
IsAdmin = false,
Login = command.Login,
Password = Crypto.Sha512Encrypt(command.Password)
};
UnitOfWork.UserAccountRepository.Add(UserAccount);
UnitOfWork.Commit();
}
public Boolean IsLoginAlreadyInUse(String login)
{
var result = UnitOfWork.UserAccountRepository.SingleOrDefault(x => x.Login == login);
return (result != null);
}
}
So a number of questions, but I'll take a stab at answering.
On the command side, where should I place the logic to call my ORM for
example?
Having this logic either in the command handler or in your event handler, to me, really depends on the type of system you're building. If you have a fairly simple system, you can probably have your persistence logic in your event handlers, which receive events raised by your domain. The thinking here is that your commands handled by the command handler will already have the information needed and your command handler ends up being not much more than a router. If you need more complexity in your command handler, such as dealing with sagas, long running transactions, or some additional layer of validation, then your command handler will use your persistence layer here to pull out data (and perhaps write data) and then route the command to the proper domain or issue more commands or raise events. So I believe it really depends on the level of complexity you're dealing with.
I tend to favor simplicity over complexity when starting out, and would probably look at having that logic in the event handler to begin with. Move to the command handler if your system is more complex.
For the event store and to undo thinks, which data do I have to save
into the db, some tutorials save the aggregate and some save the event
model
I'm not exactly sure what you're asking here, but if you're asking what should be stored in your event store, then I think a simple solution is the aggregate id, the aggregate type, the event with data (serialized) and the event type. Off the top of my head, that's probably the bare bones of what you'd need: based on the aggregate id you're working with, get all the events for that aggregate (in order raised) and then replay them to rebuild the aggregate. I don't think you need to save the aggregate unless there's some compelling reason to (which is always possible).
As for your request for a practical example and the steps you laid out, that's probably a question in and of itself, but my thoughts on that are:
Check if the user name is already in use
Depending on your application, you may want to do this from the read side in your controller (or whichever layer is raising commands) before you issue a command. Validate at that point, but you'd probably want to validate again before persisting it. You could do that in your event handler where it would probably catch an exception because you're violating a unique index in your database.
Add user to DB
Again, my thought is keep it simple and handle it in your event handler, since your domain is raising a UserIsRegistered event.
Send confirmation email
Your domain could raise the UserIsRegistered event and a second event handler (EmailHandler) would also subscribe to that event and send out the email.
ConfirmationMailSent event could be raised by the event handler, added to the event queue and handled accordingly. I guess I'm not sure what you want to happen here.
But, hopefully this helps a bit.