Push notification for toast not working in azure - azure

My Push notification code for toast notification is not running when run through scheduler in azure. my code is
function EWSReminder() {
push.wns.sendToastText01("https://sin.notify.windows.com/? token=Ysdfdhjkdjksj%2fAScjFHiwrUbS6y%2bvumj9sKUqhklsdfjgfdslcvl;dklslkskdlsdl;9XD58CMJebd04EknQY0Hgaxed6%uirutiuritubW%2fRcpdvapAYlMcnWLE360%3d", {
text1: "Sample toast from sample insert"
}, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse);
}
);
}
I get this error
Error in script '/scheduler/EWSReminder.js'. Error: The options.client_id and options.client_secret must be specified as strings or the WNS_CLIENT_ID and WNS_CLIENT_ID environment variables must be set.
[external code]
at EWSReminder (</scheduler/EWSReminder.js>:2:16)
at </scheduler/EWSReminder.js>:1:13
[external code]
I can't figure out what the problem is pls help. I have applied code of all the microsoft samples available all have the same code, but none is working for me.

You need to set Client Secret and Package SID in Azure Portal (Push tab in your Mobile Service). These credentials can be obtained through Windows Store Developer Portal.

Even I too have the same issue and I have put the values in the portal which I took from the Windows Store Developer Portal.
The below code works for me but the above code doesn't as shown by Yesh.
var pushWNS = require('wns');
pushWNS.sendToastText01(uri, { text1: Name }, { client_id: 'xxx', client_secret: 'xxx' },
function (error, response)
{
if (!error)
{
// success code
}
else
{
// error handling
}
});
and also I wanted to know the difference between both the codes mentioned by me and Yesh

Related

Node.JS PowerBI App Owns Data for Customers w/ Service Principal (set "config.json" from a table in my database)

I'm attempting to refactor the "Node.JS PowerBI App Owns Data for Customers w/ Service Principal" code example (found HERE).
My objective is to import the data for the "config.json" from a table in my database and insert the "workspaceId" and "reportId" values from my database into the "getEmbedInfo()" function (inside the "embedConfigServices.js" file). Reason being, I want to use different configurations based on user attributes. I am using Auth0 to login users on the frontend, and I am sending the user metadata to the backend so that I can filter the database query by the user's company name.
I am able to console.log the config data, but I am having difficulty figuring out how to insert those results into the "getEmbedInfo()" function.
It feels like I'm making a simple syntax error somewhere, but I am stuck. Here's a sample of my code:
//----Code Snippet from "embedConfigServices.js" file ----//
async function getEmbedInfo() {
try {
const url = ;
const set_config = async function () {
let response = await axios.get(url);
const config = response.data;
console.log(config);
};
set_config();
const embedParams = await getEmbedParamsForSingleReport(
config.workspaceId,
config.reportId
);
return {
accessToken: embedParams.embedToken.token,
embedUrl: embedParams.reportsDetail,
expiry: embedParams.embedToken.expiration,
status: 200,
};
} catch (err) {
return {
status: err.status,
error: err.statusText,
}
};
}
}
This is the error I am receiving on the frontend:
"Cannot read property 'get' of undefined"
Any help would be much appreciated. Thanks in advance.
Carlos
The error is because of fetching wrong URL. The problem is with the config for the Service Principal. We will need to provide reportId, workspaceId for the SPA and also make sure you added the service principal to workspace and followed all the steps from the below documentation for the service principal authentication.
References:
https://learn.microsoft.com/power-bi/developer/embedded/embed-service-principal

Unable to get the MSI credentials with NodeJs

I am working with the NodeJs Azure Function V2 and I want to get the secret from Key-Vault.
I tried with following reference. Here's a link.
I am using ms-rest-azure NPM library package.
My code as follows:
function getKeyVaultCredentials(){
return msRestAzure.loginWithAppServiceMSI({resource: "https://my-keyvault-DNS-url.vault.azure.net",msiEndpoint: process.env["MSI_ENDPOINT"],msiSecret:process.env["MSI_SECRET"]});
}
function getKeyVaultSecret(credentials) {
var keyVaultClient = new KeyVault.KeyVaultClient(credentials);
return keyVaultClient.getSecret("https://my-keyvault-DNS-url.vault.azure.net", 'secret', "mySecretName");
}
getKeyVaultCredentials().then(
getKeyVaultSecret
).then(function (secret){
console.log(`Your secret value is: ${secret.value}.`);
}).catch(function (err) {
throw (err);
});
The function call executed successfully but never getting the credential.
Note :
I have enabled the MSI identity and given access to kevault for that Azure function.
The error I am getting is as follows:
MSI: Failed to retrieve a token from "http://127.0.0.1:410056/MSI/token/?resource=https://my-keyvault-DNS-url.vault.azure.net&api-version=2017-09-01" with an error: {"ExceptionMessage":"AADSTS500011: The resource principal named https://my-keyvault-DNS-url.vault.azure.net was not found in the tenant named 6620834b-d11e-44cb-9931-2e08b6ee81cc00. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\nTrace ID: 1f25ac6c-01e0-40d8-8146-269f22d49f001\r\nCorrelation ID: 4beede0c-2e83-4bcc-944d-ba4e8ec2c6834\r\nTimestamp: 2019-03-29 02:54:40Z","ErrorCode":"invalid_resource","ServiceErrorCodes":["500011"],"StatusCode":400,"Message":null,"CorrelationId":"e6e8108d-e605-456b-8fb6-473962dcd5d678"}
I might doing some silly/blunder - please help!!
There are some subtle fixes that your code needs
resource should be set to https://vault.azure.net. This basically has to be the resource in general, not your instance as such.
The method is actually getSecret('<KEYVAULT_URI>', '<SECRET_NAME>', '<SECRET_VERSION>')
Here is how your code should look like at the end
function getKeyVaultCredentials() {
return msRestAzure.loginWithAppServiceMSI({
resource: 'https://vault.azure.net'
});
}
function getKeyVaultSecret(credentials) {
var keyVaultClient = new KeyVault.KeyVaultClient(credentials);
return keyVaultClient.getSecret(
'https://my-keyvault-DNS-url.vault.azure.net',
'mySecretName',
''
);
}
getKeyVaultCredentials()
.then(getKeyVaultSecret)
.then(function(secret) {
console.log(`Your secret value is: ${secret.value}.`);
})
.catch(function(err) {
throw err;
});

Firebase Cloud Messaging successful sendToDevice but no notification

I'm trying to write a cloud function which sends a push notification to an iOS device. The logs say that sendToDevice was successful. But my device isn't receiving any notifications. Neither Xcode nor Cloud Functions are showing any errors. How can I diagnose this problem?
My cloud function takes a registration token from the realtime database. This token is saved to the database during the didRegisterForRemoteNotificationsWithDeviceToken function in the ios app, confirming that the front end is registering for remote notifications. The app has been given permission to show notifications and the push notification capabilities have been enabled in Xcode.
This block of code comes from my cloud function (Node.js):
// This snapshot was taken from the realtime database
// Xcode logs confirmed that this function is receiving the correct key
const notificationKey = userSnapshot.child("notificationKey").val();
const payload = {
notification: {
title: 'Test Notification Title',
body: 'Test Notification Body',
sound: 'default',
badge: '1'
}
};
return admin.messaging().sendToDevice(notificationKey, payload).then(function (response) {
console.log("Successfully sent message: ", JSON.stringify(response));
return;
}).catch(function (error) {
console.log("Error sending message: ", error);
return;
});
When calling the cloud function above, the logs showed this console log (Id numbers truncated):
"Successfully sent message: {"results":[{"messageId":"0:154/* ... */"}],"canonicalRegistrationTokenCount":0,"failureCount":0,"successCount":1,"multicastId":576/* ... */}"
But my test device (iPhone 7) hasn't received any notifications. My app has the following delegate functions (Swift 4):
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("Notification will present: \(notification.request.content.userInfo)")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Notification received: \(response.notification.request.content.userInfo)")
}
Neither print statement is appearing in Xcode's output. The only relevant print statements found are the ones I included in didRegisterForRemoteNotificationsWithDeviceToken. My APNs certificate is apparently still valid and has not expired.
The issue was simply that my podfile was missing:
pod 'Firebase/Messaging'
That allowed my didReceiveRemoteNotification to receive the notification payloads from Firebase cloud function. Then once I added UNUserNotificationCenter.current().delegate = self to the AppDelegate, the UNUserNotificationCenterDelegate functions worked as intended.
Strange how the missing pod didn't give me any compiler errors.

Windows Azure node.js Push notification for Windows store 8.1 - How to use 'createRawTemplateRegistration' template?

Please explain with one example as I am getting Error: 400 - The specified resource description is invalid.
Basically, I want to update badge value. But there is no template for badge registration in WnsService API document (http://azure.github.io/azure-sdk-for-node/azure-sb/latest/WnsService.html). So, I am trying with "createRawTemplateRegistration" template to update the badge value.
Please help me on this.
You can directly use the function sendBadge() to push badge value to client devices.
Please try the following code:
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<hubname>', '<connectionstring>');
notificationHubService.wns.sendBadge(null,99,function(error,response){
if(error) console.log(error);
console.log(response);
})
Any further concern, please feel free to let me know.
update
Do you mean that you want only one template and to handle all the types of notifications including Raw, Toast, Badge? If so, I think the answer is negative. According the description http://azure.github.io/azure-sdk-for-node/azure-sb/latest/WnsService.html#createRawTemplateRegistration:
Remember that you have to specify the X-WNS-Type header
So the header option is required. And according the REST API which is invoked via this api in nodejs is Create Registration, and we can find the description:
The BodyTemplate element is mandatory, as is the X-WNS-Type header.
So we should specify the notification type for the template.
update1
This code sample works fine on my side:
var channel = '<devicetoken>';
var templateMessage = { text1: '$(message)' };
notificationHubService.wns.createRawTemplateRegistration(channel,'tag',JSON.stringify(templateMessage), {headers: { 'X-WNS-Type': 'wns/raw' }},
function (e, r) {
if (e) {
console.log(e);
} else {
console.log({
id: r.RegistrationId,
deviceToken: r.DeviceToken,
expires: r.ExpirationTime
});
}
}
)

Send RAW Azure Push Message

I'm trying to send a raw push notification message from Azure to my mobile device through an Web API. Previously I made use of a toast message and I got that working just fine, but not so much with the raw message type. This is what I've tried so far in my web API, without any success:
var jObject = new JObject
{
{
"Body", pushMessage.Body
},
{
"From", pushMessage.From
},
{
"Date", DateTime.Now.ToString(CultureInfo.InvariantCulture)
},
{
"Title", pushMessage.Title
},
{
"TargetType", pushMessage.TargetType.ToString()
}
};
Notification notification = new WindowsNotification(jObject.ToString());
notification.Headers.Add("X-WNS-Type", "wns/raw");
notification.ContentType = "application/json";
var task = Notifications.Instance.Hub.SendNotificationAsync(notification, "some tag value");
The above code never pushes the actual message. Could someone please provide me with some information regarding this. I've tried various methods described on the web, without any success.
Many thanks!
Turns out the above code works just fine - there was an issue with one of the settings in Azure ... pretty stupid mistake in the end o_O

Resources