C# moon APNS: iOS Device Did Not Receive Notification - c#

I'm a newbie in iOS development. Recently, I tried to use moon-APNS to send push notification to my device. I followed every step in arashnorouzi.wordpress.com. And when I run my program and read the log, notification was successfully sent to APNS server, but I never receive notification on my device. What is possibly wrong? Is there some setting I should do on my device or the iOS application? I only change the device token, certificate path, password at the example code. Here is my code:
var payload1 = new NotificationPayload("b8bf91fcc66016a7bf96154f3c65c6c479385df98094394c2514682152c29968", "Message", 1, "default");
payload1.AddCustom("RegionID", "IDQ10150");
var p = new List<NotificationPayload> {payload1};
var push = new PushNotification(false, "D:\\certificate\\aps_development.p12","aswin123");
var rejected = push.SendToApple(p);
foreach (var item in rejected)
{
Console.WriteLine(item);
}
Console.ReadLine();
Anyone can help me? I really appreciate your answers.

Check did you done this:
enabled Push Notification of your app in the appID
check , does you getting token while you run the application

Related

Why an installed app is not listed by Ms Graph API?

I am trying to upgrade an app which belongs to a chat. If the app is not installed, below code successfully install it:
await graph.Chats["19:7f...3#thread.v2"].InstalledApps
.Request()
.AddAsync(teamsAppInstallation);
But once the app is added, below code shows zero entries:
var installedApps = await graph.Chats["19:7f...3#thread.v2"].InstalledApps.Request().GetAsync();
I was expecting to see my app there. My target is to call Upgrade() for the app, because it should allow me to add ConversationReferences in one of the event functions (e.g. OnTurnAsync), that will allow me to send proactive message to the chat. Am I doing something wrong?
Permissions for an application are set:
TeamsAppInstallation.ReadWriteSelfForChat.All
TeamsAppInstallation.ReadWriteForUser.All
The authentication with the Graph API is done successfully, as I can create a chat, list channels etc.
https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token
data:
grant_type=client_credentials&client_id={ MS_APP_ID_ENC }&client_secret={ MS_APP_PASS_ENC }&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
I was adding the app to the chat both manually and with C# request:
var teamsAppInstallation = new TeamsAppInstallation {
AdditionalData = new Dictionary<string, object>()
{
{
"teamsApp#odata.bind", "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/0c...68/"}
}
};
var installedApp = await graph.Chats["19:7f...3#thread.v2"].InstalledApps. Request().AddAsync(teamsAppInstallation);
And the app was added. It can be used in the chat.
It turned out that I've used wrong application permissions. Even though TeamsAppInstallation.ReadWriteSelfForChat.Al is listed in the docs, I needed to add TeamsAppInstallation.ReadWriteForChat.All to make it working.

Pushsharp Apns notification error: 'InvalidToken'

I am currently working on automatic updates for Passbook (wallet) tickets and am experiencing some trouble using the Pushsharp library by Redth.
I am using a Push notification certificate from the apple developer portal.
I have tried to export my certificate as .p12, .pem and tried to use only the private key as .12 or .pem but nothing works. This is my full certificate (information is blanked out for security reasons):
https://cdn.pbrd.co/images/HUJtb7b.png
I dont have enough reputation to post images so a link is all i can provide.
var succeeded = 0;
var failed = 0;
var attempted = 0;
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, ConfigManager.CertPath + "PushCertificateV2.p12", ConfigManager.lvppass, false);
var broker = new ApnsServiceBroker(config);
broker.OnNotificationFailed += (notification, exception) =>
{
failed++;
};
broker.OnNotificationSucceeded += (notification) =>
{
succeeded++;
};
broker.Start();
attempted++;
broker.QueueNotification(new ApnsNotification
{
DeviceToken = pushtoken,
Payload = JObject.Parse("{ \"aps\" : { \"alert\" : \"Test notification\" } }")
});
broker.Stop();
The purpose is to send a push notification to the APNS and receive an answer, sadly i am only receiving the error: Apns notification error: 'InvalidToken'.
If it means my Pushtoken from the device is incorrect it would be weird because i am using the pushtoken i recieved from the iPhone and checked it multiple times to be sure.
I have tried searching for solutions on the web but have not found a working one so far, so any help would be greatly appreciated.
Thank you in advance.
Okay, for anyone having the same issues in the future, it turned out i needed to use the same certificate i use for signing the passes and updating them. And that you cannot use the sandbox APNS because all passbook tokens are production tokens.

Confirm firebase message was received

I have a c# project sending firebase messages via http post to clients having ios and android.
When clients uninstall my app their firebase device IDs are not deleted from my database unfortunately.
The next time I send a message to the device id witch corresponds to an user who uninstalled my app, of course the message is not delivered.
Is there any way to know if the message was not delivered ?
Unfortunately the response is always successful even if the message is not delivered.
My current code:
var firebaseMessage = new FirebaseMessage();
firebaseMessage.data = notificationMessages;
firebaseMessage.to = device.DeviceRegistrationId; <-- maybe this device is no longer valid
firebaseMessage.priority = "high";
firebaseMessage.notification = new ExpandoObject();
firebaseMessage.notification.title = "myApp";
firebaseMessage.notification.body = "testMessage";
firebaseMessage.notification.sound = "default";
firebaseMessage.notification.click_action = "FCM_PLUGIN_ACTIVITY";
firebaseMessage.notification.icon = "fcm_push_icon";
firebaseMessage.notification.delivery_receipt_requested= true;
var client = new HttpClient();
var appKey = "key=" + ApplicationConfig.FirebasKey;
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", appKey);
var response = await client.PostAsJsonAsync("https://fcm.googleapis.com/fcm/send", message);
return response;
When your app is uninstalled from a device, the corresponding registration token would then be invalidated by the FCM server, so any messages sent to that specific token would result to a NotRegistered response (also see my post here). In that event, you could proceed with deleting the token (or archiving it).
If your use-case intentionally wants to know if the message was received on the client side, you're gonna have to implement Delivery receipts.

Pushsharp send apple notification failed : SSL Stream Failed to Authenticate as Client

I trying to send push notification to apple devices using Pushsharp library on ASP.NET MVC project hosted on IIS.
My code :
public static void SendAppleNotification()
{
// Configuration (NOTE: .pfx can also be used here)
byte[] arr = File.ReadAllBytes("D:\\MySoftware\\pa_Dev.pem");
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
arr, "1234");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine("Apple Notification Sent!");
};
// Start the broker
apnsBroker.Start();
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = "660E4433785EFF2B2AA29D5076B039C969F1AADD839D79261328F40B08D26497",
Payload = JObject.Parse("{\"aps\":{\"badge\":7}}")
});
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
}
Notes :
1- Tried to change pem extension into p12 and same issue still occurred.
2- I tried to send push notification using https://pushtry.com/ and its working fine so issue not from certification file or password.
The issue inside pushsharp or there is configurations missing must done on my machine, Any one have idea ?
This just happened to me as of 23 July, 2019. It looks like Apple is now enforcing TLS 1.2 for the sandbox voip push notification server at
gateway.sandbox.push.apple.com - port 2195
feedback.sandbox.push.apple.com - port 2196
I found that I had to check out the latest code from https://github.com/Redth/PushSharp (master branch), build it, and then manually add a reference to the built DLLs in my project.
Previously I was incuding the NuGet PushSharp package, which is now 3 years old and hasn't been updated. If you look at the recent commits on the master branch there is some change there related to Apple and TLS, so I am certain this has fixed it.
My issue fixed by generating p12 file from pem using the below command not by renaming the file extension.
openssl pkcs12 -export -inkey sofwareKey.pem -in software_Prod.pem -out cert_key.p12
see more
https://www.paypal.com/us/selfhelp/article/how-do-i-convert-my-pem-format-certificate-to-pkcs12-as-required-by-the-java-and-.net-sdks-ts1020
may helpful to anyone.
i think the issue related to the Push Sharp so please try this solution by changeing the SSl3 to Tls in the class called ApplePushChannel.cs
and here is the change
The orginal code in the file is
stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
replace it with
stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Tls, false);
Hope this will hellp you

PushSharp:Android GCM Push Notification received without push message

I am using PushSharp library to send push notification from my application.
PushService push = new PushService();
var reg_id_d = "APA91bETd-LsqnZjA-HKrnBOY3FbEhmWchpiwuhRkiv4gUdGDuvwDRB7YURICZ131XppDAUNUBLGe_vEPkQ-JR8UaVX7Y-NCkEfastCBLIYcUoFtt5cPafeKXHywi0WGDYW33ZQqr3oy";
var project_id_d = "482885626272";
var api_key_d = "AIzaSyAbh7R5KQR3KM7W_y-yS-Ao-JNiihNz7tE"; // "AIzaSyDcKfuW77GTwA46L6sqD41YhGf2j5S8o2w";
var package_name_d = "com.get.deviceid";
push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(project_id_d, api_key_d, package_name_d));
push.QueueNotification(NotificationFactory.AndroidGcm()
.ForDeviceRegistrationId(reg_id_d)
.WithCollapseKey("NONE")
.WithJson("{\"alert\":\"Alert Text!\",\"badge\":\"1\"}"));
I am getting notification on my device but with blank message..
I have tried with sever code available in C# to send GCM push notification, but getting same problem of having blank message.
I tried using PHP to send notification. and it is working as expected. so, I am not sure what is wrong in my above code. Can anyone please help me on this?
I tried using different code available around.. but none of those were working..
finally I tried https://stackoverflow.com/a/11651066/1005741 and it works like a charm!
I encountered the same issue, where I received an empty message. My code was a bit different and i was using different libraries: the client was wrapped with phonegap pushPlugin ,and the server code is as follows :
...
// com.google.android.gcm.server.Sender.Sender(String key)‬
gcmSender = new Sender(androidAPIkey);
// com.google.android.gcm.server.Message
Message message = new Message.Builder().addData("alert", "test message" /*notif.getAlert()*/).build();
Result result = gcmSender.sendNoRetry(message, /* device token */ notif.getToken());
nr.add(result, notif.getToken());
...
The reason why my messages where empty is due to the fact that phonegap looks for "message" , "msgcnt" or "soundname" while parsing the extras from the intent. So, this was the solution in my case :
Message message = new Message.Builder().addData("message", notif.getAlert()).build();
Hope this will help someone
Change alert to message, Please see code below for your reference:
////---------------------------
//// ANDROID GCM NOTIFICATIONS
////---------------------------
////Configure and start Android GCM
////IMPORTANT: The API KEY comes from your Google APIs Console App, under the API Access section,
//// by choosing 'Create new Server key...'
//// You must ensure the 'Google Cloud Messaging for Android' service is enabled in your APIs Console
push.RegisterGcmService(new GcmPushChannelSettings("senderid", "apikey", "com.xx.m"));
//Fluent construction of an Android GCM Notification
//IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("regid")
.WithCollapseKey("score_update")
.WithJson("{\"message\":\"syy!\",\"badge\":7,\"sound\":\"sound.caf\"}")
.WithTimeToLive(108)
);

Categories

Resources