How to send push notifications windows phone 8 app? - windows

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.

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.

I want to send notification to certain android devices on click of a button from android devices using parse

I want to send notification to certain android devices on click of a button from android devices using parse, and i wrote this code snippet, but when i am clicking on button, the push dashboard is showing failure message as shown in screenshot:
ParseQuery userQuery = ParseUser.getQuery();
/*userQuery.whereWithinMiles("location",
currentUser.getParseGeoPoint("Location"), 1.0);*/
userQuery.whereNear("location", currentUser.getParseGeoPoint("Location"));
userQuery.setLimit(10);
userQuery.findInBackground();
// Find devices associated with these users
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereMatchesQuery("user", userQuery);
// Send push notification to query
ParsePush push = new ParsePush();
ParsePush.subscribeInBackground("Doctor");
push.setQuery(pushQuery);
push.setMessage("Only users near"
+ currentUser.getParseGeoPoint("Location")
+ " will recieve this push notification");
push.sendInBackground();
}
check userQuery.findInBackground(); call...
either try it with synchronous or try to make background (async call) with block..something like this
userQuery.findInBackground(new FindCallback<ParseObject>()
{
void done(List<ParseObject> results, ParseException e) {
if (e != null) {
// There was an error
} else {
// Find devices associated with these users
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereMatchesQuery("user", userQuery);
// Send push notification to query
ParsePush push = new ParsePush();
ParsePush.subscribeInBackground("Doctor");
push.setQuery(pushQuery);
push.setMessage("Only users near"
+ currentUser.getParseGeoPoint("Location")
+ " will recieve this push notification");
push.sendInBackground();
}
}
for further details see this link
https://parse.com/docs/android/guide#queries-queries-on-string-values

Error occuring in authenticating my weburl to windows

I have doing push notifications for my windows phone 8.1.
for getting push notifications i am trying to authenticate with WNS(windows notification service) in order to get a access token..
Here is my code..
protected async void GetAccessToken(string secret, string sid)
{
var urlSe =WebUtility.UrlEncode(secret);
var urlsId = WebUtility.UrlEncode(sid);
var body = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",urlSe ,urlsId);
Uri url1 = new Uri("https://login.live.com/accesstoken.srf" + body);
String response1;
System.Net.Http.HttpClient httpclient = new System.Net.Http.HttpClient();
using (var client = httpclient)
{
client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
System.Net.Http.HttpResponseMessage respnse = await client.GetAsync(url1);
var result =await respnse.Content.ReadAsStringAsync();
}
}
Whenever it try's to enter the "respnse" line of code it gives me a exception
A first chance exception of type 'System.InvalidOperationException' occurred in System.Net.Http.Phone.ni.DLL
I don't know what is the problem,i referred to the following link
and created this code..
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868206.aspx
Note:the code is for windows 8 phone,but i am doing for windows 8.1 phone app

I want to send mail to custom domain email provider in windows mobile application

I want to send mail from my windows mobile application.
I have configured new mail account on windows mobile emulator 6.5.3. with custom domain email provider,
Now I am able to send and receive mails with that device,And I want to send mail from my code,when the button is clicked
A code to send mail by code is available here: Sending mail in Windows mobile application in Windows
If you need more assistance, please provide more details.
EDIT: to make it more clear:
First you have to create an outlook session and specify the account to use:
public sendMail(string sMailAccount)
{
session = new OutlookSession();
//eMail = new EmailMessage();
bool bFound = false;
foreach (Account acc in session.EmailAccounts)
{
System.Diagnostics.Debug.WriteLine(acc.Name);
if (acc.Name == sMailAccount)
bFound = true;
}
if (bFound)
account = session.EmailAccounts[sMailAccount];
if (account != null)
...
The above starts a seesion and uses the provided string sMailsAccount to find an existing defined mail account. The string has to match any of the mail accounts you already have ceĀ“reated in pocket outlook.
Then, when you want to send an eMail, you use the existing session:
public bool send(string sImagePath)
{
if (account == null)
return false;
try
{
eMail = new EmailMessage();
rcp = new Recipient(_to);
eMail.To.Add(rcp);
eMail.Subject = "Visitenkarten";
eMail.BodyText = "VCard " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "\r\nsent from eMDI2Mail";
attachement = new Attachment(sImagePath);
eMail.Attachments.Add(attachement);
eMail.Send(account);
//account.Send(eMail);
if (this._syncImmediately)
{
if (this.account != null)
Microsoft.WindowsMobile.PocketOutlook.MessagingApplication.Synchronize(this.account);
}
return true;
}
...
The above code creates a new eMail, attaches a file and sends the eMail immediately or lets outlook decide, wehn to send (at a specified interval). The eMail is send immediately, if Synchronize function is used.
Makes it more clear?

Push notification fundamentals

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.

Resources