C# Pusher Client - unable to receive any private Channel events - c#

I have an app that connects to a private Pusher channel and listens to events.
The code looks a bit like this:
// Handle Pusher.
_pusher = new Pusher(Settings.Default.PusherAppKey, new PusherOptions()
{
Cluster = Settings.Default.PusherCluster,
Encrypted = false,
Authorizer = new HttpAuthorizer("[REDACTED]")
{
AuthenticationHeader = new AuthenticationHeaderValue("Bearer", $"{TokenHelper.Token}")
}
});
await _pusher.ConnectAsync();
// This works fine - it says I am subscribed to the channel.
_pusher.Subscribed += (sender, channel1) =>
{
Debug.WriteLine("Subscribed to channel " + channel1.Name);
};
// Never any errors.
_pusher.Error += (sender, error) =>
{
Debug.WriteLine("Pusher error: " + error.Message);
};
// Ok - channel is subscribed.
var channel = await _pusher.SubscribeAsync($"private-[REDACTED]");
channel.Bind(#"App\Events\FileProcessedEvent", PusherEventListener);
It seems like I am subscribing to the channel correctly - the Subscribed event is fired, and I can see that the channel is subscribed (channel.IsSubscribed == true).
However, I am unable to receive any events, including the ones provided by Pusher:
// Never happens.
channel.Bind("pusher:subscription_succeeded", (data) =>
{
Debug.WriteLine("Subscription succeeded.");
});
// Never happens either.
channel.Bind("pusher:subscription_error", (data) =>
{
Debug.WriteLine("Subscription error.");
});
It seems that the event in question ("App\Events\FileProcessedEvent") is fired server-side, but I am unable to receive it, just like the other events. What could be the reason, and how can I fix it?
I have tried Binding the events on the Pusher instance itself, instead of channel, but I failed. I have also tried Binding to all events, but that handler was never invoked - seems like not a single event is captured.
I would also like to mentioned that the channel is authorized properly by the provided endpoint, and that the channel is subscribed with no errors.

Related

subscriber not actively receiving published message

I have successfully connected MQTT to my broker both publisher and subscriber are working fine but there is a problem my subscriber is not actively receiving the message, the function mqtt_publishedRecieved triggers only one time,when I restart the subscriber app and only one message receives at a time. in order to get another message, I have to restart my app again. Well, as per my understanding it is because I called the config method of my class at startup. so therefore It checks for the subscribed topic only at startup. But I really want that functionality in my subscriber class to immediately receive the message once it is published by the receiver, which means both should work parallel.
My requirement is
=> if subscriber is connected, receives the message as soon as publisher fires.
=> if the subscriber is disconnected, message should be queued and later on all message will receive when subscriber connected again.
I do a research mqtt clean session set to false will ensure the persistent session so I set that flag to false to occupy persistent session, but it won't work for me.
it seems to me that I should add functionality to receive a message, for example, a button, so when the button is clicked it starts to get a message, but I can't set trigger/callback/button to receive the message for the subscribed topic. My app should start receiving all the published messages when service is started and stopped when it is disconnected.
below is the code of the publisher class.
public class publisher : IDatabaseSubscription
{
public publisher()
{
_mqttClient = new MqttClient("127.0.0.1");
_mqttClient.Connect("clientId", null, null, false, 60);
}
private void MQTT_OnChanged(object sender, RecordChangedEventArgs<EventDto> e)
{
if (_mqttClient != null && _mqttClient.IsConnected)
{
var message = System.Text.Encoding.UTF8.GetBytes("Hello from app 1");
var statusCode = _mqttClient.Publish("Message1",message , MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
}
}
}
below is the code of subscriber class
public class subscriber
{
private MqttClient _mqttClient;
public subscriber()
{
}
public void configure ()
{
_mqttClient = new MqttClient("127.0.0.1");
_mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
var status = _mqttClient.Subscribe(new string[] { "Message1" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
_mqttClient.Connect("clientId", null, null , false, 60) ;
}
private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
var message = System.Text.Encoding.UTF8.GetString(e.Message);
}
}
below is the code in startup
if(IsSubscriptionEnabled())
{
var service = _container.GetInstance<subscription>();
service.configure();
}
It was due to the same client id in both publisher and subscriber, broker kicked off the client if the new client connected with the same client id.

WNS PushNotificationReceived does not intercept toast push notification

I'm writing a windows desktop app that relies on notifications to work. However, the event handler code, PushNotificationReceived on the channel does not seem to actually fire when I receive a notification. The following code is called to get the channel before its uri is sent to my server:
internal async Task<PushNotificationChannel> GetChannel()
{
PushNotificationChannel pnc;
try
{
pnc = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (_channel == null || !pnc.Uri.Equals(_channel.Uri))
{
_channel = pnc;
_channel.PushNotificationReceived += OnPushNotificationReceived;
Debug.WriteLine(_channel.Uri);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
_channel = null;
}
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
return _channel;
}
Such that anytime the channel is created or updated (via a different channel uri), it should assign the new channel's PushNotificationReceived event to the following (which is basically lifted from msdn's example):
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string typeString = String.Empty;
string notificationContent = String.Empty;
switch (e.NotificationType)
{
//
//other notification types omitted for brevity
//
case PushNotificationType.Toast:
notificationContent = e.ToastNotification.Content.GetXml();
typeString = "Toast";
// Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts:
// if your application is already on the screen, there's no need to display a toast from push notifications.
e.Cancel = true;
break;
}
Debug.WriteLine("Received notification, with payload: {0}", notificationContent);
string text = "Received a " + typeString + " notification, containing: " + notificationContent;
var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.ClearBanner();
});
}
Importantly, "MainPage.Current" is a reference to the app's main page as a static variable. The clear banner line simply removes a pink banner from the main page (just trying to get something simple working to start).
However, the code never seems to fire (no debug statement, pink banner remains). I am successfully getting the toast notification, and clicking on it will set focus to my app, so it's definitely not going to the wrong place.
Is there something I am doing wrong or some way to debug the notifications themselves?

Azure Service Bus SubscriptionClient.OnMessage always completes message when it shouldnt

I am trying to receive all messages for a given subscription to a Service Bus Topic, but for the context of this app I do not want them dead lettered at this time, I just want to view them and leave them on the subscription. Despite instantiating the Client as
SubscriptionClient sc = SubscriptionClient.CreateFromConnectionString(connectionString, sub.topicName, sub.subscriptionName, ReceiveMode.PeekLock);
and making sure that I am using message.Abandon() rather than message.Complete() the message always gets Dead-lettered after accessing the message. I also have options.AutoComplete set to false
full method code below:
public List<ServiceBusMessage> RetrieveSubscriptionMessages(Subscription sub) {
ServiceBusMessage sbm;
List<ServiceBusMessage> list = new List<ServiceBusMessage>();
String connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"].ToString();
SubscriptionClient sc = SubscriptionClient.CreateFromConnectionString(connectionString, sub.topicName, sub.subscriptionName, ReceiveMode.PeekLock);
OnMessageOptions options = new OnMessageOptions();
options.AutoComplete = false;
sc.OnMessage((message) => {
try {
sbm = new ServiceBusMessage() {
topicName = sub.topicName,
messageText = message.GetBody<String>()
};
list.Add(sbm);
message.Abandon();
}
catch (Exception) {
message.Abandon();
throw;
}
}, options);
return list;
}
Am I missing something ? Or is there an issue with auto dead-lettering with the onMessage() method?
Thanks !
When a message is abandoned the service bus will immediately make it available for re-delivery to any subscriber of the topic.
If you are trying to configure a multicast mechanism in which multiple listeners all receive the same message, then understand that all listeners on a given subscription will be competing for the same message. In order for every listener to receive its own copy of the message, then simply create a unique subscription to the topic for each listener.
If your intent is to delay re-delivery of the abandoned message, you might look at the SO question: What's the proper way to abandon an Azure SB Message so that it becomes visible again in the future in a way I can control?

using EasyNetQ multiple Handler for one consumer does not work

We are using RabbitMQ for queuing messages in C# .Net (EasyNetQ Client).
i want one consumer app (C# Console App) listen to one queue and provide multiple handlers for each message type.
I implemented this scenario and my code is here :
using (var advancedBus = RabbitHutch.CreateBus("host=localhost;prefetchcount=100")
.Advanced)
{
var queue = advancedBus.QueueDeclare("MyQueue");
advancedBus.Consume(queue, x => x
.Add<MessageType1>((message, info) =>
{
Console.WriteLine("MessageType1 Body : " + message.Body.Body);
})
.Add<MessageType2>((message, info) =>
{
Console.WriteLine(" MessageType2 Body: " + message.Body.Body);
}).ThrowOnNoMatchingHandler = false);
}
My Problem :
But when i execute this consumer it does nothing. do not any thing happen.
i publish messages to that queue like this :
using (var advancedBus = RabbitHutch.CreateBus("host=localhost").Advanced)
{
var queue = advancedBus.QueueDeclare("MyQueue");
if (advancedBus.IsConnected)
advancedBus.Publish(Exchange.GetDefault(), queue.Name, false, false,
new Message<MessageType1>(change));
else
result = false;
}
What is the problem.
Ok, after testing this code, these are the problems:
First of all, you're disposing your advancedBus right after you register for consumption. You need to remember that when you invoke IAdvanceBus.Consume, you're only registering a callback for each message. If you dispose the bus immediately after registration, your delegate can't be invoked since the connection was already closed. So, you'll to remove the using statement around the rabbit declaration (don't forget to dispose it when you're done):
var advancedBus = RabbitHutch.CreateBus("host=localhost;prefetchcount=100").Advanced
Second, the immediate flag has been deprecated and shouldn't be used, the message doesn't seem to be getting to the queue. Change Publish to:
advancedBus.Publish(Exchange.GetDefault(), queue.Name, true, false,
new Message<MessageType1>(change));
Also, if you're running this from a console application, don't forget to use Console.ReadKey so your main thread doesn't terminate.
Here's a working code sample:
static void Main()
{
var change = new MessageType1();
var advancedBus = RabbitHutch.CreateBus("host=localhost").Advanced;
ConsumeMessage(advancedBus);
var queue = advancedBus.QueueDeclare("MyQueue");
if (advancedBus.IsConnected)
{
advancedBus.Publish(Exchange.GetDefault(), queue.Name, true, false,
new Message<MessageType1>(change));
}
else
{
Console.WriteLine("Can't connect");
}
Console.ReadKey();
}
private static void ConsumeMessage(IAdvancedBus advancedBus)
{
var queue = advancedBus.QueueDeclare("MyQueue");
advancedBus.Consume(queue, registration =>
{
registration.Add<MessageType1>((message, info) =>
{
Console.WriteLine("Body: {0}", message.Body);
});
});
}

PushSharp ApplePushChannel not connecting or sending

I'm trying to upgrade from APNS-Sharp 1.0.4.4 and I'm using the current NuGet Version 2.2.1.0
After registering all events, the channel and sending a notification, nothing happens. No event fires, even if I wait for minutes. A test with GCM two weeks ago worked, just the ios side seems to have problems.
code shortened:
push = new PushBroker();
push.OnServiceException += push_OnServiceException;
// shortened.. all On* events registered here.
push.OnDeviceSubscriptionExpired += push_OnDeviceSubscriptionExpired;
push.RegisterAppleService(
new ApplePushChannelSettings(
config.Production,
config.Certificate,
config.CertPassword
)
);
...
AppleNotification anot = new AppleNotification()
.ForDeviceToken(token)
.WithTag(id);
if (alert != null) anot.WithAlert(alert);
if (sound != null) anot.WithSound(sound);
if (badge.HasValue) anot.WithBadge(badge.Value);
if (custom != null) anot.WithCustomItem("cc", new object[1] { custom });
notification = anot;
push.QueueNotification(anot);
...
Console.WriteLine("Press ENTER to stop server");
Console.ReadLine();
...
push.StopAllServices(true);
All the events write to a log if they're called, but none is called.
The Certificate works - I'm getting an error if I test it with the wrong password, none with the right.
If I try to send the same test Notification with APNS-Sharp and he same certificate/token, I receive it on the phone.
Any Ideas?

Categories