Push notification fundamentals - windows-phone-7

I am trying to implement like this http://dotnettrain.blogspot.co.uk/2011/07/push-notifications-in-windows-phone-75.html
I am sending and receiving in the same page. A.xaml
The Payload I am trying to send :In GetToastPayLoad
string message = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>New Link Request</wp:Text1>" +
"<wp:Text2>"+data.Title+"</wp:Text2>" +
"</wp:Toast>" +
"</wp:Notification>";
And the header for httpRequest is :-
.........................................
var request = (HttpWebRequest)WebRequest.Create(new Uri(channelUri));
request.Method = "POST";
request.ContentType = "text/xml";
payload = GetToastPayload(data);
request.Headers.Add("X-WindowsPhone-Target", "toast");
request.Headers.Add("X-NotificationClass", "2");
}
I am able to capture the response in A.xaml as OnToastNotificationReceived and print in the details in a message box.
But when I remove the event handler, I am not getting any notification in my running application.
How can I receive and display in proper manner as a normal toast notification?
*What should I do to make this universal, say I want it to be displayed wherever the user is: A.xaml, B.xaml, C.xaml etc. ?*

To receive notifications anywhere try to put your code inside the App() constructor in App.xaml.cs as it is showed in Sending toast notifications on Windows Phone 7
Toast notifications are not showed when your app is running so you won't be able to show them this way (even if you try to manually execute ToastPrompt) So you should use ShellToastNotificationReceived to handle notifications in this case.
When your app is not running you should see toast notifications showed.

Related

What's the right way to handle message reactions in a notification only bot?

I have created a one way notification only bot in Teams (only personal scope), I am able to send proactive messages but however, when someone reacts to a message, Teams is showing a notification for the message which was reacted to. How do I prevent this behavior and just silently ignore the message reaction. I was hoping since it's a one way notification bot, there would be an option to disable it, but apparently there isn't.
I have a PHP REST API endpoint which is configured to be the bot endpoint address. This API is pretty basic and handles only certain types of requests like installationUpdate. For all other types, it just sends a HTTP 200 response with an empty body.
When the user first installs the App in teams, I am storing the conversationId, tenantId and the serviceUrl and later use these values to send notifications (proactive messages) when certain events happen in a web application. These are sent via a C# Console Application.
When a user reacts to a message, I get a request with the type messageReaction, this is where I am unable to figure out how to handle this so that the message reaction is ignored and does not cause a notification in Teams.
This is what my PHP REST API (bot endpoint) looks like
function onBotRequest() {
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
http_response_code(404);
return;
}
$requestJson = json_decode(file_get_contents('php://input'), true);
if ($requestJson['channelId'] != 'msteams') {
http_response_code(404);
return;
} elseif ($requestJson['type'] == 'installationUpdate') {
$serviceUrl = $requestJson["serviceUrl"];
$conversationId = $requestJson["conversation"]["id"];
$tenantId = $requestJson["conversation"]["tenantId"];
if ($requestJson['action'] == 'add') {
// App installed
// Store conversationId, tenantId, serviceUrl in db
} elseif($requestJson['action'] == 'remove') {
// App uninstalled
// Remove conversationId, tenantId, serviceUrl from db
}
} elseif ($requestJson['type'] == 'messageReaction') {
// What should be sent as the response here to ignore the message reaction?
}
header('Content-Type: application/json');
http_response_code(200);
}
The code used for sending proactive messages
var credentials = new MicrosoftAppCredentials(appId, appPassword);
var connectorClient = new ConnectorClient(new Uri(serviceUrl), credentials);
var response = await connectorClient.Conversations.SendToConversationAsync(conversationId, activity);
I tried sending different HTTP status codes like 400 but irrespective of the response status code, the notification still occurs. I guess I am missing some required params in the response body, but I couldn't find any documentation.
Removing the call to TeamsNotifyUser will prevent Teams sending notifications when message reactions are added/removed.

How to use the library PushSharp to send push notifications to iOS?

I am using the latest PushSharp version to send push notification through APN. I am using the below code given in their Git wiki page to send the notifications:
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration (ApnsConfiguration.ApnsServerEnvironment.Sandbox,
"push-cert.p12", "push-cert-pwd");
// 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 ();
foreach (var deviceToken in MY_DEVICE_TOKENS) {
// Queue a notification to send
apnsBroker.QueueNotification (new ApnsNotification {
DeviceToken = deviceToken,
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 ();
The confusions -
I don't know if the method apnsBroker.QueueNotification sends the push at all, or just queues it up.
I don't know if I need to install the apple certificate in some way on my Windows machine.
There is no proper sample code available online with the latest version of PushSharp.
Just fire the above code in a console application and Pushsharp will send the notifications.
Apple allow a single push token for a push notification at a time.
The code works as it. But there are some uncertain points as you said.
First notification will be send right away when you queue it, it is just a async mechanism to not to wait the code there. So if anything goes wrong (or right) you can handle it via broker's events.
Second part is a little complicated. First of all you have create a certificate for pushnotifications on a macOS machine. Than you have to upload it to your developer account etc. You can find videos how to that via google. It is pretty long to describe it here. Than you have to export your "Apple Push Services" certificate from your macOSmachine to a p12 file. And get and put that .p12 file to your .net service folder for example to "App_Data" folder and load it like (i assume you are writing a web service):
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "yourfileName.p12"),"yourFilePassword");
I hope that helps you.

How to send push notifications windows phone 8 app?

I am new in windows phone.Iam developing one app.in this app I want to send pushnotifications.how to send and receive pushnotifications in windows phone 8 using c#.please help me.
public string SendNotificationToWindows(string message, string notificationId)
{
try
{
//string subscriptionUri = "http://db3.notify.live.net/throttledthirdparty/01.00/AwYAAACKB3Noan4l%2bojXM5%2f3TDodPTegXbZxtTAzRktj3eWFOYmjjN1FPIdkuduXrwYZByFKLxy1gXy8rCmf1FSM6GH92rva7ecbQ%2b1%2bnGYxLWxoAI0GL03fZbV29p%2fu%2fJYrHQI%3d";
string subscriptionUri = "http://db3.notify.live.net/throttledthirdparty/01.00/aHR0cHM6Ly9zaW4ubm90aWZ5LndpbmRvd3MuY29tLz90b2tlbj1Bd1lBQUFEQjE1TzJMQWMlMmZBQldlUlpQendHMlglMmJRNWlPbzVUOVF3UUtXeUFQJTJic2clMmZFREhuSHM0bDBVN2tFN2prSXVJYU1hWEZIdmJYR2t6cEpQJTJiaCUyYldJSVJFTjBSd244TzJRNFV5RUs0OFJKZDdLSWJPeXVUMXFNWVNwa0Y3bmlBak5kZmslM2Q=";
//string subscriptionUri = "https://hk2.notify.windows.com/?token=AwYAAACKB3Noan4l%2bojXM5%2f3TDodPTegXbZxtTAzRktj3eWFOYmjjN1FPIdkuduXrwYZByFKLxy1gXy8rCmf1FSM6GH92rva7ecbQ%2b1%2bnGYxLWxoAI0GL03fZbV29p%2fu%2fJYrHQI%3d";
//string subscriptionUri = "http://sn1.notify.live.net/throttledthirdparty/01.00/aHR0cHM6Ly9zaW4ubm90aWZ5LndpbmRvd3MuY29tLz90b2tlbj1Bd1lBQUFEckVzRmdhR2phMXQ1aVo5MGdvRzAzejR5cE1SJTJiMHIwR2ZQc0Q0U0xzYnJOY2V3JTJmdU5pek1kZER4ZG9UdE5CM05PbjQ4dU9yUktzakN0U2JJa2lObmdBQVljQzdScDZ0blRBZlBDWjB4OWlZMDJRSDF3JTJieHM1ZzVMSTlWSXdGZWslM2Q=";
// string subscriptionUri = "https://sin.notify.windows.com/?token=AwYAAADrEsFgaGja1t5iZ90goG03z4ypMR%2b0r0GfPsD4SLsbrNcew%2fuNizMddDxdoTtNB3NOn48uOrRKsjCtSbIkiNngAAYcC7Rp6tnTAfPCZ0x9iY02QH1w%2bxs5g5LI9VIwFek%3d";
var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + message + "</wp:Text1>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (var requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
var notificationStatus = response.Headers["X-NotificationStatus"];
var notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
var rep = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
return rep;
}
catch (Exception ex)
{
return ex.ToString();
// TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
this is my service I am sending on uri to this service,but I don't know whenever came to response it will throw exeception"The remote server returned an error: (400) Bad Request."but i dont know what type of uri will give.in this uri with send one key but which type of key will send please anyone reply me
You could check out PushSharp It appears to have been updated for the new notification payload formats in Windows Phone 8. Here is the server code for sending Push Notifications from a Server and in this link you can find the implementation for the Windows Phone.
Basically, there are two types of Push notification your app may be using in Windows Phone 8.1.
MPNS: Microsoft Push Notification Service
WNS: Windows Notification Service.
MPNS is the old style notification service used in Windows Phone 7 and 8. WNS is the Windows 8 style notification which is available to Applications specifically targeting Windows Phone 8.1. (Windows Phone Silverlight 8.1 apps and Windows Phone 8.1 (Windows runtime) apps.
PushSharp appears to support both types of notification services, MPNS in the PushSharp.WindowsPhone libraries and WNS in the PushSharp.Windows libraries.
Also it might be worth checking out Azure for the same.
Here is a tutorial for the same => Send push notifications to authenticated users
Below are the steps needed for push notification for windows phone .
Your app requests a push notification URI from the Push client service.
The Push client service negotiates with the Microsoft Push Notification Service (MPNS), and MPNS returns a notification URI to the Push client service.
The Push client service returns the notification URI to your app.
Your app can then send the notification URI to your cloud service.
When your cloud service has info to send to your app, it uses the notification URI to send a push notification to MPNS.
MPNS routes the push notification to your app.
See this MSDN page to understand push notification in detail.
I tried to send notification manually with the following code:
void SendToastMessage(string pushUri, string message)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(pushUri);
request.ContentType = "text/xml";
request.Method = "POST";
request.Headers.Add("X-MessageID", Guid.NewGuid().ToString());
request.Headers.Add("X-NotificationClass", "2");
request.Headers.Add("X-WindowsPhone-Target", "toast");
string toastMessage = #"<?xml version=""1.0"" encoding=""utf-8""?>
<wp:Notification
xmlns:wp=""WPNotification"">
<wp:Toast>
<wp:Text1>{0}</wp:Text1>
<wp:Text2>{1}</wp:Text2>
</wp:Toast>
</wp:Notification>";
string toastXml = string.Format(toastMessage,
"sample:",
message);
byte[] notificationMessage = Encoding.UTF8.GetBytes(toastXml);
request.ContentLength = notificationMessage.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(notificationMessage,
0,
notificationMessage.Length);
}
try
{
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
return;
}
catch (Exception ex)
{
return;
}
}
This code worked perfectly fine to me a year earlier and it still does. But make sure your pushUri is correct.

Outbound calls with Twilio Rest Api are not executed

I'm building an application and one of the features is integrated with Twilio.
I have all the IVR flow done with Asp.Net Mvc 3 and everything is working correctly so far.
However, one of the features is to have the user input a phone number and have Twilio call that number and play something once the other user answers.
I'm using the Twilio REST API to make the call, but the call is not being done and I don't have any error on the application or on Twilio.
What I'm doing is this: I have an Action that receive the data from twilio
public ActionResult Dial(Call request, int opt)
{
var twilio = new TwilioRestClient(Configuration.TwilioAccKey, Configuration.TwilioAuthKey);
twilio.InitiateOutboundCall(Configuration.TwilioPhoneNumber,
"+" + request.Digits,
string.Format("{0}/Calls/Endorsement/Play?opt={1}", Configuration.BaseUrl, opt));
var response = new TwilioResponse();
response.Redirect("/Calls/Endorsement/Play?opt=" + opt, "GET");
return TwiML(response);
}
The response after the REST call is being executed and the outbound call doesn't throw any error.
What am I doing wrong?
Thanks!
Your code to initiate the outbound call looks correct.
Its possible that an exception is being returned from the REST API. I've changed your code to use the InitiateOutboundCall methods callback parameter to check if the RestException property is not null:
var twilio = new TwilioRestClient(Configuration.TwilioAccKey,
Configuration.TwilioAuthKey);
twilio.InitiateOutboundCall(Configuration.TwilioPhoneNumber,
"+" + request.Digits,
string.Format("{0}/Calls/Endorsement/Play?opt={1}", Configuration.BaseUrl, opt),
call =>
{
if (call.RestException != null)
{
//handle the rest error
}
}
);
If RestException is null and nothing is being logged in the Twilio debugger log, then your best option might be to break out Fiddler and see whats happening during the actual request to the API.
I had a similar problem and want to post here in case someone else finds this issue like I did. (At the time this is the only thing that shows up in a search for "InitiateOutboundCall".)
In my case no exceptions were thrown either by my app or by Twilio. The call to InitiateOutboundCall simply was not doing anything.
The docs make it clear that the URL must be absolute and I had left off the "http://". After adding this everything worked as expected.

404 error on push notification using sample code

I got my url from the app. It begins with:
http://sn1.notify.live.net/throttledthirdparty/01.00/
and if I navigate to that URL using a browser, I get the message:
Microsoft Push Notification Server
I then grabbed the code provided by Microsoft.
http://msdn.microsoft.com/en-us/library/ff402545%28v=VS.92%29.aspx
If I take the C# code, and use it as is (changing only the URL, the Payload to be an empty byte array, and changing the "" string to Guid.NewGuid().ToString()
I get a 404 every time.
Because I don't get a 404 from by browser, the content must matter, and the push notification servers are dependent on content, so if I change it to a simple raw notification by removing the notification message and adding (as they recommend):
byte[] notificationMessage = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
sendNotificationRequest.Headers.Add("X-NotificationClass", "13");
I still get a 404 every time. I've tried doing toast notifications with the same result.
What am I doing wrong?
The reason you are getting a 404 is because the notificationMessage data you are sending isn't what it's expecting. Try this out and see if it works.
You can find a tutorial here:
http://benjii.me/2011/04/push-notifications-in-windows-phone-7-3-push-that-notification/
string template =
"<?xml version='1.0' encoding='utf-8'?>" +
"<wp:notification xmlns:wp='WPNotification'>" +
"<wp:toast>" +
"<wp:text1>{0}</wp:text1>" +
"<wp:text2>{1}</wp:text2>" +
"</wp:toast>" +
"</wp:notification>";
string toastXML = string.Format(template, "Testing", "This is a test");
byte[] notificationMessage = new UTF8Encoding().GetBytes(toastXML);
I ended up getting mine to work after binding toast notifications to the shell. I had a method which did it, but under some cases wasn't calling that method.

Resources