Issue with sending Notification to Windows Store app using Service bus - azure

I use Notification Hubs to send Notifications to IPhone and Windows Store app. The IPhone is working perfectly fine, but there is some issue with Windows Store when sending the notification.
Error: The Push Notification System handle for the registration is invalid.
Template:
String WindowsTemplateStr = #"<toast><visual><binding template=""ToastImageAndText03""><image id=""1"" src=""https://"" alt=""Customer""/><text id=""1"">$(headlineText)</text><text id=""2"">$(bodyText)</text></binding></visual></toast>";
I use this code to register:
registration = await hubClient.CreateWindowsTemplateRegistrationAsync(userDeviceInformation.ChannelUri, Templates.WindowsNotificationTemplate,
new string[]
{
userDeviceInformation.InstallationId,
userDeviceInformation.UserName
});
The registration goes through fine and I can see the tags properly associated using "Service Bus Explorer".
When I try to send the Notification this is what I do:
notification.Add("src", ImageUrl);
notification.Add("headlineText", String.Format("Message from {0}", fullName));
notification.Add("bodyText", String.Format("Message {0}", message));
When the notification is sent, nothing is received on the device; and I see the registration is also being deleted.
I can't seem to find what is causing this behavior.
Any ideas ?

If WNS returns invalid handle then the corresponding registration will be removed from the notification hubs.
You can use test send to check the error details:
http://msdn.microsoft.com/en-us/library/microsoft.servicebus.notifications.notificationhubclient.enabletestsend.aspx

Related

Is IoT hub message feedback absolute confirmation?

I'm working Azure Function that sends data to few devices via IoT hub. I'm trying to log whole process and I am unsure if my current solution is sufficient.
So far I'm using message feedback(as mentioned in documentation) to log if device received send message.
"The IoT hub doesn't generate a feedback message. If the cloud-to-device message reaches the Completed state, the IoT hub generates a feedback message." As I understand it if I receive said feedback it is confirmation that message was successfully/unsuccessfully received by device.
Is my understanding that this is absolute confirmation that message was or wasn't received by device correct? Or is there another option to get is confirmation?
I recommend reading through the section Receive Cloud to Device Delivery feedback for better understanding on this. The section explains how you can set the Acknowledgment feedback option. The Azure IoT Hub provides feedback in both Positive and Negative scenarios.
If you have set the message Ack to full as indicated in the article using the following code commandMessage.Ack = DeliveryAcknowledgement.Full;, you will receive a message in both Completed as well as Dead lettered scenarios (Positive and Negative outcome).
If you are specifically targeting the success messages, you would need to set the acknowledgement to Positive. The feedback you then receive is a confirmation proving that message was successfully received by device.
Hope this helps!
I followed the below steps to send a message to an IoT device using azure function.
Additional answer wrto #LeelaRajesh_Sayana.
Created a IoT hub and added the device
Add the device name and click on save
Select the device you created and click on send message
Enter the message to send
To create a particular condition, we have code it. I have used C# function time trigger to send message IoT Hub messages and added the below condition .
try
{
log.Loginformation($"Message sent : {message}");
}
catch (Exception ex)
{
log.LogError($"Error sending message :{ex.Message});
}
using System;
using Microsoft.Azure.Devices;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
namespace AzureFunctionIoT
{
public static class SendMessageToIoTDevices
{
[FunctionName("SendMessageToIoTDevices")]
public static void Run([TimerTrigger("0 0 0 * * *")]TimerInfo myTimer, ILogger log)
{
string connectionString = Environment.GetEnvironmentVariable("IoTHubConnectionString");
ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
var message = new Microsoft.Azure.Devices.Message(System.Text.Encoding.ASCII.GetBytes("Hello IoT Devices"));
serviceClient.SendAsync("<DeviceId>", message).GetAwaiter().GetResult();
log.LogInformation("Message sent successfully");
}
}
}
Run the messages with Azure IoT Hub (.NET) Code

Azure Notifcation Hub CreateOrUpdateInstallationAsync not failing but Installation not being created

I have an ASP.NET Web Api that is registering Android and iOS installations in our Azure Notification Hub. It creates a HubClient using a connection string
this.azureHub = NotificationHubClient.CreateClientFromConnectionString(
"Endpoint=sb://OUR-HUB-NS.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=tK/SEXXXXXXXXXXX/7LUtvRoNt+HjToFmP+T++yW5g=",
"OUR-HUB");
We then create an installation using this code
try
{
await azureHub.CreateOrUpdateInstallationAsync(installation, token);
}
catch(Exception e)
{
this.logger.LogError(e, "CreateOrUpdateInstallationAsync failed with" + e.Message);
return false;
}
return true;
When I had the NoticationHubClient incorrectly configured I was getting 401 errors and if I pass in nonsense for the installation data I will get a 400. Currently the call does not throw an error so I asm going to assume what I am passing is correct and it can successfully connect to the hub. However registrations are not being created. If i try and get the installation after it is created with
GetInstallationAsync(installation.InstallationId)
I get an error saying the installation cannot be found and if I try and get all registrations i get an empty list
var registrations = await azureHub.GetAllRegistrationsAsync(0);
Further confirmation that my installations are not being created is that if I use the "Test Send" in Azure Portal I get "Message was successfully sent, but there were no matching targets." for either Apple or Android platform
What is happening to my registration?
I recreated the Notification Hub with a different name, in the same namespace and everything just started working.
I then recreated the non-working hub in Azure Portal and it now all works.
All I can say is that I had previously deleted the hub using the OSS Service Bus Explorer and perhaps that deleted the hub in a way that Azure didn't like.
Not the answer I was expecting.

The Azure Alerts using webhook to Slack is not working

I'm using Azure Alerts to use webhooks. I added the webhook in the action group. The URL I used is the one from Slack.
I also added a Notification Type Email. The notification email gets triggered but I am not receiving any message in the Slack channel.
I was able to push messages to the webhooks using postman hence I know my webhook is correct. But Azure Alert is not able to trigger the webhook. I am not receiving any messages in the Slack channel.
Azure Monitor sends a notification with its own schema definition. Slack doesn't recognize it, so you cannot see any notifications in the channel. It is possible to create a Logic App or Azure Function to transform the default schema.
Here the more information about it:
https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/alerts-common-schema
Slack expect a json object when using webhooks. When sending directly from azure alert you will get bad request.
Every slack channel has an e-mail adress. You can post messages to the channel using that email in azure alerts
Anyone looking for using Slack and Azure Alerts. This seems to work fine:
...
webhook_receiver {
name = "Slack"
service_uri = "https://hooks.slack.com/services/secret"
use_common_alert_schema = false
}
Then in the scheduled query rules alert:
...
action {
action_group = [data.azurerm_monitor_action_group.actiongroup.id]
email_subject = "Disk storage at less than 10%"
custom_webhook_payload = "{ \"text\" : \"Warning: Storage has less than 10% diskspace remaining!\"}"
}

Send push notification to all registered devices with Azure Notification Hub in .NET

I'm working with Azure Notification Hub, and I want to send a push notification message to all registered device in .NET backend. But I'm not sure this way will send to all devices because I don't have the way to check the number of devices received push message.
So, how to, I can send a push message to all devices or can make sure this way is correct?
public static async Task<bool> SendBroadcast(string msg)
{
try
{
var notificationHubClient = NotificationHubClient.CreateClientFromConnectionString(ConfigurationManager.AppSettings["ServiceBusPushNotificationConnectionString"], ConfigurationManager.AppSettings["ServiceBusPushNotificationName"]);
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("message", msg);
param.Add("alert", msg);
var template = new TemplateNotification(param);
var result = await notificationHubClient.SendNotificationAsync(template);
Console.WriteLine(JsonConvert.SerializeObject(result));
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
return false;
}
}
If you don't specify any tag expression, that means it's broadcast. All devices will receive the notification. You can track how many devices are received through using Per Message Telemetry. Please see below links for same.
https://msdn.microsoft.com/en-us/library/azure/mt608135.aspx
https://azure.microsoft.com/en-us/blog/push-notification-hub-telemetry-expiry-update/
You need to use tags as described in Routing and Tag Expressions:
The only way to target specific registrations is to associate them
with a tag, then target that tag. As discussed in Registration
Management, in order to receive push notifications an app has to
register a device handle on a notification hub. Once a registration is
created on a notification hub, the application backend can send push
notifications to it. The application backend can choose the
registrations to target with a specific notification in the following
ways:
Broadcast: all registrations in the notification hub receive the
notification.
Tag: all registrations that contain the specified tag receive the
notification.
Tag expression: all registrations whose set of tags match the
specified expression receive the notification.
Note, there're limitations on broadcast messages that you need to take into account.
Take a look at the Breaking News App Sample on details about how to use broadcast notifications.

Requesting a New Registration Id and Creating a Tag for the Azure Notification Hub with NodeJs

How to get a new registration Id for the Azure Notification Hub with JavaScript (NodeJS) and how to create the tag afterwards? The tutorial provided by the Azure documentation misses this part - it sends to all devices (null).
https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-nodejs-how-to-use-notification-hubs/
var payload={
alert: 'Hello!'
};
notificationHubService.apns.send(null, payload, function(error){
if(!error){
// notification sent
}
});
Thanks!
The Notification Hub apns object also has a createNativeRegistration(token, tags, options, callback) function.
var token='abcd1234......'; // token from iOS device
var tags = ['mynewtag', 'myoldtag'];
notificationHubService.apns.createNativeRegistration(token, tags, {success:newRegistrationCompleteCallback, error:newRegistrationErrorCallback});
If you are using the npm you can read the source for it since the documentation is pretty incomplete.
If you are using Mobile Services' Node.js backend, see also the documentation for the built-in push apns object, which seems to be using the same library.

Resources