I am able to add messages to local MSMQ using nservicebus by below code
var endpointConfiguration = new EndpointConfiguration("Samples.Msmq.Simple");
var transport = endpointConfiguration.UseTransport<MsmqTransport>();
endpointConfiguration.SendFailedMessagesTo("error");
endpointConfiguration.EnableInstallers();
endpointConfiguration.UsePersistence<InMemoryPersistence>();
var endpointInstance = await Endpoint.Start(endpointConfiguration)
.ConfigureAwait(false);
var myMessage = new MyMessage();
await endpointInstance.SendLocal(myMessage)
.ConfigureAwait(false);
But I read at some places that I can send messages to remote MSMQ, see code below
FormatName:Direct=TCP:100.100.100.12\\private$\\remoteTxn
But I am not able to figure how to send to Remote MSMQ using Nservicebus. Anyone can pitch here?
Instead of using SendLocal you need to either use Send in case of a command or Publish in case of an event.
Using Send means you need to have message routing in place, as that determines what is the destination of the message. Routing could be defined using code, or other means like external files which makes it easier for dev/ops to change the routes at runtime in future.
An overload of the Send method also accepts a destination endpoint, but it is recommended to not mix concerns and keep the routing code separate (hence not using the overload with the destination). More info here.
Related
I'm exposing an API to a vendor where that vendor requires the API to be synchronous. I however would like to use NServiceBus on the backend of it to make good use of our other architecture.
Is there a product/framework that can be used to do support this flow?
Are there any thoughts/considerations in choosing this approach?
The API is as said synchronous where we will transform the request a bit and then put it on an NServiceBus queue for further processing by other systems.
After the message has been sent to a queue we should wait for the other system to complete its actions and be woken up again when the reply message is received.
Pseudo code:
void APICall(String someMessage) {
var msgBusMessage = new { json = someMessage, ID = Guid.NewID() };
NServiceBus.EnqueueMessage(msgBusMessage);
var returnMessage = NServiceBus.WaitForReplyMessageWithID(msgBusMessage.ID);
return returnMessage;
}
NServiceBus has a feature called Callbacks which is designed to handle this type of interaction. It works almost exactly like the snippet you have provided. You send a request via NServiceBus and then get a Task that will eventually contain the response. You can await that task and return the result to the synchronous API.
To set it up:
Add a reference to the NServiceBus.Callbacks package (in both the sender and the receiver endpoints)
Enable callbacks by calling endpointConfiguration.EnableCallbacks(). If an endpoint returns replies but does not request request synchronous callbacks then you should use endpointConfiguration.EnableCallbacks(makesRequests: false)
Any endpoint that makes callback requests should be made Uniquely Addressable endpointConfiguration.MakeInstanceUniquelyAddressable(someUniqueIdThatSurvivesRestarts). This allows the response message to be routed to the specific endpoint instance that is waiting for it.
In the caller, use the following var response = await endpoint.Request<ResponseMessage>(new RequestMessage { ... })
In the receiver create a handler for RequestMessage and return context.Reply(new ResponseMessage {...})
You can read more about this feature (including some caveats around when you should and shouldn't use it) in the documentation. There is also a sample showing the feature in use.
I have some performance issue on using websockets on ASP.NET Core 2.1
At first, I have an implementation of websockets similar to this example:
https://radu-matei.com/blog/aspnet-core-websockets-middleware/
On every incoming websocket message, I have it to parse, call some services, send a message back to websocket.
if (result.MessageType == WebSocketMessageType.Text)
{
using (var scope = service.CreateScope())
{
var communicationService = scope.ServiceProvider.GetSomeService();
await communicationService.HandleConnection(webSocket, result, buffer);
}
}
So as you see on every incoming message I am creating a new Scope, getting Service provider and then calling services on this service's method communicationService.HandleConnection. But if there is a lot of messages, my Azure WebService CPU goes up to 100%.
Can someone tell me if I am using these scope creations correct on every socket message?
It's hard to know for certain with the limited code snippet you provided (i.e. the lifetime and type of communicationService. Having said that, I would look at https://learn.microsoft.com/en-us/azure/app-service/faq-availability-performance-application-issues to capture a snapshot of your app service when the CPU spike to 100%. You may discover the issue might be unrelated to your using (scope).
Just getting my head around message queues and Redis MQ, excellent framework.
I understand that you have to use .RegisterHandler(...) to determine which handler will process the type of message/event that is in the message queue.
So if I have EventA, EventB etc should I have one Service which handles each of those Events, like :
public class DomainService : Service {
public object Any(EventA eventA) {...}
public object Any(EventB eventA) {...}
}
So these should be only queue/redis list created?
Also, what If I want a chain of events to happen, so for example a message of type EventA also has a handler that sends an Email providing handlers earlier on the chain are successful?
ServiceStack has no distinction between services created for MQ's, REST, HTML or SOAP services, they're the same thing. i.e. they each accept a Request DTO and optionally return a Response DTO and the same service can handle calls from any endpoint or format, e.g HTML, REST, SOAP or MQ.
Refer to ServiceStack's Architecture diagram to see how MQ fits in.
Limitations
The only things you need to keep in mind are:
Like SOAP, MQ's only support 1 Verb so your methods need to be named Post or Any
Only Action Filters are executed (i.e. not Global or Attribute filters)
You get MqRequest and MqResponse stubs in place of IHttpRequest, IHttpResponse. You can still use .Items to pass data through the request pipeline but any HTTP actions like setting cookies or HTTP Headers are benign
Configuring a Redis MQ Host
The MQ Host itself is completely decoupled from the rest of the ServiceStack framework, who doesn't know the MQ exists until you pass the message into ServiceStack yourself, which is commonly done inside your registered handler, e.g:
var redisFactory = new PooledRedisClientManager("localhost:6379");
var mqHost = new RedisMqServer(redisFactory, retryCount:2);
mqHost.RegisterHandler<Hello>(m => {
return this.ServiceController.ExecuteMessage(m);
});
//shorter version:
//mqHost.RegisterHandler<Hello>(ServiceController.ExecuteMessage);
mqHost.Start(); //Starts listening for messages
In your RegisterHandler<T> you specify the type of Request you want it to listen for.
By default you can only Register a single handler for each message and in ServiceStack a Request is tied to a known Service implementation, in the case of MQ's it's looking for a method signature first matching: Post(Hello) and if that doesn't exist it looks for the fallback Any(Hello).
Can add multiple handlers per message yourself
If you want to invoke multiple handlers then you would just maintain your own List<Handler> and just go through and execute them all when a request comes in.
Calling different services
If you want to call a different service, just translate it to a different Request DTO and pass that to the ServiceController instead.
When a MQ Request is sent by anyone, e.g:
mqClient.Publish(new Hello { Name = "Client" });
Your handler is invoked with an instance of type IMessage where the Request DTO is contained in the Body property. At that point you can choose to discard the message, validate it or alter it.
MQ Requests are the same as any other Service requests
In most cases you would typically just forward the message on to the ServiceController to process, the implementation of which is:
public object ExecuteMessage<T>(IMessage<T> mqMsg)
{
return Execute(mqMsg.Body, new MqRequestContext(this.Resolver, mqMsg));
}
The implementation just extracts the Request DTO from the mqMsg.Body and processes that message as a normal service being passed a C# Request DTO from that point on, with a MqRequestContext that contains the MQ IHttpRequest, IHttpResponse stubs.
I have both ends of a bi-directional connected Stream, which I want to do some communication over. The underlying implementation behind the stream isn't important, I want to work at the Stream level...
Rather than implement my own communications protocol for the stream, I want to use all of the existing WCF goodness to wrap the existing stream with with a bi-directional (request/response + callback) WCF communications channel.
My question is, how can I go about doing this...?
UPDATE:
I've gone down the path of implementing a custom transport. I've got this working, but I'm still not totally happy with it...
I've implemented an IDuplexSessionChannel to wrap the stream, along with appropriate IChannelFactory and IChannelListener, and a Binding Element for creating the channel factories. Now, I just pass through the connected stream, and eventually pass these into the transport channel when it is created.
So, I can create the client proxy for accessing the service via the stream as follows:
var callback = new MyCallback();
var instanceContext = new InstanceContext( callback );
var pipeFactory = new DuplexChannelFactory<IMyService>( instanceContext, new StreamBinding(clientStream),
new EndpointAddress("stream://localhost/MyService"));
var serviceProxy = pipeFactory.CreateChannel();
The problem I have is, it seems WCF is set on using a ServiceHost to create the server end of the channel, via a IChannelListener. In my case, I already have a connected stream, and I won't be able to listen for any more incoming connections. I can work around this, but I'd much rather not use a ServiceHost to create the server end of the channel, because I end up with a lot of obscure boilerplate and hacks to make it work.
Questions
I'm looking, therefore, for a better way to take the IDuplexSessionChannels, and wrap these into a Channel proxy at both the server and client ends.
Or maybe a different ServiceHost implementation that doesn't require a IChannelListener.
Really, the problem here is I don't want a single server, multiple client arrangement, I have a 1-1 relationship between my WCF Service and the client. Is there a correct way to instantiate one of these?
To put it yet another way, I want to create the Server-side service instance without using a ServiceHost.
Any suggestions would be appreciated at this stage.
Use a client at both ends. You will need to define your contracts carefully though. If you have ClientA and ClientB at either end of the stream, when ClientA sends a request, ClientB will expect it to look like what it sees as it's defined callback contract and vice versa.
I have a client app and a server app.
The client calls a wcf service and passes machine information
to server , based on the machine name the server calls back a wcf service on client side.
So to achieve this , I am just changing the EndPointAddress but then it's throwing
NoEndPointFoundException , how can i fix it , below is the code :
public void RegisterTasks(MachineConfig machineInfo)
{
string add = exeProxy.Endpoint.Address.Uri.Scheme + "://" + machineInfo.MachineName.Trim()+"/"
+ exeProxy.Endpoint.Address.Uri.Segments[1];
Uri uri = new Uri(add);
EndpointAddress eadd = new EndpointAddress(add);
WSHttpBinding whttpBinding = new WSHttpBinding(SecurityMode.None);
//ServiceReference1.ExecuteTaskClient newProxy = new ExecuteTaskClient(whttpBinding , eadd);
//EndpointAddress endPointAddress = ;
exeProxy.Endpoint.Address = eadd;
//exeProxy.Endpoint.Binding = new System.ServiceModel.BasicHttpBinding("httpBinding");
// we just execute the task by
// calling the wcf service on client side
foreach (Task task in machineInfo.Tasks)
{
exeProxy.ExecuteTask(task.TaskID);
// newProxy.ExecuteTask(task.TaskID);
}
}
I am assuming that you are getting EndpointNotFoundException not NoEndPointFoundException. I could not find a reference to NoEndPointFoundException.
http://msdn.microsoft.com/en-us/library/system.servicemodel.endpointnotfoundexception.aspx
What this is saying is that the client cannot find the server. In your case the server is trying to call back to the client, so the roles are reversed.
There are two things that could be wrong:
the url that you have in the variable "add" is incorrect (try logging the value)
the wcf service on the client side is not listening on the correct url (try putting the url in a browser)
Hope this helps
Shiraz
My first impression is that your design should be reconsidered. Any time I see an ingenious (read: bizarre) solution I see a whole heap of head banging in the making.
So firstly, write out what it is that you are trying to acheive in baby speak: "I want client to be contacted when server has new data." and then think about how it can be acheived using more conventional techniques.
Check out the duplex bindings - and polling a stateful singleton is not always a bad idea if you're not scaling into thousands of clients -- in fact, I bet it'd scale better than your current design.
But, to solve your current design issue, I'd setup the client (which will become the server) with the MEX endpoint (mexHttpBinding) and then set it off so its listening, then use VS (an empty project or from the server project) to try and connect to the client(server) by way of Add Service Reference and supplying the local machine name etc. This alone might turn up your problem. Then once added, you can use the autogen app.config to know what settings you need.
Also, have you considered how the server will be able to call the client if the server doesn't have the proxy classes setup?
It does sound like you're making a rod for your own back.