reply does not work in nservicebus - nservicebus

guys
I'm trying to send message to server and get response on client side, also I'm trying to publish another message on server using the same endpoint.
I don't get response on client side, but subscribers get published messages with success
Server side code:
if (!someCondition)
{
_bus.Reply(new BookingStatus(message, Status.Occupied));
}
else
{
_bus.Reply(new BookingStatus(message, Status.Ok));
_bus.Publish(new RoomBooked(message, Guid.NewGuid()));
//some logic
}
Code for config bus:
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("NServiceBusDemo");
busConfiguration.UseTransport<MsmqTransport>();
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.EnableInstallers();
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.AutoSubscribe();
DefaultFactory defaultFactory = LogManager.Use<DefaultFactory>();
defaultFactory.Directory(#"..\..\..\logs");
defaultFactory.Level(LogLevel.Warn);
var bus = Bus.Create(busConfiguration);
return bus;

Related

Consume MassTransit Message in Grpc Service

I have a GRPC Service using protobuf-net.Grpc where I use Server Streaming to send messages back to the client. I'm using Azure App Services, so I thought I would use an Azure Service Bus and Mass Transit to wait for messages/events and send them back to the client.
public async IAsyncEnumerable<TestResult> SubscribeAsync([EnumeratorCancellation] CancellationToken cancel)
{
while (!cancel.IsCancellationRequested)
{
// wait for new mass transit message
yield return new TestResult { Result = MessageContent };
}
}
Is something like this even possible using mass transit, or would I need some kind of observable queue.

Socket.io rooms is not getting message

I have two file in a nodejs- express application
first.pug
var socket = io.connect('//'+document.location.hostname+':'+document.location.port, {
query: {
token: "XXXXXX"
}
});
socket.on('connect', (s) => {
console.log('connected!');
socket.emit('join123', 'room1');
});
second.pug
var socket = io.connect('//'+document.location.hostname+':'+document.location.port, {
query: {
token: "XXXXXX"
}
});
socket.on('join123', function (data) {
console.log("join.group========================"+data);
});
Nodejs Server side
io.on('connection', (socket) => {
console.log('a user connected');
socket.join('join123');
});
I dont see any message in second.pug when a message is pulished from first.pug
The socket.io connection made by second.pug never receives a message because your server never sends it a message.
Here's what first.pug does:
It creates a socket.io connection to your server.
When that connection succeeds, it sends a join123 message to that server.
Here's what your socket.io server does:
It listens for connecting clients.
When a client connects, it puts that client into the join123 room.
No messages are sent out to any of the connected clients.
Note: there is no listener on the server for the join123 message that the client sent so likely something is wrong there.
Here's what second.pug does:
It create a socket.io connection to your server.
It listens for a join123 message to be sent to it.
But, nothing ever sends a join123 message to second.pug, so second.pug never receives that message. first.pug sends a join123 message to your server, but the server never sends that to anyone else. The act of doing socket.join('join123') does not cause any messages to be sent. It just adds the socket to a room by that name. If you want the second.pug to get a join123 message, you would have to write code on your server that actually sends that message either to all connections or somehow just to the second.pug connection.

use socket.io in express best practice

I'm doing a system using expressjs + socket.io(with SessionSocket plugin) + mongoosejs.
The server was build like this:
var mongoose = require('mongoose'),
connect = require('connect'),
express = require('express'),
http = require('http'),
io = require('socket.io');
// hold cookieParser and sessionStore for SessionSocket
var cookieParser = express.cookieParser('your secret sauce'),
sessionStore = new connect.middleware.session.MemoryStore();
// create express server
var app = express();
// config express server
require('./config/express')(app, config, cookieParser, sessionStore);
// Express3 requires a http.Server to attach socke.io
var server = http.createServer(app);
// attach socket.io
var sio = io.listen(server);
sio.set('log level', 2);
// create SessionSocket
var SessionSockets = require('session.socket.io'),
sessionSockets = new SessionSockets(sio, sessionStore, cookieParser);
// setup SessionSocket
sessionSockets.on('connection', function(err, socket, session) {
socket.join(session.user._id);
socket.emit('message', {
title: "welcome",
msg: "welcome to selink"
});
});
// config express server route
app.get('/some-action', **SomeMongooseFunction**);
// start server
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In the express route handler("SomeMongooseFunction", defined in other file), after processed user action(query, modify DB etc.), I want sent a real-time notification to the user or other online user. so I thing I must pass "sio" object into the "SomeMongooseFunction", the example above has only one route, but actually I have dozens of routes, It gonna looks ugly if I do so.
or in the setup SessionSocket part, I think could paste the sio into the user's session. but, I'm not sure this way is right or not.
so, is there any other way to get sio reference in the express handler? (it will be nice if I can refer sio like a global variable, but global is evil...)
thanks for any ideas.
You're storing user ID from session into Socket.IO rooms manager. Now you have somehow get the target's user ID
and send the event message for this user.
For your case, you are using notification entity so lets do it:
//client side - send a notification for a specific user.
var note = {
from: userID, //sender
target: id, //receiver
type: type //type of notification
}
socket.emit('notification', note);
target field is the target user ID, this user will receive the notification status.
type here is just for illustrate if you wanna to handle more than one type of notifications.
socket.emit('notification', note); this part is the most important one. It will send the note JSON object
to notification event. This event must be registered on you server side Socket.IO page;
//server side - receive JSON data on notification event
socket.on('notification', function(data) {
io.sockets.in(data.target).emit('notification', data);
});
NOTE: I use 'io' instead of 'sio'.
notification event is registered and will catch all client messages directed to it. data is the
JSON object we sent before, so io.sockets.in().emit()
Once again on client. We must catch all notification event.
//client side - the final destination
socket.on('notification', function(data) {
//DO SOME JQUERY STUFF TO ALERT THIS TARGET USER FROM THE MESSAGE RECEIVED.
console.log("User: " + data.from + " sent you this notification");
});
The steps we can conclude are:
Sender user sends a message for notification event on server-side that contains target user
Server gets the message and now knows which event and target must be receive the message.
Server sends the message to the correct target on specified socket.io event.
You can use this analogy for any case you have to send Socket.IO messages for a specific user.

GCM server side implementation for java

I need to implement a standalone application for the server side of gcm to push notifications to the device. Is there any reference i could get other than the one on the Getting started page.People say something about xmpp. Do we need to use this or can we directly use the gcm server side methods.Help.Or is there any other easy way to implement this.I hope i put my question properly.
Here is nice tutorial for GCM server side implementation for java.
URL: java gcm server side implementation
Example code: java gcm server side implementation`{
new Thread(){
public void run(){
try {
//Please add here your project API key: "Key for browser apps (with referers)".
//If you added "API key Key for server apps (with IP locking)" or "Key for Android apps (with certificates)" here
//then you may get error responses.
Sender sender = new Sender("AIzaSyB7Ej255tpTaemk_-Ljmn4GcklldT14Hp4");
// use this to send message with payload data
Message message = new Message.Builder()
.collapseKey("message")
.timeToLive(3)
.delayWhileIdle(true)
.addData("message", "Welcome to Push Notifications") //you can get this message on client side app
.build();
//Use this code to send notification message to a single device
Result result = sender.send(message,
"APA91bEbKqwTbvvRuc24vAYljcrhslOw-jXBqozgH8C2OB3H8R7U00NbIf1xp151ptweX9VkZXyHMik022cNrEETm7eM0Z2JnFksWEw1niJ2sQfU3BjQGiGMq8KsaQ7E0jpz8YKJNbzkTYotLfmertE3K7RsJ1_hAA",
1);
System.out.println("Message Result: "+result.toString()); //Print message result on console
//Use this code to send notification message to multiple devices
ArrayList<String> devicesList = new ArrayList<String>();
//add your devices RegisterationID, one for each device
devicesList.add("APA91bEbKqwTbvvRuc24vAYljcrhslOw-jXBqozgH8C2OB3H8R7U00NbIf1xp151ptweX9VkZXyHMik022cNrEETm7eM0Z2JnFksWEw1niJ2sQfU3BjQGiGMq8KsaQ7E0jpz8YKJNbzkTYotLfmertE3K7RsJ1_hAA");
devicesList.add("APA91bEVcqKmPnESzgnGpEstHHymcpOwv52THv6u6u2Rl-PaMI4mU3Wkb9bZtuHp4NLs4snBl7aXXVkNn-IPEInGO2jEBnBI_oKEdrEoTo9BpY0i6a0QHeq8LDZd_XRzGRSv_R0rjzzZ1b6jXY60QqAI4P3PL79hMg");
//Use this code for multicast messages
MulticastResult multicastResult = sender.send(message, devicesList, 0);
System.out.println("Message Result: "+multicastResult.toString());//Print multicast message result on console
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}`
The simplest way to implement GCM server side for Java is using restful POST.
URL: "https://android.googleapis.com/gcm/send"
Example code: using scribe framework as consumer
public void pushToAndroidDevice(String deviceToken, String data) {
OAuthRequest request = new OAuthRequest(Verb.POST, "https://android.googleapis.com/gcm/send");
request.addHeader("Authorization", "key=" + apiKey);
request.addHeader("Content-Type", "application/json");
request.addPayload(data);
Response response = request.send();
}
There are 2 ways you can implement server for GCM connections
1) XMPP
2) HTTP
The difference being XMPP allow you to get response back from device to server(Bidirectional) and HTTP is (Unidirectional) for GCM, you can only send push notification to device.
In case you need the full implementation of Java Client and HTTP server, here is the link
GCM Client and Server

Cross domain policy file over net.tcp for WCF servicehost and Silverlight 5

I have a locally hosted WCF service and a silverlight 5 app that communicates with it. By default silverlight tries to obtain the cross domain policy file over HTTP when making calls to the WCF service. I need to change this so that the policy file is served over net.tcp port 943 instead.
I have setup a local tcp listener that serves up the policy file over port 943 and i have followed this technique whereby i make a dummy socket connection in order to obtain the policy file over tcp as it is only retrieved once per application lifetime. The tcp server is being hit as expected and i am getting SocketError property value as Success (though i must note, the first time i hit the tcp server after starting the listener, the result is always access denied).
From what i can tell, the policy file is either invalid as the silverlight application as still unable to connect or the above mentioned technique does not work with silverlight 5.
What i would like to know is if what i am doing is possible & im doing it correctly, otherwise if there is an alternative means to have the policy file successfully downloaded over tcp and removing the need for retrieving it over HTTP.
Thanks
I wrote a long post about hosting silverlight in WPF - and using WCF with a http listener here:
How can I host a Silverlight 4 application in a WPF 4 application?
Now while not directly answering your question, it does show how to create a http version of the policy file.
I have also written something that serves up a policy listener over port 943, but I can't find where I posted the source - so I'll keep digging. As far as I remember though, silverlight does a cascade find of the policy file, if it doesn't get a connection on port 80, it'll then look on port 943.
I hope this is of some help somewhere.
Ok, here is the policy listener I had for net.TCP transport i.e. not HTTP based. I presume you have sorted this by now, sorry for the delay. It may well be of use to someone else now.
I was looking for the MS thing that said they cascade from HTTP to TCP, however, I can't, and therefore have to assume it was bunk and then changed.
Either way, if you call using a net.TCP service, and want a listener for it, this code should help:
#region "Policy Listener"
// This is a simple policy listener
// that provides the cross domain policy file for silverlight applications
// this provides them with a network access policy
public class SocketPolicyListener
{
private TcpListener listener = null;
private TcpClient Client = null;
byte[] Data;
private NetworkStream netStream = null;
private string listenaddress = "";
// This could be read from a file on the disk, but for now, this gives the silverlight application
// the ability to access any domain, and all the silverlight ports 4502-4534
string policyfile = "<?xml version='1.0' encoding='utf-8'?><access-policy><cross-domain-access><policy><allow-from><domain uri='*' /></allow-from><grant-to><socket-resource port='4502-4534' protocol='tcp' /></grant-to></policy></cross-domain-access></access-policy>";
// the request that we're expecting from the client
private string _policyRequestString = "<policy-file-request/>";
// Listen for our clients to connect
public void Listen(string ListenIPAddress)
{
listenaddress = ListenIPAddress;
if (listener == null)
{
listener = new TcpListener(IPAddress.Parse(ListenIPAddress), 943);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,lo);
}
listener.Start();
WaitForClientConnect();
}
private void WaitForClientConnect()
{
listener.BeginAcceptTcpClient(new AsyncCallback(OnClientConnected), listener);
}
public void StopPolicyListener()
{
if (Client.Connected)
{
// Should never reach this point, as clients
// are closed if they request the policy
// only clients that open the connection and
// do not submit a policy request will remain unclosed
Client.Close();
}
listener.Stop();
}
public void RestartPolicyListener()
{
listener.Start();
}
// When a client connects:
private void OnClientConnected(IAsyncResult ar)
{
if (ar.IsCompleted)
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;
// End the operation and display the received data on
// the console.
Client = listener.EndAcceptTcpClient(ar);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
// Set our receive callback
Data = new byte[1024];
netStream = Client.GetStream();
netStream.BeginRead(Data, 0, 1024, ReceiveMessage, null);
}
WaitForClientConnect();
}
// Read from clients.
public void ReceiveMessage(IAsyncResult ar)
{
int bufferLength;
try
{
bufferLength = Client.GetStream().EndRead(ar);
// Receive the message from client side.
string messageReceived = Encoding.ASCII.GetString(Data, 0, bufferLength);
if (messageReceived == _policyRequestString)
{
// Send our policy file, as it's been requested
SendMessage(policyfile);
// Have to close the connection or the
// silverlight client will wait around.
Client.Close();
}
else
{
// Continue reading from client.
Client.GetStream().BeginRead(Data, 0, Data.Length, ReceiveMessage, null);
}
}
catch (Exception ex)
{
throw new Exception(Client.Client.RemoteEndPoint.ToString() + " is disconnected.");
}
}
// Send the message.
public void SendMessage(string message)
{
try
{
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
//Client.Client.Send(bytesToSend,SocketFlags.None);
Client.GetStream().Write(bytesToSend,0, bytesToSend.Length);
Client.GetStream().Flush();
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion