Firebase: server response does not contain a JSON object - c#

I am trying to run a ASP.NET Core API to send FCM push notifications.
The API works with Firebase SDK. The code is basically the one in the documentation:
Initialize the default app, configPath being the JSON project configuration
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(configPath), //JSON con API Key credentials
});
Example of the payload I am sending
//Send a message to the device corresponding to the provided
//registration token.
//var message = new Message()
//{
// Data = new Dictionary<string, string>()
// {
// { "score", "850" },
// { "time", "2:45" },
// },
// Token = registrationToken,
// Notification = new Notification
// {
// Body = "Test"
// }
//};
The async task I am sending
string response = await FirebaseMessaging.DefaultInstance.SendAsync(payload).ConfigureAwait(false);
Everything works OK on local (push notifications are being send), configuration seems to be alright but the deployed API running on my server returns the following error:
Server runs on Windows 10, has internet connectivity and already has other APIs (not FCM related) working fine.
As a ServiceUnavailable error I have already checked if its a Firebase problem but then again if it is Firebase problem it wouldn't work on local, right?

Related

Send notification from C# to web Cause Error Auth error from APNS or Web Push Service

I am trying to send notification to my web app using Firebase. I successfully followed the steps mentioned here to setup a JavaScript Firebase Cloud Messaging client app. Then successfully I got user approval and subscription token. Here is the code
subscribeToNotifications() {
const messaging = firebase.messaging();
messaging.requestPermission().then(function () {
console.log('have permission');
return messaging.getToken();
})
.then(function(token){
console.warn('Messaging Token: ' + token)
})
.catch(function (err) {
console.error(err);
})
}
Then I am trying to use this token to send notification from my C# console. So, here is what I did so far:
First: I generated a private key file for my service account following these steps
In the Firebase console, open Settings > Service Accounts.
Click Generate New Private Key, then confirm by clicking Generate Key.
Securely store the JSON file containing the key.
Second: I created a .net core C# console app and did the following to initialize firebase.
Installed the firebase admin package
Install-Package FirebaseAdmin -Version 1.8.0
Wrote the following code to initialize the firebase app
static void Main(string[] args)
{
FirebaseApp.Create(new AppOptions()
{
Credential =
GoogleCredential.FromFile("D:\\__\\myprojectcred.json"),
});
Console.WriteLine("Initialized");
SendMessageAsync().Wait();
}
The application successfully initialized.
However, when I tried to send the message by calling SendMessageAsync it fails in this line
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
The code is as follow:
public static async System.Threading.Tasks.Task SendMessageAsync()
{
// This registration token comes from the client FCM SDKs.
var registrationToken = "eRXeB4adi0k:APA91HGlcqh8Ow…nlrO8";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Token = registrationToken,
};
// Send a message to the device corresponding to the provided
// registration token.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
}
The error is
FirebaseMessagingException: Auth error from APNS or Web Push Service
Please help to figure out the problem.
Update:
The notification is sent to the server successfully when I tested it with Firefox client, so now the problem is with Edge browser only.

I am working on Sending push notification to android devices from C# Web app

I am Creating Application to send push notifications to Android devices using firebase and azure notification hub.
How to store RegistrationID using Push.RegisterAsync In my Code ...
Here RegistrationId is generated from firebaseinstanceID Refresh Token which is every time new So how Can I handle thatid` for sending notifications to registered devices?
var refreshedToken = FirebaseInstanceId.Instance.Token;
var templates = new JObject();
templates["genericMessage"] = new JObject
{
{ "body", templateBodyFCM }
};
var client = new MobileServiceClient(HalalApps.App.MobileServiceUrl);
var push = client.GetPush();
await push.RegisterAsync(refreshedToken, templates);

Updating trigger frequency of Azure Logic App using API

I am trying to update the recurrence frequency and interval of a Logic App using Azure Logic SDK and it is failing with this error message
Microsoft.Rest.Azure.CloudException: The request to patch workflow 'kk-test-logic-app' is not supported.
None of the fields inside the properties object can be patched.
Here is a code snippet showing what I am trying to do.
var workflow = await _client.Value.Workflows.GetAsync(resourceGroupName, workflowName);
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = triggerFrequency, interval = triggerInterval });
await _client.Value.Workflows.UpdateAsync(resourceGroupName, workflowName, workflow);
where _client is Lazy<LogicManagementClient>.
Here is the definition of the trigger I am trying to update (got using Fiddler):
"triggers": {
"When_a_new_email_arrives": {
"recurrence": {
"frequency": "Hour",
"interval": 2
},
"splitOn": "#triggerBody()?.value",
"type": "ApiConnection",
"inputs": {
"host": {
"api": {
"runtimeUrl": "https://logic-apis-southindia.azure-apim.net/apim/office365"
},
"connection": {
"name": "#parameters('$connections')['office365']['connectionId']"
}
},
"method": "get",
"path": "/Mail/OnNewEmail",
"queries": {
"folderPath": "Inbox",
"importance": "Any"
}
}
}
}
Note that I am able to successfully retrieve the workflows, workflowRuns, workflowTriggers etc. Only the update operation is failing. Any ideas on how to update properties of workflows using the SDK?
UPDATE:
As pointed out by Amor-MSFT in the comments below, this is a defect and as a workaround, I am currently using CreateOrUpdateAsync instead of UpdateAsync. A new defect has been created in GitHub to get this to the attention of the SDK development team.
The trigger currently executes every 30s checking if a new mail was received from a certain email address and is working well as expected. I'm trying to change the recurrence frequency from 30s to 2hours using the code I provided.
I created a mail trigger and I can reproduce the issue if I use invoke UpdateAsync method. According to the source code of Azure Logic C# SDK, it send a PATCH request which is not supported according the response message. After changed the HTTP method to PUT, I can update the workflow. Here is the sample code which I used to send the PUT request.
string triggerName = "When_a_new_email_arrives";
string resourceGroupName = "my resourcegroup name";
string workflowName = "my-LogicApp";
string subscriptionID = "my-subscriptionID";
var workflow = await _client.Workflows.GetAsync(resourceGroupName, workflowName);
string url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Logic/workflows/{2}?api-version=2016-06-01",
subscriptionID, resourceGroupName, workflowName);
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
message.Headers.Add("Authorization", "Bearer put your token here");
message.Headers.Add("Accept", "application/json");
message.Headers.Add("Expect", "100-continue");
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = "Minute", interval = 20 });
string s = workflow.ToString();
string workflowString = JsonConvert.SerializeObject(workflow, _client.SerializationSettings);
message.Content = new StringContent(workflowString, Encoding.UTF8, "application/json");
await client.SendAsync(message);

Bot Framework Channel Emulator has invalid channel ID?

I'm using the C# Bot Framework library to retrieve some data from the Bot State Service. Whenever channelId == "emulator" in the code below, it fails with a 400 Bad Request. It looks like both Emulator versions 3.0.0.59 and 3.5.27 use this channel ID. Here's the returned payload:
{
"error": {
"code": "BadArgument",
"message": "Invalid channel ID"
}
}
Note that if I change channelId to something else like "skype", it works as expected.
var credentials = new MicrosoftAppCredentials(id, password);
this.botState = new BotState(new StateClient(credentials));
var channelId = activity.ChannelId;
await botState.GetUserDataAsync(channelId, activity.From.Id);
Received this answer from the Bot Framework team:
For emulator they need to use the activity’s serviceurl when create the state client. Builder automatically does that in the connector client factory:
https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Library/Microsoft.Bot.Builder/ConnectorEx/IConnectorClientFactory.cs#L86
if (IsEmulator(this.address))
{
// for emulator we should use serviceUri of the emulator for storage
return new StateClient(this.serviceUri, this.credentials);
}
That error is from state.botframework.com (which is the default endpoint for stateclient) since emulator is not a valid channelid for the state service.

Push sharp - APNS Notifications not being sent

I'm currently developing an app with Telerik, and I need push notifications, I have set this up using Push Sharp in my api, gcm notifications are sending correctly to android phones, but when I run sendToiOS, iPhones do not receive APNS notifications.
I have checked using break points and can see that OnNotificationSucceeded is being called, and OnNotificationFailed is not. Which would be a good sign, however the Notifications don't seem to be coming through, I think I may have something wrong with the configuration of the APNSServiceBroker. Please note that "AppleCert" is a byte array containing the .p12 certificate for the app.
private static void sendToiOS(string deviceRegId, object notificationToSend, FERIS.Data.Model.Notification notification)
{
string json = JsonConvert.SerializeObject(notificationToSend);
Apns.QueueNotification(new ApnsNotification
{
DeviceToken = deviceRegId,
Payload = JObject.Parse(json)
});
}
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,AppleCert,"IFB_4222");
Apns = new ApnsServiceBroker(config);
Apns.OnNotificationFailed += (NotificationFailed, aggregateEx) => {
aggregateEx.Handle(ex => {
return true;
});
};
Apns.OnNotificationSucceeded += (NotificationSent) => {
Console.WriteLine("Notification Sent!");
sentTotal++;
};

Categories